Draw workflow-graph edges as straight runs and give the graph a bigger panel

A user reading the graph on their phone said it was not clear what happened, and
asked for the TUI's straight arrows and a larger panel.

- Edges are now axis-aligned orthogonal polylines instead of Bezier curves: the
  stage-to-stage runs and the routes into the bottom-row #success/#failure
  terminals are horizontal/vertical segments joined at right angles, matching the
  Go TUI's routing, and every arrowhead now points along the direction of its
  final segment instead of the straight source-to-target chord (which pointed
  wrongly as soon as a route turned a corner). Routing is a pure function.
- The graph panel is a sensible share of the window height on both screens
  instead of 360dp/340dp, and a new expand/collapse control beside 'Fit graph to
  view' grows it to nearly the full height.

Verified: :app:assembleDebug and :app:testDebugUnitTest succeed offline with 42
tests and 0 failures (WorkflowGraphTest 15 to 23, covering the orthogonal routing
and arrowhead direction), and the app was driven on the emulator with before/after
screenshots of a pipeline graph, a run graph with the executed route highlighted,
a panned state and the expanded panel.
This commit is contained in:
2026-10-15 02:34:15 +01:00
parent 8adc6b8080
commit 1a890d8c31
5 changed files with 352 additions and 54 deletions
@@ -1,13 +1,20 @@
package net.awan.pipelines.ui.graph
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FitScreen
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.FullscreenExit
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -18,6 +25,8 @@ import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -31,6 +40,7 @@ import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@@ -39,10 +49,12 @@ import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.abs
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.GraphRoute
@@ -77,6 +89,9 @@ internal data class EdgeLayout(
// there are, so each label can get its own row instead of overprinting.
val labelSlot: Int,
val labelCount: Int,
// The axis-aligned polyline this edge is drawn along, computed once by
// [routePoints] during layout so drawing never re-routes per frame.
val points: List<Offset> = emptyList(),
)
internal data class GraphLayout(
@@ -95,6 +110,7 @@ internal data class GraphLayout(
* When [runState] is supplied, executed stages/routes are highlighted and the
* rest dimmed; when it is null the full definition is shown.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WorkflowGraph(
graph: Graph,
@@ -103,7 +119,13 @@ fun WorkflowGraph(
selectedStage: String? = null,
) {
val density = LocalDensity.current
val configuration = LocalConfiguration.current
val textMeasurer = rememberTextMeasurer()
// The panel lives inside the screens' scrolling column, so growing it just
// extends it downwards below the fold. This lets an expand scroll the panel
// back into view instead of leaving the graph off-screen.
val bringIntoView = remember { BringIntoViewRequester() }
val scope = rememberCoroutineScope()
val layout = remember(graph, density) {
with(density) { layoutGraph(graph, this) }
}
@@ -147,6 +169,8 @@ fun WorkflowGraph(
// reset affordance below clears this and re-applies the fit transform.
var userAdjusted by remember { mutableStateOf(false) }
var fitRequest by remember { mutableIntStateOf(0) }
// Survives recomposition/rotation so a panel the user opened stays open.
var expanded by rememberSaveable { mutableStateOf(false) }
// Fit the whole graph into the viewport on first layout and whenever the
// viewport itself changes size, unless the user has taken over the view.
@@ -172,6 +196,18 @@ fun WorkflowGraph(
Box(
modifier = modifier
// Let an expand scroll the (now taller) panel back into the visible
// viewport of the enclosing scrolling column.
.bringIntoViewRequester(bringIntoView)
// The shared panel height lives here so both screens get the same
// size; the caller only supplies width/layout modifiers.
.height(
if (expanded) {
expandedGraphHeight(configuration.screenHeightDp)
} else {
collapsedGraphHeight(configuration.screenHeightDp)
},
)
// Compose does not clip children by default: without this the panned/
// zoomed Canvas draws nodes and edges over sibling content outside the
// graph viewport. Clip at the shared container so every caller is covered.
@@ -208,15 +244,39 @@ fun WorkflowGraph(
drawNodes(layout, colors, runState, selectedStage, textMeasurer)
}
}
IconButton(
onClick = {
userAdjusted = false
// Re-run the fit effect even when the viewport is unchanged.
fitRequest += 1
},
Row(
modifier = Modifier.align(Alignment.TopEnd).padding(4.dp),
) {
Icon(Icons.Default.FitScreen, contentDescription = "Fit graph to view")
IconButton(
onClick = {
userAdjusted = false
// Re-run the fit effect even when the viewport is unchanged.
fitRequest += 1
},
) {
Icon(Icons.Default.FitScreen, contentDescription = "Fit graph to view")
}
IconButton(
onClick = {
val nowExpanded = !expanded
expanded = nowExpanded
// Refit the resized panel, mirroring the Fit control.
userAdjusted = false
fitRequest += 1
if (nowExpanded) {
// Growing the panel pushes it below the fold of the
// enclosing scrolling column; scroll it back so the
// expanded graph is visible without a manual pan.
scope.launch { bringIntoView.bringIntoView() }
}
},
) {
if (expanded) {
Icon(Icons.Default.FullscreenExit, contentDescription = "Collapse graph")
} else {
Icon(Icons.Default.Fullscreen, contentDescription = "Expand graph")
}
}
}
}
}
@@ -367,13 +427,79 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
targetRank = targetRank,
labelSlot = labelSlot,
labelCount = countsBySource[edge.source] ?: 1,
)
).let { it.copy(points = routePoints(it)) }
}
val height = pad * 2 + nodeHeight + (if (hasTerminal) terminalRowGap + nodeHeight else 0f)
return GraphLayout(positions.values.toList(), edgeLayouts, width, height)
}
/**
* The axis-aligned polyline an edge is drawn along: horizontal and vertical runs
* joined at right angles, mirroring internal/tui/graph_layout.go (source track ->
* lane -> target track). Pure and independent of drawing so tests can assert it
* and layout can precompute it once per edge.
*
* - `bottomExit` (error -> #failure) drops out of the source's bottom, runs
* across above the terminal and drops into its top border.
* - `topEntry` (any other terminal) leaves the source's right edge, drops into a
* lane just above the lower terminal row, then drops into the terminal top.
* - `backEdge` (loop) dips below the stages, runs back horizontally and enters
* the target's left edge.
* - a forward edge is a single horizontal segment when source and target share a
* y, otherwise an L across a shared mid-x.
*
* Consecutive equal points are collapsed so no zero-length segment is produced.
*/
internal fun routePoints(edge: EdgeLayout): List<Offset> {
val raw = when {
edge.bottomExit -> {
val approachY = edge.to.y - BOTTOM_EXIT_APPROACH
listOf(edge.from, Offset(edge.from.x, approachY), Offset(edge.to.x, approachY), edge.to)
}
edge.topEntry -> {
val laneY = edge.to.y - LANE_APPROACH
listOf(edge.from, Offset(edge.from.x, laneY), Offset(edge.to.x, laneY), edge.to)
}
edge.backEdge -> {
val dipY = maxOf(edge.from.y, edge.to.y) + BACK_EDGE_DIP
val leadX = edge.to.x - BACK_EDGE_LEAD
listOf(
edge.from,
Offset(edge.from.x, dipY),
Offset(leadX, dipY),
Offset(leadX, edge.to.y),
edge.to,
)
}
edge.from.y == edge.to.y -> listOf(edge.from, edge.to)
else -> {
val midX = (edge.from.x + edge.to.x) / 2f
listOf(edge.from, Offset(midX, edge.from.y), Offset(midX, edge.to.y), edge.to)
}
}
val points = ArrayList<Offset>(raw.size)
for (point in raw) {
val last = points.lastOrNull()
if (last == null || last.x != point.x || last.y != point.y) points += point
}
return points
}
/**
* Direction of the final non-degenerate segment of [points], used to orient an
* arrowhead along the incoming segment rather than the from-to chord (which is
* wrong once a route turns a corner). Returns [Offset.Zero] when there is no
* segment to derive a direction from.
*/
internal fun arrowDirection(points: List<Offset>): Offset {
for (i in points.size - 1 downTo 1) {
val delta = points[i] - points[i - 1]
if (delta.x != 0f || delta.y != 0f) return delta
}
return Offset.Zero
}
/**
* Column rank for every stage in declaration order, mirroring
* tui.layoutSingleRowGraph: `graph.Stages` is the source order, so stages keep
@@ -396,34 +522,17 @@ private fun DrawScope.drawEdgePaths(
val executed = edge.isExecuted(runState)
val color = outcomeColor(edge.edge, colors)
val alpha = if (executed) 1f else 0.25f
// Routing already happened once in layoutGraph; drawing only replays the
// stored polyline, so there is no per-frame recompute.
val points = if (edge.points.isEmpty()) routePoints(edge) else edge.points
if (points.size < 2) continue
val path = Path()
path.moveTo(edge.from.x, edge.from.y)
when {
// An error->#failure route drops out of the source bottom, runs down
// and across, then rises into the terminal top border.
edge.bottomExit -> {
val approachY = edge.to.y - BOTTOM_EXIT_APPROACH
path.lineTo(edge.from.x, approachY)
path.lineTo(edge.to.x, approachY)
path.lineTo(edge.to.x, edge.to.y)
}
// Terminal edges leave the source's right edge and curve down/right
// into the terminal's top border.
edge.topEntry -> {
val midX = (edge.from.x + edge.to.x) / 2f
path.cubicTo(midX, edge.from.y, midX, edge.to.y, edge.to.x, edge.to.y)
}
edge.backEdge -> {
val dip = maxOf(edge.from.y, edge.to.y) + BACK_EDGE_DIP
path.cubicTo(edge.from.x + 24f, dip, edge.to.x - 24f, dip, edge.to.x, edge.to.y)
}
else -> {
val midX = (edge.from.x + edge.to.x) / 2f
path.cubicTo(midX, edge.from.y, midX, edge.to.y, edge.to.x, edge.to.y)
}
path.moveTo(points.first().x, points.first().y)
for (i in 1 until points.size) {
path.lineTo(points[i].x, points[i].y)
}
drawPath(path, color = color.copy(alpha = alpha), style = Stroke(width = 3f))
drawArrowHead(edge.from, edge.to, color.copy(alpha = alpha))
drawArrowHead(points, color.copy(alpha = alpha))
}
}
@@ -470,8 +579,17 @@ private fun DrawScope.drawEdgeLabels(
}
}
private fun DrawScope.drawArrowHead(from: Offset, to: Offset, color: Color) {
val angle = kotlin.math.atan2((to.y - from.y).toDouble(), (to.x - from.x).toDouble())
/**
* Draws an arrowhead at the tip of [points], oriented along the final segment's
* direction (see [arrowDirection]) instead of the from-to chord, so a route that
* turns a corner still gets an arrow pointing the way it actually travels.
*/
private fun DrawScope.drawArrowHead(points: List<Offset>, color: Color) {
if (points.size < 2) return
val to = points.last()
val direction = arrowDirection(points)
if (direction.x == 0f && direction.y == 0f) return
val angle = kotlin.math.atan2(direction.y.toDouble(), direction.x.toDouble())
val size = 12f
val left = Offset(
x = to.x - size * kotlin.math.cos(angle - 0.5).toFloat(),
@@ -593,6 +711,28 @@ private const val BACK_EDGE_DIP = 64f
/** How far above a terminal's top border the bottom-exit route levels off. */
private const val BOTTOM_EXIT_APPROACH = 32f
/** How far above the target's left edge a loop route levels off before entering. */
private const val BACK_EDGE_LEAD = 24f
/** How far above the terminal row a top-entry route runs before dropping in. */
private const val LANE_APPROACH = 32f
/** Breathing room left around a fitted graph, and the least content kept visible. */
private val FIT_PADDING = 16.dp
private val MIN_VISIBLE = 48.dp
/**
* Collapsed graph-panel height, shared by both detail screens (one source for
* the former 360.dp / 340.dp literals). ~58% of the window height so the graph
* is a substantial share of the screen, floored at a height that still fits a
* 4-stage layout plus its lower terminal row: pad*2 + node + terminal gap + node
* = 32*2 + 56 + 72 + 56 = 248px at density 1.
*/
internal fun collapsedGraphHeight(screenHeightDp: Int): Dp =
(screenHeightDp * 0.58f).dp.coerceAtLeast(GRAPH_PANEL_MIN_HEIGHT)
/** Expanded graph-panel height: (approximately) the full available window height. */
internal fun expandedGraphHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.92f).dp
/** Floor that still fits a 4-stage graph with its terminal row (see above). */
internal val GRAPH_PANEL_MIN_HEIGHT = 260.dp
@@ -1,12 +1,10 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
@@ -145,9 +143,7 @@ private fun PipelineDetailContent(detail: PipelineDetail, modifier: Modifier = M
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Box(Modifier.fillMaxWidth().height(360.dp)) {
WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxSize())
}
WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxWidth())
if (detail.source.isNotBlank()) {
Text("Source", style = MaterialTheme.typography.titleMedium)
@@ -1,12 +1,10 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
@@ -238,14 +236,12 @@ private fun RunDetailContent(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Box(Modifier.fillMaxWidth().height(340.dp)) {
WorkflowGraph(
graph = run.graph,
modifier = Modifier.fillMaxSize(),
runState = runState,
selectedStage = runState.currentStage,
)
}
WorkflowGraph(
graph = run.graph,
modifier = Modifier.fillMaxWidth(),
runState = runState,
selectedStage = runState.currentStage,
)
} else {
Text("This server did not include the run graph.", style = MaterialTheme.typography.bodySmall)
}
@@ -9,6 +9,7 @@ import net.awan.pipelines.data.protocol.Stage
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.hypot
class WorkflowGraphTest {
@@ -187,4 +188,141 @@ class WorkflowGraphTest {
assertTrue(single.width.isFinite() && single.height.isFinite())
assertTrue(single.nodes.single().terminal.not())
}
/**
* Every route is drawn as an axis-aligned polyline anchored to the edge's
* from/to anchors, with no zero-length segment: pure geometry, no Compose
* runtime. Mirrors the TUI's right-angled tracks.
*/
@Test
fun everyRouteIsAxisAlignedAndAnchoredToItsEndpoints() {
val layout = layoutGraph(sampleGraph(), Density(1f))
assertTrue(layout.edges.isNotEmpty())
for (edge in layout.edges) {
val points = routePoints(edge)
assertTrue("route too short for ${edge.edge}", points.size >= 2)
assertEquals(edge.from, points.first())
assertEquals(edge.to, points.last())
for (i in 1 until points.size) {
val a = points[i - 1]
val b = points[i]
assertTrue("zero-length segment in ${edge.edge}", a.x != b.x || a.y != b.y)
assertTrue("segment not axis-aligned in ${edge.edge}", a.x == b.x || a.y == b.y)
}
}
}
/** Layout precomputes the polyline once; drawing replays it without re-routing. */
@Test
fun layoutStoresTheRoutePointsOnEachEdge() {
val layout = layoutGraph(sampleGraph(), Density(1f))
for (edge in layout.edges) {
assertEquals(routePoints(edge), edge.points)
}
}
/**
* The arrowhead direction is the final segment's delta, not the straight
* from-to chord, which no longer points the travel direction once a route
* turns a corner.
*/
@Test
fun arrowDirectionFollowsTheFinalSegmentNotTheChord() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val pointsFor: (String, String) -> List<Offset> = { source, outcome ->
layout.edges.first { it.edge.source == source && it.edge.outcome == outcome }.points
}
// Every cornered route's arrow follows its final segment exactly.
for (edge in layout.edges.filter { it.bottomExit || it.topEntry || it.backEdge }) {
val points = edge.points
val last = points[points.size - 1] - points[points.size - 2]
assertEquals(last, arrowDirection(points))
}
// The three canonical turn cases differ from the straight from-to chord.
for (points in listOf(
pointsFor("planner", "error"), // bottomExit
pointsFor("ui_reviewer", "approved"), // topEntry
pointsFor("reviewer", "rejected"), // backEdge
)) {
val last = points[points.size - 1] - points[points.size - 2]
val chord = points.last() - points.first()
val chordLength = hypot(chord.x, chord.y)
val dirLength = hypot(last.x, last.y)
assertTrue(dirLength > 0f)
val normalizedChord = Offset(chord.x / chordLength, chord.y / chordLength)
val normalizedDir = Offset(last.x / dirLength, last.y / dirLength)
assertTrue(normalizedChord != normalizedDir)
}
}
@Test
fun terminalTopEntryRoutesDropVerticallyIntoTheTerminalTopCentre() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val success = layout.nodes.single { it.key == Protocol.SUCCESS_END }
val edge = layout.edges.first { it.edge.target == Protocol.SUCCESS_END && !it.bottomExit }
assertTrue(edge.topEntry)
val points = edge.points
val before = points[points.size - 2]
val tip = points.last()
assertEquals(before.x, tip.x, 0.001f)
assertTrue(tip.y > before.y)
assertEquals(success.x + success.width / 2f, tip.x, 0.001f)
assertEquals(success.y, tip.y, 0.001f)
}
@Test
fun errorToFailureBottomExitEndsVerticalDownAtTheFailureTopCentre() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val failure = layout.nodes.single { it.key == Protocol.FAILURE_END }
val edge = layout.edges.first { it.edge.source == "planner" && it.edge.outcome == "error" }
assertTrue(edge.bottomExit)
val points = edge.points
val before = points[points.size - 2]
val tip = points.last()
assertEquals(before.x, tip.x, 0.001f)
assertTrue(tip.y > before.y)
assertEquals(failure.x + failure.width / 2f, tip.x, 0.001f)
assertEquals(failure.y, tip.y, 0.001f)
}
@Test
fun backEdgeEndsWithAHorizontalSegmentIntoTheTargetLeftEdge() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val edge = layout.edges.first { it.edge.source == "reviewer" && it.edge.outcome == "rejected" }
assertTrue(edge.backEdge)
val implementer = layout.nodes.single { it.key == "implementer" }
val points = edge.points
val before = points[points.size - 2]
val tip = points.last()
assertEquals(before.y, tip.y, 0.001f)
assertTrue(tip.x > before.x)
assertEquals(implementer.x, tip.x, 0.001f)
assertEquals(implementer.y + implementer.height / 2f, tip.y, 0.001f)
}
@Test
fun forwardEdgeBetweenStagesIsASingleHorizontalSegment() {
val layout = layoutGraph(sampleGraph(), Density(1f))
val edge = layout.edges.first { it.edge.source == "planner" && it.edge.outcome == "success" }
assertEquals(edge.from.y, edge.to.y, 0.001f)
assertEquals(2, edge.points.size)
assertEquals(edge.from, edge.points.first())
assertEquals(edge.to, edge.points.last())
assertEquals(edge.points.first().y, edge.points.last().y, 0.001f)
}
/**
* Both screens share one height helper: a fraction of the window height with
* a floor that still fits a 4-stage graph plus its terminal row.
*/
@Test
fun collapsedGraphPanelIsAFractionOfTheWindowWithAMinimumFloor() {
assertEquals(580f, collapsedGraphHeight(1000).value, 0.01f)
// Short windows fall back to the minimum that fits a 4-stage graph.
assertEquals(GRAPH_PANEL_MIN_HEIGHT, collapsedGraphHeight(200))
assertTrue(collapsedGraphHeight(100).value >= GRAPH_PANEL_MIN_HEIGHT.value)
// Expanded is larger and approximately the full window height.
assertTrue(expandedGraphHeight(1000).value > collapsedGraphHeight(1000).value)
assertEquals(920f, expandedGraphHeight(1000).value, 0.01f)
}
}