Files
pipelines/web/src/graph.js
T
alan ebf02c3bed web: gated access, anchored viewers, mobile tabs and chat colour
- serve.mjs requires a signed session cookie for every page, artifact and the
  WebSocket, with a password file, 30-day sessions, login throttling and public
  brand assets for the sign-in page.
- The diff viewer is a fixed-height top-anchored panel whose toolbar (modes,
  copy, previous, next, close as icons) is its first row; the artifact viewer is
  likewise a fixed frame so its navigation never moves.
- The audit's selected tab uses the app's normal selected surface and bottom
  accent. Sessions that were not recorded say so plainly.
- Chat code blocks are syntax-coloured; graph pinch-zoom works with two fingers
  while a single pointer still pans and clicks nodes.
- Phones always keep the destination bar (pane collapse is wide-only), with the
  destinations spread evenly and Search on the right; the list default width is
  narrower; the theme colour matches the app.
- Code-format and layout tests, plus the full browser suite, pass.
2026-10-20 02:21:51 +01:00

1579 lines
58 KiB
JavaScript

// The workflow graph (P6): a reusable, DOM-light renderer for a pipeline's
// parsed definition plus the pure maths and semantics it is built from.
//
// Mirrors the Android app one-for-one so the browser reaches parity rather than
// re-inventing the picture:
// ui/graph/WorkflowGraph.kt (layoutGraph, fitScale, clampOffset, zoomAbout,
// hitTest, nodeDisplayLabel, rankStages)
// ui/graph/GraphPalette.kt (GraphNodeKind, node fills, tonal tint)
// data/protocol/GraphSemantics.kt (outcome order, `error*`, stable edge ids)
// ui/graph/StageDetailPane.kt (the definition-only stage pane)
// ui/screens/RunGraphTab.kt (the two empty states)
//
// Two deliberate shapes:
//
// * Everything above `mount` is pure: plain data in, plain data out, no DOM.
// `node --test test/graph.test.mjs` exercises it without a browser, and the
// run-detail graph (R5) reuses the same helpers when it lands.
// * `mount` is the only DOM touchpoint: it appends semantic DOM (a viewport,
// one inline <svg> for the edges, real <button> nodes, an absolutely
// positioned label layer and a definition pane) into `container` and returns
// `{ unmount }`. Every server-provided string is written with `textContent`
// (or, for a node's accessible name, `setAttribute("aria-label", …)`); raw
// HTML is never assigned anywhere in this file.
//
// No framework, no bundler, no runtime dependency: plain ES modules.
import { Protocol, isTerminal, resolveTarget } from "./protocol.js";
import { effectiveStageType } from "./templates.js";
import { formatDuration, secondsSince } from "./runs.js";
// Re-exported so a caller (and the unit tests) can reach the shared "blank is
// the model stage" rule from the graph module it belongs to without a second
// import path drifting from templates.js.
export { effectiveStageType };
// ---------------------------------------------------------------------------
// Pan/zoom constants (WorkflowGraph.kt MIN_SCALE / MAX_SCALE / GRAPH_FIT_PADDING)
// ---------------------------------------------------------------------------
/** The smallest scale a zoom gesture may reach (`MIN_SCALE`). */
export const MIN_SCALE = 0.3;
/** The largest scale a zoom gesture may reach (`MAX_SCALE`). */
export const MAX_SCALE = 3.0;
/** Padding kept around the fitted graph, in graph-space pixels. */
export const FIT_PADDING = 24;
/**
* The least amount of the scaled graph that must stay inside the viewport on
* each axis, so a drag can never leave an empty canvas (`GRAPH_MIN_VISIBLE`).
*/
export const MIN_VISIBLE = 40;
/** A gentle zoom response: a 100px wheel delta is roughly a 16% scale change. */
const WHEEL_ZOOM_RATE = 0.0015;
/** Movement (px) before a press becomes a pan rather than a click. */
const DRAG_THRESHOLD = 4;
// ---------------------------------------------------------------------------
// Empty states (RunGraphTab.kt + the pipeline-detail analogue)
// ---------------------------------------------------------------------------
/** The run tab's empty state when the server omitted the run graph (R5). */
export const RUN_GRAPH_MISSING = "This server did not include the run graph.";
/**
* The pipeline detail's empty state when the parsed definition declares no
* stages. The template gallery has its own Android-authored analogue
* ("This template has no stages."); there is no such string for a pipeline, so
* this is the honest browser equivalent rather than an empty canvas.
*/
export const PIPELINE_GRAPH_EMPTY = "This pipeline has no stages.";
/** The pane's message when a node has no recorded stage or incoming routes. */
export const NO_NODE_DETAILS = "No details recorded for this node.";
/** The one stage-definition section's title (StageDetailPane.kt). */
export const STAGE_DEFINITION_TITLE = "Stage definition";
/** The section pane's message for a section the app does not record (R5). */
export const SECTION_NOT_RECORDED = "This section is not recorded for this stage.";
// ---------------------------------------------------------------------------
// Node/edge semantics (GraphSemantics.kt, GraphPalette.kt)
// ---------------------------------------------------------------------------
/** Ordering priority: success first, error last, everything else alphabetical. */
function outcomePriority(outcome) {
if (outcome === "success") return 0;
if (outcome === "error") return 2;
return 1;
}
/** A stage's outcomes in the app's one order (GraphSemantics.outcomes). */
export function stageOutcomes(stage) {
return Object.keys(stage?.edges ?? {}).sort((a, b) => {
const priority = outcomePriority(a) - outcomePriority(b);
if (priority !== 0) return priority;
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
}
/** The outcome label on an edge: `error*` for an implicit fallback error route. */
export function edgeLabel(stage, outcome) {
return outcome === "error" && stage?.fallback_error ? "error*" : outcome;
}
/** A node's display label: a stage keeps its key, a terminal reads Success/Failure. */
export function nodeDisplayLabel(key) {
if (key === Protocol.SUCCESS_END) return "Success";
if (key === Protocol.FAILURE_END) return "Failure";
return key;
}
/** The node label the TUI-mirroring panes use (all-caps terminals). */
export function nodeLabel(key) {
if (key === Protocol.SUCCESS_END) return "SUCCESS";
if (key === Protocol.FAILURE_END) return "FAILURE";
return key;
}
/**
* Every definition edge in stable id order, exactly like `Graph.edges()`:
* stages in declaration order, each stage's outcomes in `stageOutcomes` order,
* target resolved through `resolveTarget`, label carrying the `error*` marker.
*/
export function graphEdges(graph) {
const result = [];
for (const stage of graph?.stages ?? []) {
for (const outcome of stageOutcomes(stage)) {
const raw = (stage.edges ?? {})[outcome];
if (raw == null) continue;
result.push({
id: result.length + 1,
source: stage.key,
outcome,
target: resolveTarget(outcome, raw),
label: edgeLabel(stage, outcome),
// The parser adds `error -> #failure` when a stage declares no error
// route; that edge is the system's, not the author's.
fallback: outcome === "error" && Boolean(stage.fallback_error),
});
}
}
return result;
}
/** The kind of a node, mirroring `graphNodeKind` (GraphPalette.kt). */
export function graphNodeKind(terminal, key, type) {
if (terminal && key === Protocol.FAILURE_END) return "TerminalFailure";
if (terminal) return "TerminalSuccess";
const stageType = effectiveStageType(type);
if (stageType === "ntfy") return "Ntfy";
if (stageType === "model") return "Model";
return "Custom";
}
/** The CSS class suffix for a node kind, so fills match the app's tint roles. */
export function nodeKindClass(kind) {
switch (kind) {
case "TerminalFailure":
return "graph-node-terminal-failure";
case "TerminalSuccess":
return "graph-node-terminal-success";
case "Ntfy":
return "graph-node-ntfy";
case "Custom":
return "graph-node-custom";
default:
return "graph-node-model";
}
}
/** True for the two decisive outcomes the app emphasises (success/error). */
export function isPassFailOutcome(outcome) {
return outcome === "success" || outcome === "error";
}
/** The CSS colour variable an executed edge's stroke uses. */
export function edgeStrokeColor(outcome) {
if (outcome === "success" || outcome === "done") return "var(--ok)";
if (outcome === "error" || outcome === "failed") return "var(--bad)";
return "var(--accent)";
}
// ---------------------------------------------------------------------------
// Run-state highlighting (R5 reuses this; the definition view passes null)
// ---------------------------------------------------------------------------
function inSet(setLike, value) {
if (setLike == null) return false;
if (typeof setLike.has === "function") return setLike.has(value);
return Array.isArray(setLike) ? setLike.includes(value) : false;
}
/** True when no run is selected (definition view) or the run visited the stage. */
export function stageIsExecuted(key, runState) {
return runState == null || inSet(runState.visitedStages, key);
}
/** True when no run is selected (definition view) or the run took the route. */
export function edgeIsExecuted(edge, runState) {
if (runState == null) return true;
const route = `${edge.source}\u0000${edge.outcome}\u0000${edge.target}`;
if (inSet(runState.takenRoutes, route)) return true;
return inSet(runState.takenRoutes, edge) || inSet(runState.takenRoutes, edge.id);
}
/**
* The key of the stage a run is executing right now, else null. Only a live run
* (still `executing`) has an active stage, so a finished run never carries a
* halo or an elapsed badge. Pure: drawing, the elapsed badge and the tests share
* one definition of "active".
*/
export function activeStage(runState) {
if (runState == null || !runState.executing) return null;
const key = runState.currentStage;
return key == null || key === "" ? null : key;
}
// ---------------------------------------------------------------------------
// Pure viewport maths (WorkflowGraph.kt)
// ---------------------------------------------------------------------------
function finite(value) {
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
/**
* Uniform scale that fits `content` inside `viewport` with `padding` on every
* side, never upscaling above 1:1 and never below `MIN_SCALE`. Degenerate or
* non-finite sizes return 1 rather than dividing by zero, so no NaN/infinity
* ever reaches the transform.
*/
export function fitScale(viewport, content, padding = 0) {
const vw = finite(viewport?.width);
const vh = finite(viewport?.height);
const cw = finite(content?.width);
const ch = finite(content?.height);
const pad = finite(padding) ?? 0;
if (vw == null || vh == null || cw == null || ch == null) return 1;
const availableWidth = vw - 2 * pad;
const availableHeight = vh - 2 * pad;
if (cw <= 0 || ch <= 0 || availableWidth <= 0 || availableHeight <= 0) return 1;
return Math.max(MIN_SCALE, Math.min(1, availableWidth / cw, availableHeight / ch));
}
/**
* Bounds a pan `offset` so at least `minVisible` px of the scaled `content`
* stays inside `viewport` on each axis, i.e. `offset.x` in
* `[minVisible - content.width, viewport.width - minVisible]` (same for y), so
* panning can never leave an empty viewport. Degenerate content, an empty bound
* range or a non-finite input is returned unchanged.
*/
export function clampOffset(offset, content, viewport, minVisible = 0) {
const ox = finite(offset?.x);
const oy = finite(offset?.y);
const cw = finite(content?.width);
const ch = finite(content?.height);
const vw = finite(viewport?.width);
const vh = finite(viewport?.height);
const mv = finite(minVisible) ?? 0;
const fallback = { x: ox ?? 0, y: oy ?? 0 };
if (ox == null || oy == null || cw == null || ch == null || vw == null || vh == null) {
return fallback;
}
if (cw <= 0 || ch <= 0) return { x: ox, y: oy };
const minX = mv - cw;
const maxX = vw - mv;
const minY = mv - ch;
const maxY = vh - mv;
return {
x: minX <= maxX ? Math.min(Math.max(ox, minX), maxX) : ox,
y: minY <= maxY ? Math.min(Math.max(oy, minY), maxY) : oy,
};
}
/**
* Anchors a zoom at `centroid` so the content point under it stays put. The draw
* transform is `offset + p * scale`, so keeping the centroid's content point
* fixed gives `centroid - (centroid - offset) * (newScale / scale)`; the result
* scale is clamped to `[minScale, maxScale]`. A non-finite/non-positive
* `scale`/`zoom` (or a non-finite centroid) returns the input unchanged, so no
* NaN/infinity ever reaches the transform.
*/
export function zoomAbout(offset, scale, centroid, zoom, minScale = MIN_SCALE, maxScale = MAX_SCALE) {
const ox = finite(offset?.x);
const oy = finite(offset?.y);
const s = finite(scale);
const z = finite(zoom);
const cx = finite(centroid?.x);
const cy = finite(centroid?.y);
const unchanged = { offset: { x: ox ?? 0, y: oy ?? 0 }, scale: s ?? 1 };
if (ox == null || oy == null || s == null || z == null || cx == null || cy == null) {
return unchanged;
}
if (s <= 0 || z <= 0) return unchanged;
const newScale = Math.min(Math.max(s * z, minScale), maxScale);
const ratio = newScale / s;
return {
offset: { x: cx - (cx - ox) * ratio, y: cy - (cy - oy) * ratio },
scale: newScale,
};
}
/** Maps a viewport-space point to graph space: `(tap - offset) / scale`. */
export function toGraphPoint(tap, offset, scale) {
const s = finite(scale);
const tx = finite(tap?.x);
const ty = finite(tap?.y);
const ox = finite(offset?.x);
const oy = finite(offset?.y);
if (s == null || s === 0 || tx == null || ty == null || ox == null || oy == null) {
return { x: 0, y: 0 };
}
return { x: (tx - ox) / s, y: (ty - oy) / s };
}
/** The key of the node whose rect contains `point`, else null. */
export function hitTest(layout, point) {
const x = finite(point?.x);
const y = finite(point?.y);
if (x == null || y == null) return null;
const node = (layout?.nodes ?? []).find(
(candidate) =>
x >= candidate.x &&
x <= candidate.x + candidate.width &&
y >= candidate.y &&
y <= candidate.y + candidate.height,
);
return node ? node.key : null;
}
/** The screen-reader description of the whole graph (never colour alone). */
export function graphDescription(graph) {
const stages = graph?.stages ?? [];
if (!stages.length) return "Empty workflow graph";
const count = `${stages.length} ${stages.length === 1 ? "stage" : "stages"}`;
return `Workflow graph with ${count}. Stages can be opened for details.`;
}
// ---------------------------------------------------------------------------
// Layout (layoutGraph, WorkflowGraph.kt)
// ---------------------------------------------------------------------------
/**
* Graph-space sizes for one layout. The defaults are the app's token geometry
* (GRAPH_NODE_WIDTH/H_GAP/PAD/…) at 1x; a caller may override any of them (the
* unit tests supply a compact set).
*/
export const DEFAULT_GRAPH_METRICS = Object.freeze({
nodeWidth: 180,
nodeHeight: 76,
hGap: 60,
pad: 24,
// A lane only has to fit its 18px outcome chip plus a gap, so 34 keeps a
// dense definition's lanes from stretching the canvas to twice its height.
laneSpacing: 34,
terminalGap: 88,
trackStep: 40,
portSpacing: 20,
// Edge labels are DOM chips over the SVG, so the layout has to reserve room
// for them itself: a wide chip between two adjacent stages would otherwise
// overprint both boxes (the layered-drawing "label dummy" problem).
labelCharWidth: 6.4,
labelPadding: 10,
// The rendered chip is ~24px tall at the 11px label type, so routes that
// share a band must clear that plus a gap.
labelHeight: 24,
labelGap: 8,
});
/** The chip width a layout reserves for an outcome label (deterministic, no DOM). */
export function labelWidthFor(label, metrics = DEFAULT_GRAPH_METRICS) {
const m = { ...DEFAULT_GRAPH_METRICS, ...(metrics ?? {}) };
const text = String(label ?? "");
return Math.max(28, Math.round(text.length * m.labelCharWidth) + 16);
}
/** Centred fan for the k-th of n ports: 0, +s, -s, +2s, -2s, ... (portOffset). */
export function portOffset(index, spacing) {
if (index <= 0) return 0;
const magnitude = Math.floor((index + 1) / 2);
const sign = index % 2 === 1 ? 1 : -1;
return sign * magnitude * spacing;
}
/**
* A tiny one-dimensional allocator (SegmentAllocator): places a run at the first
* position, starting from `desired` and stepping outward by `step`, that is at
* least `eps` from every already-placed run whose cross-interval overlaps. It is
* the single mechanism that keeps two edges off the same row/column.
* Deterministic because callers allocate in stable edge-id order.
*/
function segmentAllocator(eps) {
const placed = [];
return {
allocate(desired, from, to, min, max, step) {
const start = Math.min(Math.max(desired, min), max);
const a = Math.min(from, to);
const b = Math.max(from, to);
const free = (candidate) =>
!placed.some(
(run) => Math.abs(run.position - candidate) < eps && run.lo <= b && a <= run.hi,
);
for (let k = 0; k <= 512; k += 1) {
const candidates = k === 0 ? [start] : [start + k * step, start - k * step];
for (const candidate of candidates) {
if (candidate < min || candidate > max) continue;
if (free(candidate)) {
placed.push({ position: candidate, lo: a, hi: b });
return candidate;
}
}
}
placed.push({ position: start, lo: a, hi: b });
return start;
},
};
}
/** Collapses consecutive equal points so no zero-length segment is produced. */
function collapsePoints(points) {
const result = [];
for (const point of points) {
const last = result[result.length - 1];
if (!last || last.x !== point.x || last.y !== point.y) result.push(point);
}
return result;
}
/** The polyline an edge is drawn along (routePoints, WorkflowGraph.kt). */
export function routePoints(edge) {
const raw = edge.bottomExit
? [
edge.from,
{ x: edge.from.x, y: edge.lane },
{ x: edge.to.x, y: edge.lane },
edge.to,
]
: edge.topEntry
? [
edge.from,
{ x: edge.trackX, y: edge.from.y },
{ x: edge.trackX, y: edge.lane },
{ x: edge.to.x, y: edge.lane },
edge.to,
]
: edge.across
? [
edge.from,
{ x: edge.trackX, y: edge.from.y },
{ x: edge.trackX, y: edge.lane },
{ x: edge.leadX, y: edge.lane },
{ x: edge.leadX, y: edge.to.y },
edge.to,
]
: edge.from.y === edge.to.y
? [edge.from, edge.to]
: [
edge.from,
{ x: edge.trackX, y: edge.from.y },
{ x: edge.trackX, y: edge.to.y },
edge.to,
];
return collapsePoints(raw);
}
/**
* Where an edge's outcome label sits. The preferred spot is the midpoint of the
* widest horizontal run that can actually hold the chip; a side exit with only a
* short stub would otherwise park its label on top of a forward route's label.
* When no horizontal run fits, the longest run wins, and a vertical one is
* flagged so the chip can sit beside the wire in the gap. Pure and stored on the
* layout so drawing never recomputes it.
*/
export function labelPointFor(edge, points, labelWidth = 0) {
if (points.length < 2) return { ...edge.from, vertical: false };
let bestH = null;
let bestHw = -1;
let bestV = null;
let bestVh = -1;
for (let i = 1; i < points.length; i += 1) {
const a = points[i - 1];
const b = points[i];
if (a.y === b.y) {
const width = Math.abs(b.x - a.x);
if (width > bestHw) {
bestHw = width;
bestH = [a, b];
}
} else if (a.x === b.x) {
const height = Math.abs(b.y - a.y);
if (height > bestVh) {
bestVh = height;
bestV = [a, b];
}
}
}
const fits = (run) => run != null && bestHw >= Math.max(labelWidth, 24);
if (fits(bestH)) {
return { x: (bestH[0].x + bestH[1].x) / 2, y: bestH[0].y, vertical: false };
}
if (bestV && bestVh >= bestHw) {
return { x: bestV[0].x, y: (bestV[0].y + bestV[1].y) / 2, vertical: true };
}
if (bestH) return { x: (bestH[0].x + bestH[1].x) / 2, y: bestH[0].y, vertical: false };
if (bestV) return { x: bestV[0].x, y: (bestV[0].y + bestV[1].y) / 2, vertical: true };
return { ...points[0], vertical: false };
}
/**
* Lays out a graph's nodes and edges once. Stages keep their declaration order
* on one row; `#failure` and `#success` share a lower row with Failure left of
* Success, the pair centred. Every non-forward edge gets its own lane below the
* stage row, allocated in stable edge-id order, so no two collinear runs share a
* track. Pure: no DOM, returns plain data.
*/
export function layoutGraph(graph, metrics = {}) {
const m = { ...DEFAULT_GRAPH_METRICS, ...(metrics ?? {}) };
const stages = graph?.stages ?? [];
if (!stages.length) {
return { nodes: [], edges: [], width: 0, height: 0, hasTerminal: false, laneCount: 0 };
}
const rank = new Map(stages.map((stage, index) => [stage.key, index]));
const edges = graphEdges(graph);
const hasTerminal = stages.some((stage) =>
Object.values(stage.edges ?? {}).some((target) => isTerminal(target) || target === "#"),
);
const stageCount = stages.length;
const contentLeft = m.pad + m.hGap;
const stageBottom = m.pad + m.nodeHeight;
const isForward = (edge) =>
!isTerminal(edge.target) && (rank.get(edge.target) ?? -1) === (rank.get(edge.source) ?? -2) + 1;
// A gap is as wide as its widest straight-route label plus breathing room, so
// a chip never reaches into either neighbouring box. This is the standard
// layered-drawing answer to edge labels: reserve the space up front instead of
// discovering the collision after drawing.
const gapWidths = new Array(stageCount).fill(m.hGap);
for (const edge of edges) {
if (!isForward(edge)) continue;
const targetRank = rank.get(edge.target);
if (targetRank == null) continue;
gapWidths[targetRank] = Math.max(
gapWidths[targetRank],
labelWidthFor(edge.label, m) + 2 * m.labelPadding,
);
}
const stageX = (index) => {
let x = contentLeft;
for (let i = 1; i <= index; i += 1) x += gapWidths[i] + m.nodeWidth;
return x;
};
const stageRowRight = stageX(stageCount - 1) + m.nodeWidth;
// Every non-forward edge needs its own cross lane, stacked below the stage row
// in stable edge-id order; the terminal row sits below all of them.
const laneIds = edges.filter((edge) => !isForward(edge));
const laneIndexById = new Map(laneIds.map((edge, index) => [edge.id, index]));
const laneCount = laneIds.length;
const laneY = (edge) => stageBottom + ((laneIndexById.get(edge.id) ?? 0) + 1) * m.laneSpacing;
const terminalY = stageBottom + (laneCount + 1) * m.laneSpacing + m.terminalGap;
// Terminal widths grow with their incoming-edge count so every incoming route
// gets its own top port without crowding.
const terminalWidthFor = (incoming) =>
Math.max(m.nodeWidth, incoming * m.trackStep + 4 * m.portSpacing);
const failureIncoming = hasTerminal
? edges.filter((edge) => edge.target === Protocol.FAILURE_END).length
: 0;
const successIncoming = hasTerminal
? edges.filter((edge) => edge.target === Protocol.SUCCESS_END).length
: 0;
const failureWidth = hasTerminal ? terminalWidthFor(failureIncoming) : m.nodeWidth;
const successWidth = hasTerminal ? terminalWidthFor(successIncoming) : m.nodeWidth;
const terminalPairInner = failureWidth + successWidth + m.hGap;
const width = Math.max(stageRowRight + m.hGap + m.pad, terminalPairInner + 2 * m.pad);
const nodes = stages.map((stage, index) => ({
key: stage.key,
label: nodeDisplayLabel(stage.key),
type: effectiveStageType(stage.type),
terminal: false,
x: stageX(index),
y: m.pad,
width: m.nodeWidth,
height: m.nodeHeight,
rank: index,
}));
const byKey = new Map(nodes.map((node) => [node.key, node]));
if (hasTerminal) {
const centre = width / 2;
const failureX = centre - terminalPairInner / 2;
const successX = failureX + failureWidth + m.hGap;
const failure = {
key: Protocol.FAILURE_END,
label: nodeDisplayLabel(Protocol.FAILURE_END),
type: "terminal",
terminal: true,
x: failureX,
y: terminalY,
width: failureWidth,
height: m.nodeHeight,
rank: stageCount,
};
const success = {
key: Protocol.SUCCESS_END,
label: nodeDisplayLabel(Protocol.SUCCESS_END),
type: "terminal",
terminal: true,
x: successX,
y: terminalY,
width: successWidth,
height: m.nodeHeight,
rank: stageCount,
};
nodes.push(failure, success);
byKey.set(failure.key, failure);
byKey.set(success.key, success);
}
// One shared allocator per axis so no two collinear runs overlap. Horizontal
// runs pass their x-interval, vertical runs their y-interval.
const horizontals = segmentAllocator(m.portSpacing);
const verticals = segmentAllocator(m.trackStep / 3);
const gapContaining = (x) => {
if (x < contentLeft) return [m.pad, contentLeft];
for (let gap = 1; gap < stageCount; gap += 1) {
const lo = stageX(gap - 1) + m.nodeWidth;
const hi = stageX(gap);
if (x <= hi) return [lo, hi];
}
return [stageRowRight, stageRowRight + m.hGap];
};
const gapBounds = (gap) => {
if (gap <= 0) return [m.pad, contentLeft];
if (gap >= stageCount) {
const right = stageX(stageCount - 1) + m.nodeWidth;
return [right, right + m.hGap];
}
return [stageX(gap - 1) + m.nodeWidth, stageX(gap)];
};
// Forward edges are allocated first: a straight forward route keeps a single
// horizontal segment by sharing one y between its source and target ports.
// Grouping per source (not one global index) lets a stage's own routes fan
// across its side at a spacing that keeps their two chips apart, instead of
// piling every forward edge in the definition into the same 20px band.
const forwardBySource = new Map();
for (const edge of edges) {
if (!isForward(edge)) continue;
const list = forwardBySource.get(edge.source) ?? [];
list.push(edge);
forwardBySource.set(edge.source, list);
}
const forwardY = new Map();
for (const list of forwardBySource.values()) {
const source = byKey.get(list[0].source);
if (!source) continue;
const n = list.length;
const usable = source.height - m.portSpacing;
const spacing =
n > 1 ? Math.min(Math.max(m.labelHeight + m.labelGap, m.portSpacing), usable / (n - 1)) : 0;
const first = source.y + source.height / 2 - ((n - 1) / 2) * spacing;
list.forEach((edge, index) => {
const target = byKey.get(edge.target);
if (!target) return;
const desired = first + index * spacing;
forwardY.set(
edge.id,
horizontals.allocate(
desired,
source.x + source.width,
target.x,
desired,
desired,
Math.max(spacing, m.portSpacing),
),
);
});
}
const portMin = (node) => node.y + m.portSpacing / 2;
const portMax = (node) => node.y + node.height - m.portSpacing / 2;
const parts = edges.map((edge) => {
const source = byKey.get(edge.source);
const target = byKey.get(edge.target);
if (!source || !target) return null;
const forward = isForward(edge);
const bottomExit = edge.outcome === "error" && edge.target === Protocol.FAILURE_END;
const topEntry = isTerminal(edge.target);
const across = !isTerminal(edge.target) && !forward;
const sourceRank = rank.get(edge.source) ?? 0;
const targetRank = isTerminal(edge.target) ? stageCount : (rank.get(edge.target) ?? 0);
const backEdge = !isTerminal(edge.target) && targetRank <= sourceRank;
const lane = forward ? null : laneY(edge);
let fromX;
let fromY;
if (bottomExit) {
const slot = edges
.filter(
(candidate) =>
candidate.outcome === "error" &&
candidate.target === Protocol.FAILURE_END &&
candidate.source === edge.source,
)
.findIndex((candidate) => candidate.id === edge.id);
fromX = source.x + source.width / 2 + portOffset(slot, m.portSpacing);
fromY = source.y + source.height;
} else if (forward) {
fromX = source.x + source.width;
fromY = forwardY.get(edge.id) ?? source.y + source.height / 2;
} else {
const slot = edges
.filter(
(candidate) =>
candidate.source === edge.source &&
!isForward(candidate) &&
!(candidate.outcome === "error" && candidate.target === Protocol.FAILURE_END),
)
.findIndex((candidate) => candidate.id === edge.id);
fromX = source.x + source.width;
fromY = horizontals.allocate(
source.y + source.height / 2 + portOffset(slot, m.portSpacing),
source.x + source.width,
source.x + source.width + m.hGap,
portMin(source),
portMax(source),
m.portSpacing,
);
}
let toX;
let toY;
if (forward) {
toX = target.x;
toY = forwardY.get(edge.id) ?? target.y + target.height / 2;
} else if (topEntry) {
const slot = edges
.filter((candidate) => candidate.target === edge.target)
.findIndex((candidate) => candidate.id === edge.id);
toX = target.x + target.width / 2 + portOffset(slot, m.portSpacing);
toY = target.y;
} else {
const slot = edges
.filter(
(candidate) =>
candidate.target === edge.target &&
!isTerminal(candidate.target) &&
!isForward(candidate),
)
.findIndex((candidate) => candidate.id === edge.id);
toX = target.x;
toY = horizontals.allocate(
target.y + target.height / 2 + portOffset(slot, m.portSpacing),
target.x - m.hGap,
target.x,
portMin(target),
portMax(target),
m.portSpacing,
);
}
let trackX = 0;
let leadX = 0;
if (topEntry && !bottomExit) {
const [gapLo, gapHi] = gapBounds(sourceRank + 1);
trackX = verticals.allocate(
gapLo + m.trackStep,
Math.min(fromY, lane),
Math.max(fromY, lane),
gapLo + m.trackStep / 2,
gapHi - m.trackStep / 2,
m.trackStep,
);
} else if (across) {
const [sourceGapLo, sourceGapHi] = gapBounds(sourceRank + 1);
trackX = verticals.allocate(
sourceGapLo + m.trackStep,
Math.min(fromY, lane),
Math.max(fromY, lane),
sourceGapLo + m.trackStep / 2,
sourceGapHi - m.trackStep / 2,
m.trackStep,
);
const [targetGapLo, targetGapHi] = gapBounds(targetRank);
leadX = verticals.allocate(
targetGapHi - m.trackStep,
Math.min(lane, toY),
Math.max(lane, toY),
targetGapLo + m.trackStep / 2,
targetGapHi - m.trackStep / 2,
m.trackStep,
);
} else if (!forward && fromY !== toY) {
const [gapLo, gapHi] = gapBounds(sourceRank + 1);
trackX = verticals.allocate(
gapLo + m.trackStep,
Math.min(fromY, toY),
Math.max(fromY, toY),
gapLo + m.trackStep / 2,
gapHi - m.trackStep / 2,
m.trackStep,
);
}
const layout = {
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
label: edge.label,
fallback: Boolean(edge.fallback),
from: { x: fromX, y: fromY },
to: { x: toX, y: toY },
forward,
backEdge,
across,
topEntry,
bottomExit,
sourceRank,
targetRank,
lane,
laneIndex: forward ? -1 : laneIndexById.get(edge.id) ?? -1,
trackX,
leadX,
points: [],
labelPoint: { x: 0, y: 0 },
};
layout.points = routePoints(layout);
const width = labelWidthFor(layout.label, m);
layout.labelPoint = labelPointFor(layout, layout.points, width);
if (layout.labelPoint.vertical) {
// Keep a chip on a vertical run inside its own gap, clear of both boxes.
const half = width / 2 + 2;
const [lo, hi] = gapContaining(layout.labelPoint.x);
layout.labelPoint.x = Math.min(Math.max(layout.labelPoint.x, lo + half), Math.max(lo + half, hi - half));
}
return layout;
});
const orderedEdges = parts.filter(Boolean);
const contentBottom = hasTerminal
? terminalY + m.nodeHeight
: stageBottom + (laneCount > 0 ? laneCount * m.laneSpacing : 0);
return {
nodes,
edges: orderedEdges,
width,
height: contentBottom + m.pad,
hasTerminal,
laneCount,
};
}
// ---------------------------------------------------------------------------
// The stage definition pane (StageDetailPane.kt)
// ---------------------------------------------------------------------------
/** One labelled row/block of stage detail. */
function field(label, value, options = {}) {
return { label, value, mono: Boolean(options.mono), block: Boolean(options.block) };
}
/** A config key's display label (configLabel, StageDetailPane.kt). */
export function configLabel(key) {
switch (key) {
case "provider":
return "Provider";
case "model":
return "Model";
case "retries":
return "Retries";
case "timeout":
return "Timeout";
case "budget_usd":
return "Budget (USD)";
case "budget_tokens":
return "Budget (tokens)";
case "harness":
return "Harness";
default:
return key;
}
}
/**
* The pure definition view of a stage: type, prompt, output, outcomes with their
* resolved targets, configs, tools, limits, memory and notify policy. Only
* non-blank fields are emitted, so the pane never shows an empty row.
*/
export function stageDefinitionFields(stage) {
const fields = [];
if (!stage) return fields;
fields.push(field("Type", effectiveStageType(stage.type)));
if ((stage.prompt ?? "").trim() !== "") fields.push(field("Prompt", stage.prompt, { block: true }));
if ((stage.output ?? "").trim() !== "") fields.push(field("Output", stage.output, { block: true }));
const outcomes = stageOutcomes(stage).map((outcome) => {
const target = resolveTarget(outcome, (stage.edges ?? {})[outcome] ?? "");
const label = nodeLabel(target);
const suffix = isTerminal(target) ? " (terminal)" : "";
return `${outcome} \u2192 ${label}${suffix}`;
});
if (outcomes.length) fields.push(field("Outcomes", outcomes.join("\n"), { block: true }));
for (const key of Object.keys(stage.configs ?? {}).sort()) {
const value = stage.configs[key];
if (value != null && String(value).trim() !== "") fields.push(field(configLabel(key), value));
}
const tools = stage.blocks?.tools;
if (tools != null && String(tools).trim() !== "") fields.push(field("Tools", tools, { block: true }));
const limits = stage.limits;
if (limits) {
if (Number(limits.max_visits) > 0) fields.push(field("Max visits", String(limits.max_visits)));
const on = limits.on ?? [];
if (on.length) fields.push(field("Limit on", on.join(", ")));
}
const memory = stage.memory;
if (memory && Object.keys(memory).length) {
fields.push(
field("Memory", Object.entries(memory).map(([key, value]) => `${key}: ${value}`).join("\n"), {
block: true,
}),
);
}
const notify = stage.notify;
if (notify) {
const on = notify.on ?? [];
if (on.length) fields.push(field("Notify on", on.join(", ")));
if ((notify.destination ?? "").trim() !== "") {
fields.push(field("Notify destination", notify.destination));
}
const artifacts = notify.artifacts ?? [];
if (artifacts.length) fields.push(field("Notify artifacts", artifacts.join(", ")));
}
return fields;
}
/** Incoming routes into a terminal node, for the pane opened on a terminal. */
export function terminalFields(graph, key) {
const lines = graphEdges(graph)
.filter((edge) => edge.target === key)
.map((edge) => `${edge.source} \u00b7 ${edge.label} \u2192 ${nodeLabel(key)}`);
return lines.length ? [field("Incoming routes", lines.join("\n"), { block: true })] : [];
}
// ---------------------------------------------------------------------------
// The DOM renderer
// ---------------------------------------------------------------------------
const SVG_NS = "http://www.w3.org/2000/svg";
let markerSeq = 0;
function svgEl(tag, attrs = {}) {
const node = document.createElementNS(SVG_NS, tag);
for (const [key, value] of Object.entries(attrs)) {
if (value == null) continue;
node.setAttribute(key, String(value));
}
return node;
}
function el(tag, className, textValue) {
const node = document.createElement(tag);
if (className) node.className = className;
if (textValue != null) node.textContent = textValue;
return node;
}
function pathFromPoints(points) {
return points.map((point, index) => `${index === 0 ? "M" : "L"}${point.x},${point.y}`).join(" ");
}
/**
* Mounts a pannable, zoomable, tappable workflow graph into `container`.
*
* Pure helper reuse: the layout is computed once here (never per frame); pan and
* zoom only rewrite the content layer's single CSS `transform`. Clicking a node
* opens the definition pane (and calls `options.onStageTap(key)`); clicking empty
* space does nothing.
*
* Options:
* runState — omitted for the definition view (every route executed and
* no legend); R5 passes the `runGraphState(run)` shape
* ({ visitedStages, takenRoutes, currentStage, executing,
* currentStageStartedAt }) to render the run: executed nodes
* solid, unvisited ones hollow/dashed, executed routes
* arrowed, the live stage's halo + elapsed badge and the
* Executed / Not executed legend.
* animationsEnabled — honour the caller's animation gate. Defaults to the
* page's `prefers-reduced-motion` setting; when false the
* active stage keeps a static ring instead of pulsing.
* expanded — start with the taller panel.
* selectedKey — open the definition pane for this node at mount (the
* deep-linked stage route) without a synthetic click.
* onSelectionChange — called with the selected node key, or null when the pane
* closes, after the in-graph selection changes. The caller
* records the URL; it must not rebuild the graph to do so.
* onStageTap — called with the node key on a node click. When supplied
* (the run tab), the click opens the caller's own stage
* pane and no definition pane is drawn.
* onExpandedChange — called with the new expanded flag on toggle.
* metrics — layout metrics override (tests).
*
* Returns `{ unmount }`; call it before discarding the container so the wheel,
* pointer, resize and elapsed-timer handles never leak.
*/
export function mount(container, graph, options = {}) {
const runState = options.runState ?? null;
const activeKey = activeStage(runState);
const reducedMotion =
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// The caller may force animations off; otherwise the page's motion preference
// decides. A finished run never animates regardless (activeKey is null then).
const animationsEnabled =
options.animationsEnabled === undefined ? !reducedMotion : Boolean(options.animationsEnabled);
const pulse = activeKey != null && animationsEnabled;
const layout = layoutGraph(graph, options.metrics);
const stagesByKey = new Map((graph?.stages ?? []).map((stage) => [stage.key, stage]));
const state = {
scale: 1,
offset: { x: 0, y: 0 },
userAdjusted: false,
expanded: Boolean(options.expanded),
selectedKey: null,
};
const root = el("section", "graph-panel");
if (state.expanded) root.classList.add("expanded");
const viewport = el("div", "graph-viewport");
viewport.setAttribute("role", "group");
viewport.setAttribute("aria-label", graphDescription(graph));
const content = el("div", "graph-content");
content.style.transformOrigin = "0 0";
content.style.width = `${layout.width}px`;
content.style.height = `${layout.height}px`;
// Edge layer: one inline <svg> with a single arrowhead marker per mount.
const markerId = `graph-arrow-${(markerSeq += 1)}`;
const svg = svgEl("svg", {
class: "graph-edges",
width: layout.width,
height: layout.height,
viewBox: `0 0 ${layout.width} ${layout.height}`,
});
const defs = svgEl("defs");
const marker = svgEl("marker", {
id: markerId,
class: "graph-arrowhead",
markerWidth: 8,
markerHeight: 8,
refX: 6,
refY: 3,
orient: "auto",
markerUnits: "strokeWidth",
});
marker.append(svgEl("path", { d: "M0,0 L6,3 L0,6 z" }));
defs.append(marker);
svg.append(defs);
const pathsById = new Map();
for (const edge of layout.edges) {
if (edge.points.length < 2) continue;
const executed = edgeIsExecuted(edge, runState);
const kind = edge.fallback ? "fallback" : executed ? "executed" : "not-executed";
const path = svgEl("path", {
class: `graph-edge-path ${kind}`,
d: pathFromPoints(edge.points),
"data-edge-id": edge.id,
"data-outcome": edge.outcome,
fill: "none",
});
path.style.stroke = executed || edge.fallback ? edgeStrokeColor(edge.outcome) : "var(--muted)";
if (executed || edge.fallback) path.setAttribute("marker-end", `url(#${markerId})`);
pathsById.set(edge.id, path);
svg.append(path);
}
content.append(svg);
// Label layer: the outcome chips, so a neighbouring edge never crosses one.
// In a RUN, label only the routes that actually happened: every stage declares
// error/blocked/retry outcomes too, and labelling all of them buried the graph
// under a wall of chips. A definition (no runState) still labels every route.
const labelLayer = el("div", "graph-label-layer");
const chipsById = new Map();
for (const edge of layout.edges) {
if (runState && !edgeIsExecuted(edge, runState)) continue;
const chipClass = [
"graph-edge-label",
edge.fallback ? "fallback" : "",
edge.labelPoint.vertical ? "vertical" : "",
].filter(Boolean).join(" ");
const chip = el("span", chipClass, edge.label);
chip.style.left = `${edge.labelPoint.x}px`;
chip.style.top = `${edge.labelPoint.y}px`;
chip.setAttribute("data-outcome", edge.outcome);
chip.setAttribute("data-edge-id", edge.id);
chipsById.set(edge.id, chip);
labelLayer.append(chip);
}
content.append(labelLayer);
// Hovering either the wire or its chip lights the pair and dims the rest, so a
// route is traceable through the crossing lanes without following every bend.
function setEdgeHot(id, hot) {
pathsById.get(id)?.classList.toggle("hot", hot);
chipsById.get(id)?.classList.toggle("hot", hot);
svg.classList.toggle("has-hot", hot);
labelLayer.classList.toggle("has-hot", hot);
}
for (const [id, path] of pathsById) {
path.addEventListener("pointerenter", () => setEdgeHot(id, true));
path.addEventListener("pointerleave", () => setEdgeHot(id, false));
const chip = chipsById.get(id);
if (!chip) continue;
chip.addEventListener("pointerenter", () => setEdgeHot(id, true));
chip.addEventListener("pointerleave", () => setEdgeHot(id, false));
}
// Node layer: real buttons, positioned in graph space.
const nodeLayer = el("div", "graph-node-layer");
let elapsedBadge = null;
for (const node of layout.nodes) {
const kind = graphNodeKind(node.terminal, node.key, stagesByKey.get(node.key)?.type);
const button = el("button", `graph-node ${nodeKindClass(kind)}`, node.label);
button.type = "button";
button.style.left = `${node.x}px`;
button.style.top = `${node.y}px`;
button.style.width = `${node.width}px`;
button.style.height = `${node.height}px`;
button.dataset.key = node.key;
button.setAttribute(
"aria-label",
node.terminal
? `${node.label}, open details`
: `Stage ${node.key}, ${node.type}, open details`,
);
const executed = stageIsExecuted(node.key, runState);
if (runState != null) button.classList.add(executed ? "executed" : "not-executed");
if (node.key === activeKey) {
button.classList.add("active");
if (pulse) button.classList.add("pulsing");
const badge = el("span", "graph-elapsed");
badge.setAttribute("aria-hidden", "true");
button.append(badge);
elapsedBadge = badge;
}
button.addEventListener("click", (event) => {
if (dragged) {
event.preventDefault();
return;
}
// The run tab owns its own stage pane (the shared timeline visit pane), so
// a supplied handler replaces the definition pane rather than stacking on it.
if (typeof options.onStageTap === "function") options.onStageTap(node.key);
else selectNode(node.key);
});
nodeLayer.append(button);
}
content.append(nodeLayer);
viewport.append(content);
// Controls, pinned top-end: Fit re-arms the auto-fit; expand grows the panel.
const controls = el("div", "graph-controls");
const fitButton = el("button", "graph-control", "Fit graph to view");
fitButton.type = "button";
fitButton.setAttribute("aria-label", "Fit graph to view");
const expandButton = el(
"button",
"graph-control",
state.expanded ? "Collapse graph" : "Expand graph",
);
expandButton.type = "button";
expandButton.setAttribute("aria-label", expandButton.textContent);
controls.append(fitButton, expandButton);
viewport.append(controls);
// The legend: a solid, arrowed swatch means "executed", a dashed, arrowless
// one "not executed", and a dotted one a system-added fallback (the parser's
// implicit `error -> #failure`). A definition shows only the fallback key.
const legendEntries = runState != null
? [
{ label: "Executed", kind: "executed" },
{ label: "Not executed", kind: "not-executed" },
]
: [];
if (layout.edges.some((edge) => edge.fallback)) {
legendEntries.push({ label: "System fallback", kind: "fallback" });
}
if (legendEntries.length > 0) {
const legend = el("div", "graph-legend");
legend.setAttribute("role", "note");
legend.setAttribute("aria-label", "Route kinds");
for (const entry of legendEntries) {
const item = el("span", "graph-legend-entry");
item.append(el("span", `graph-legend-swatch ${entry.kind}`));
item.append(el("span", "graph-legend-label", entry.label));
legend.append(item);
}
viewport.append(legend);
}
// The definition pane, hidden until a node is clicked (definition view only;
// the run tab opens its own pane through onStageTap instead).
const pane = el("div", "graph-pane");
pane.hidden = true;
root.append(viewport, pane);
container.replaceChildren(root);
function viewportSize() {
return { width: viewport.clientWidth, height: viewport.clientHeight };
}
function scaledContent() {
return { width: layout.width * state.scale, height: layout.height * state.scale };
}
function applyTransform() {
content.style.transform = `translate(${state.offset.x}px, ${state.offset.y}px) scale(${state.scale})`;
}
function fit() {
const size = viewportSize();
if (size.width <= 0 || size.height <= 0 || layout.width <= 0 || layout.height <= 0) return;
const contentBox = { width: layout.width, height: layout.height };
const scale = fitScale(size, contentBox, FIT_PADDING);
state.scale = scale;
const scaled = { width: contentBox.width * scale, height: contentBox.height * scale };
state.offset = clampOffset(
{ x: (size.width - scaled.width) / 2, y: (size.height - scaled.height) / 2 },
scaled,
size,
MIN_VISIBLE,
);
state.userAdjusted = false;
applyTransform();
}
// --- Pane ----------------------------------------------------------------
function renderField(view, spec) {
if (spec.block) {
const block = el("div", "graph-field graph-field-block");
block.append(el("span", "graph-field-label", spec.label));
const pre = el("pre", "graph-block", spec.value);
pre.tabIndex = 0;
block.append(pre);
view.append(block);
return;
}
const row = el("div", "graph-field");
row.append(el("span", "graph-field-label", spec.label));
row.append(el("span", `graph-field-value${spec.mono ? " monospace" : ""}`, spec.value));
view.append(row);
}
function selectNode(key, { notify = true } = {}) {
state.selectedKey = key;
const node = layout.nodes.find((candidate) => candidate.key === key) ?? null;
const stage = stagesByKey.get(key) ?? null;
const children = [];
const head = el("div", "graph-pane-head");
const title = el("h3", "graph-pane-title", node ? node.label : key);
const type = el("span", "graph-type-chip", stage ? effectiveStageType(stage.type) : "terminal");
head.append(title, type);
const close = el("button", "graph-pane-close", "Close");
close.type = "button";
close.addEventListener("click", () => closePane());
head.append(close);
children.push(head);
const fields = stage ? stageDefinitionFields(stage) : terminalFields(graph, key);
if (!fields.length) {
children.push(el("p", "muted graph-pane-empty", NO_NODE_DETAILS));
} else {
const section = el("div", "graph-section");
const toggle = el("button", "graph-section-toggle");
toggle.type = "button";
toggle.append(
el("span", "chevron", "\u25be"),
el("span", null, STAGE_DEFINITION_TITLE),
);
const body = el("div", "graph-section-body");
for (const spec of fields) renderField(body, spec);
toggle.addEventListener("click", () => {
const collapsed = body.hidden = !body.hidden;
toggle.firstChild.textContent = collapsed ? "\u25b8" : "\u25be";
});
section.append(toggle, body);
children.push(section);
}
pane.replaceChildren(...children);
pane.hidden = false;
if (notify && typeof options.onSelectionChange === "function") {
options.onSelectionChange(state.selectedKey);
}
}
/** Close the definition pane, telling the caller so it can restore the URL. */
function closePane({ notify = true } = {}) {
pane.hidden = true;
pane.replaceChildren();
state.selectedKey = null;
if (notify && typeof options.onSelectionChange === "function") {
options.onSelectionChange(null);
}
}
// --- Elapsed badge (live run only) ---------------------------------------
function updateElapsed() {
if (!elapsedBadge) return;
const seconds = secondsSince(runState?.currentStageStartedAt, Date.now());
elapsedBadge.textContent = seconds == null ? "" : formatDuration(seconds);
}
let elapsedTimer = null;
if (elapsedBadge != null) {
updateElapsed();
// Tick only while the graph has a live stage with a known start; a still
// ring (reduced motion) and a finished run never wake up once a second.
if (
pulse &&
typeof setInterval === "function" &&
String(runState?.currentStageStartedAt ?? "").trim() !== ""
) {
elapsedTimer = setInterval(updateElapsed, 1000);
}
}
// --- Interactions --------------------------------------------------------
let dragged = false;
let pointerId = null;
let dragOrigin = null;
let lastPoint = null;
const pointers = new Map();
let pinch = null;
function onPointerDown(event) {
if (event.button !== 0) return;
// No pointer capture: capturing retargeted the following click to the
// viewport and swallowed node taps. A pinch that leaves the canvas simply
// stops updating until the fingers return.
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const rect = viewport.getBoundingClientRect();
pinch = {
distance: Math.hypot(a.x - b.x, a.y - b.y),
scale: state.scale,
lastCentroid: {
x: (a.x + b.x) / 2 - rect.left,
y: (a.y + b.y) / 2 - rect.top,
},
};
dragged = true;
pointerId = null;
dragOrigin = null;
lastPoint = null;
return;
}
if (pointers.size > 2) return;
dragged = false;
pointerId = event.pointerId;
dragOrigin = { x: event.clientX, y: event.clientY };
lastPoint = { x: event.clientX, y: event.clientY };
}
function onPointerMove(event) {
if (pointers.has(event.pointerId)) {
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
}
if (pointers.size >= 2 && pinch) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinch.distance <= 0 || distance <= 0) return;
const rect = viewport.getBoundingClientRect();
const centroid = {
x: (a.x + b.x) / 2 - rect.left,
y: (a.y + b.y) / 2 - rect.top,
};
const target = Math.min(
Math.max(pinch.scale * (distance / pinch.distance), MIN_SCALE),
MAX_SCALE,
);
const zoomed = zoomAbout(
state.offset,
state.scale,
centroid,
target / state.scale,
MIN_SCALE,
MAX_SCALE,
);
const dx = centroid.x - pinch.lastCentroid.x;
const dy = centroid.y - pinch.lastCentroid.y;
state.scale = zoomed.scale;
state.offset = clampOffset(
{ x: zoomed.offset.x + dx, y: zoomed.offset.y + dy },
scaledContent(),
viewportSize(),
MIN_VISIBLE,
);
pinch.lastCentroid = centroid;
state.userAdjusted = true;
applyTransform();
return;
}
if (pointerId === null || event.pointerId !== pointerId || !lastPoint) return;
if (!dragged) {
const moved =
Math.abs(event.clientX - dragOrigin.x) + Math.abs(event.clientY - dragOrigin.y);
if (moved < DRAG_THRESHOLD) return;
dragged = true;
}
const dx = event.clientX - lastPoint.x;
const dy = event.clientY - lastPoint.y;
lastPoint = { x: event.clientX, y: event.clientY };
state.userAdjusted = true;
state.offset = clampOffset(
{ x: state.offset.x + dx, y: state.offset.y + dy },
scaledContent(),
viewportSize(),
MIN_VISIBLE,
);
applyTransform();
}
function onPointerUp(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinch = null;
if (pointerId !== null && event.pointerId !== pointerId) return;
pointerId = null;
dragOrigin = null;
lastPoint = null;
// After a pinch, continue with the finger still down as a pan.
if (pointers.size === 1) {
const [id, point] = [...pointers.entries()][0];
pointerId = id;
dragOrigin = { ...point };
lastPoint = { ...point };
}
}
function onWheel(event) {
if (layout.width <= 0 || layout.height <= 0 || !event.deltaY) return;
event.preventDefault();
const rect = viewport.getBoundingClientRect();
const centroid = { x: event.clientX - rect.left, y: event.clientY - rect.top };
const zoomed = zoomAbout(
state.offset,
state.scale,
centroid,
Math.exp(-event.deltaY * WHEEL_ZOOM_RATE),
MIN_SCALE,
MAX_SCALE,
);
state.scale = zoomed.scale;
state.userAdjusted = true;
state.offset = clampOffset(zoomed.offset, scaledContent(), viewportSize(), MIN_VISIBLE);
applyTransform();
}
function onFit() {
state.userAdjusted = false;
fit();
}
function onToggleExpanded() {
state.expanded = !state.expanded;
root.classList.toggle("expanded", state.expanded);
expandButton.textContent = state.expanded ? "Collapse graph" : "Expand graph";
expandButton.setAttribute("aria-label", expandButton.textContent);
if (typeof options.onExpandedChange === "function") options.onExpandedChange(state.expanded);
fit();
}
viewport.addEventListener("pointerdown", onPointerDown);
viewport.addEventListener("pointermove", onPointerMove);
viewport.addEventListener("pointerup", onPointerUp);
viewport.addEventListener("pointercancel", onPointerUp);
viewport.addEventListener("wheel", onWheel, { passive: false });
fitButton.addEventListener("click", onFit);
expandButton.addEventListener("click", onToggleExpanded);
const resizeObserver =
typeof ResizeObserver === "function"
? new ResizeObserver(() => {
if (!state.userAdjusted) fit();
})
: null;
resizeObserver?.observe(viewport);
// Fit immediately when the viewport already has a size; the observer covers
// the (usual) case where the host is attached after mount, and a frame
// fallback makes sure the very first paint is already fitted.
applyTransform();
fit();
if (typeof requestAnimationFrame === "function") {
requestAnimationFrame(() => {
if (!state.userAdjusted) fit();
});
}
// A deep-linked stage opens its pane after the graph is mounted, without a
// synthetic click and without notifying the caller (the URL already says so).
// Bring the pane itself into view: the graph is tall, so a deep link that only
// revealed the pane's header below the fold would not show the stage.
if (options.selectedKey != null) {
const key = String(options.selectedKey);
if (layout.nodes.some((node) => node.key === key)) {
selectNode(key, { notify: false });
// The pane is still detached while the caller builds the detail, so reveal
// it on the next frame, once renderContent has put it in the document. The
// detail's own `.pane-scroll` is the only scroller in the shell: move it,
// never the never-scrolling document.
const reveal = () => {
if (typeof pane.getBoundingClientRect !== "function") return;
const scroller = pane.closest(".pane-scroll");
if (scroller) {
const top =
pane.getBoundingClientRect().top -
scroller.getBoundingClientRect().top +
scroller.scrollTop -
12;
scroller.scrollTop = Math.max(0, top);
return;
}
const top = pane.getBoundingClientRect().top + (window.scrollY ?? 0) - 12;
window.scrollTo?.({ top: Math.max(0, top), behavior: "instant" });
};
if (typeof requestAnimationFrame === "function") requestAnimationFrame(reveal);
else reveal();
}
}
return {
unmount() {
if (elapsedTimer != null) {
clearInterval(elapsedTimer);
elapsedTimer = null;
}
resizeObserver?.disconnect();
viewport.removeEventListener("pointerdown", onPointerDown);
viewport.removeEventListener("pointermove", onPointerMove);
viewport.removeEventListener("pointerup", onPointerUp);
viewport.removeEventListener("pointercancel", onPointerUp);
viewport.removeEventListener("wheel", onWheel);
fitButton.removeEventListener("click", onFit);
expandButton.removeEventListener("click", onToggleExpanded);
container.replaceChildren();
state.selectedKey = null;
},
};
}