From ba2c6594e402090ece56d994e908f9ff870c9f79 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Fri, 20 Nov 2026 11:20:46 +0100 Subject: [PATCH] fix(graphview): nothing leaves its cluster or the view; LayoutProblems checks it - A cluster is never wider than the view: its nodes wrap into more rows (the box grows taller, the graph scrolls) and a node narrows to a box narrower than itself. - Cluster titles and every part of a node are clipped to their cluster box. - The legend wraps to as many rows as its entries need instead of running off the right edge. - LayoutProblems also checks a GraphView's geometry (node inside cluster, cluster inside the view) and ignores the children of a scroll viewport (ScrollsContent), whose content is meant to reach past it. Coverage stays 100 %. Co-Authored-By: Claude Sonnet 5.5 --- graphview.go | 121 ++++++++++++++++++++++--------- graphview_contain_test.go | 145 ++++++++++++++++++++++++++++++++++++++ layoutcheck.go | 49 +++++++++++++ 3 files changed, 283 insertions(+), 32 deletions(-) create mode 100644 graphview_contain_test.go diff --git a/graphview.go b/graphview.go index 7a6980c..5155401 100644 --- a/graphview.go +++ b/graphview.go @@ -241,6 +241,9 @@ func (g *GraphView) layout() { return } area := r + for _, n := range nodes { // the legend's entries, in the order the nodes name them + g.categoryColor(n.Category) + } if g.ShowLegend { area.H -= g.legendHeight() } @@ -266,7 +269,7 @@ func (g *GraphView) layout() { for j, n := range members[c.ID] { nc, nr := j%perRows[i], j/perRows[i] g.nodeBox[n.ID] = Rect{X: box.X + gGap() + nc*(nw+gGap()), - Y: box.Y + gTitleH() + gGap() + nr*(gNodeH()+gGap()), W: nw, H: gNodeH()} + Y: box.Y + gTitleH() + gGap() + nr*(gNodeH()+gGap()), W: min(nw, max(box.W-2*gGap(), 1)), H: gNodeH()} g.order = append(g.order, n.ID) } } @@ -282,8 +285,17 @@ func flowClusters(clusters []GraphCluster, members map[string][]GraphNode, width for _, c := range clusters { n := maxInt(1, len(members[c.ID])) perRow := int(math.Ceil(math.Sqrt(float64(n)))) + // A cluster never grows wider than the view: past that its nodes wrap into + // more rows (the box grows taller) and its title is clipped to the box. + capW := width - 2*gap + if fit := (capW - gap) / (nodeW + gap); capW > 0 && fit < perRow { + perRow = maxInt(1, fit) + } rowsIn := (n + perRow - 1) / perRow cw := maxInt(perRow*(nodeW+gap)+gap, titleW(c)) + if capW > 0 { + cw = min(cw, capW) + } ch := gTitleH() + rowsIn*(gNodeH()+gap) + gap if x > gap && x+cw+gap > width { x, y, rowH = gap, y+rowH+gap, 0 @@ -440,7 +452,10 @@ func (g *GraphView) Draw(p painter.Painter, theme *Theme) { for id, box := range g.clusterBox { g.fillBox(p, box, g.clusterRadius(), theme.Surface) g.strokeBox(p, box, g.clusterRadius(), theme.Border) - g.drawText(p, box.X+gGap(), box.Y+scaled(2), labels[id], theme.OnSurface) + // The title is clipped to its box: a long one never runs out of it. + withClip(p, box, func() { + g.drawText(p, box.X+gGap(), box.Y+scaled(2), labels[id], theme.OnSurface) + }) } nodes := g.Model.Nodes.Slice() for _, n := range nodes { @@ -460,20 +475,24 @@ func (g *GraphView) Draw(p painter.Painter, theme *Theme) { if !visible[n.ID] { col = blendRGBA(col, theme.Background, 0.25) } - g.fillBox(p, box, g.CornerRadius, col) - // Label ink by the swatch's lightness, so it reads on every colour. - ink := RGB(0x10, 0x10, 0x10) - if luminance(col) < 0.4 { - ink = RGB(0xFF, 0xFF, 0xFF) - } - // The label is clipped to its box: a long one must not run into the - // node beside it. - withClip(p, box, func() { - g.drawText(p, box.X+3, box.Y+(box.H-g.glyphHeight())/2, n.Label, ink) + // Nothing of a node is drawn outside its cluster's box. + limit := g.clusterBox[n.Cluster] + withClip(p, limit, func() { + g.fillBox(p, box, g.CornerRadius, col) + // Label ink by the swatch's lightness, so it reads on every colour. + ink := RGB(0x10, 0x10, 0x10) + if luminance(col) < 0.4 { + ink = RGB(0xFF, 0xFF, 0xFF) + } + // The label is clipped to its box: a long one must not run into the + // node beside it. + withClip(p, box, func() { + g.drawText(p, box.X+3, box.Y+(box.H-g.glyphHeight())/2, n.Label, ink) + }) + if sel == "node:"+n.ID { + g.strokeBox(p, Rect{X: box.X - 2, Y: box.Y - 2, W: box.W + 4, H: box.H + 4}, g.CornerRadius+2, theme.Accent) + } }) - if sel == "node:"+n.ID { - g.strokeBox(p, Rect{X: box.X - 2, Y: box.Y - 2, W: box.W + 4, H: box.H + 4}, g.CornerRadius+2, theme.Accent) - } } if g.ShowLegend { // Clusters scrolled under the legend must not show through it. @@ -604,32 +623,70 @@ const ( ) // legendHeight is the legend strip's height, from the widget's font: one -// line of text (or a swatch, if the font is smaller) with its padding. +// line of text (or a swatch, if the font is smaller) with its padding per row. +// The legend wraps to as many rows as its entries need in the widget's width, so +// it never runs off the right edge. func (g *GraphView) legendHeight() int { - return max(g.glyphHeight(), graphSwatch) + 2*graphLegendPad + rows := len(g.legendRows()) + return rows*max(g.glyphHeight(), graphSwatch) + (rows+1)*graphLegendPad } -// drawLegend draws one swatch per category seen, and the denied style, on a -// line centred in the legend strip. -func (g *GraphView) drawLegend(p painter.Painter, theme *Theme) { - r := g.Bounds() - h := g.legendHeight() - line := h - 2*graphLegendPad - top := r.Y + r.H - h + graphLegendPad - ty := top + (line-g.glyphHeight())/2 // text - sy := top + (line-graphSwatch)/2 // swatch - x := r.X + gGap() +// legendItem is one entry of the legend: a swatch (or the dashed denied style) +// and its caption, and the width the pair takes. +type legendItem struct { + cat string + denied bool + w int +} + +// legendRows flows the legend's entries (one per category, then "denied") into +// rows no wider than the widget less its margins. +func (g *GraphView) legendRows() [][]legendItem { names := make([]string, len(g.categories)) for cat, i := range g.categories { names[i] = cat } + items := make([]legendItem, 0, len(names)+1) for _, cat := range names { - fillRect(p, x, sy, graphSwatch, graphSwatch, g.categoryColor(cat)) - g.drawText(p, x+13, ty, cat, theme.OnBackground) - x += 13 + g.textWidth(cat) + 10 + items = append(items, legendItem{cat: cat, w: 13 + g.textWidth(cat) + 10}) + } + items = append(items, legendItem{cat: "denied", denied: true, w: 20 + g.textWidth("denied")}) + avail := g.Bounds().W - 2*gGap() + rows := [][]legendItem{nil} + x := 0 + for _, it := range items { + if x > 0 && x+it.w > avail { + rows = append(rows, nil) + x = 0 + } + rows[len(rows)-1] = append(rows[len(rows)-1], it) + x += it.w + } + return rows +} + +// drawLegend draws one swatch per category seen, and the denied style, on lines +// centred in the legend strip. +func (g *GraphView) drawLegend(p painter.Painter, theme *Theme) { + r := g.Bounds() + h := g.legendHeight() + line := max(g.glyphHeight(), graphSwatch) + for i, row := range g.legendRows() { + top := r.Y + r.H - h + graphLegendPad + i*(line+graphLegendPad) + ty := top + (line-g.glyphHeight())/2 // text + sy := top + (line-graphSwatch)/2 // swatch + x := r.X + gGap() + for _, it := range row { + if it.denied { + drawDashed(p, x, sy+graphSwatch/2, x+16, sy+graphSwatch/2, graphDeniedInk(theme)) + g.drawText(p, x+20, ty, it.cat, theme.OnBackground) + } else { + fillRect(p, x, sy, graphSwatch, graphSwatch, g.categoryColor(it.cat)) + g.drawText(p, x+13, ty, it.cat, theme.OnBackground) + } + x += it.w + } } - drawDashed(p, x, sy+graphSwatch/2, x+16, sy+graphSwatch/2, graphDeniedInk(theme)) - g.drawText(p, x+20, ty, "denied", theme.OnBackground) } // edgeAt returns the edge whose segment passes within graphHitSlack of (x,y). diff --git a/graphview_contain_test.go b/graphview_contain_test.go new file mode 100644 index 0000000..72b5f95 --- /dev/null +++ b/graphview_contain_test.go @@ -0,0 +1,145 @@ +// Copyright (c) 2026 the go-widgets/toolkit authors. All rights reserved. +// Use of this source code is governed by a BSD-3-Clause license that can be +// found in the LICENSE file at the root of this repository. + +package toolkit + +import ( + "strconv" + "strings" + "testing" +) + +// crowded is one cluster of n nodes with a long title, in k categories. +func crowded(n, k int) *GraphViewModel { + m := NewGraphViewModel() + m.Clusters.Append(GraphCluster{ID: "c", Label: "a cluster whose title is much longer than the view is wide"}, + GraphCluster{ID: "d", Label: "d"}) + for i := 0; i < n; i++ { + m.Nodes.Append(GraphNode{ID: "n" + strconv.Itoa(i), Label: "a long node label", Cluster: "c", Category: "cat" + strconv.Itoa(i%k)}) + } + m.Nodes.Append(GraphNode{ID: "x", Cluster: "d", Category: "cat0"}) + return m +} + +// A cluster is never wider than the view: its nodes wrap into more rows (the box +// grows taller) and the graph still scrolls, however narrow the view. +func TestGraphViewClusterNeverWiderThanTheView(t *testing.T) { + for _, w := range []int{400, 220, 120, 40} { + g := NewGraphView(crowded(30, 3)) + g.ShowLegend = true + g.SetBounds(Rect{X: 5, Y: 7, W: w, H: 300}) + if got := LayoutProblems(g); len(got) != 0 { + t.Fatalf("width %d: %v", w, got) + } + cb := g.clusterBox["c"] + if cb.W > w { + t.Fatalf("width %d: cluster %v is wider than the view", w, cb) + } + if w == 120 { + // 30 nodes one per row (a node is 72 wide, the room is 120-12): tall, so it scrolls. + if cb.H < 30*(gNodeH()+gGap()) || !g.hasBar { + t.Fatalf("a narrow view wraps the nodes into rows and scrolls: box %v bar %v", cb, g.hasBar) + } + } + // Painting it (titles and nodes clipped) must not fail either. + g.Draw(newP(makeSurface(w+10, 320), w+10), DefaultLight()) + } + // Wide enough, the old layout is kept: sqrt(n) columns. + g := NewGraphView(crowded(9, 1)) + g.SetBounds(Rect{W: 900, H: 600}) + g.layout() + if cb := g.clusterBox["c"]; cb.W != 3*(g.nodeW()+gGap())+gGap() && cb.W < g.textWidth("a cluster whose title is much longer than the view is wide") { + t.Fatalf("a wide view changed the cluster: %v", cb) + } +} + +// The legend wraps to as many rows as it needs, and every entry stays inside. +func TestGraphViewLegendWrapsToTheWidth(t *testing.T) { + g := NewGraphView(crowded(8, 8)) + g.ShowLegend = true + g.SetBounds(Rect{W: 500, H: 400}) + g.layout() // the nodes' categories are the legend's entries + one := g.legendHeight() + wide := len(g.legendRows()) + g.SetBounds(Rect{W: 150, H: 400}) + rows := g.legendRows() + if len(rows) <= wide || g.legendHeight() <= one { + t.Fatalf("a narrow legend did not wrap: %d rows (was %d), height %d (was %d)", len(rows), wide, g.legendHeight(), one) + } + for _, row := range rows { + w := 0 + for _, it := range row { + w += it.w + } + if len(row) > 1 && w > 150-2*gGap() { + t.Fatalf("a legend row of %d entries is %d wide in a 150 view", len(row), w) + } + } + if !rows[len(rows)-1][len(rows[len(rows)-1])-1].denied { + t.Fatal("the denied entry is last") + } + g.Draw(newP(makeSurface(150, 400), 150), DefaultDark()) +} + +// The check itself, both ways: a graph laid out by the widget passes, and boxes +// that reach out of their cluster, or a cluster out of the view, are reported. +func TestGraphProblemsFlagsBoxesOutsideTheirFrame(t *testing.T) { + g := NewGraphView(crowded(4, 2)) + g.SetBounds(Rect{W: 600, H: 400}) + if got := LayoutProblems(g); len(got) != 0 { + t.Fatalf("a graph the widget laid out was reported: %v", got) + } + nb := g.nodeBox["n0"] + nb.W += 500 + g.nodeBox["n0"] = nb + cb := g.clusterBox["d"] + cb.X = 580 + g.clusterBox["d"] = cb + delete(g.clusterBox, "ghost") // a cluster with no box is skipped, not reported + got := LayoutProblems(g) + var node, cluster bool + for _, p := range got { + node = node || strings.Contains(p.Path, "node n0") + cluster = cluster || strings.Contains(p.Path, "cluster d") + if p.Kind != LayoutOutside { + t.Fatalf("kind %v", p.Kind) + } + } + if !node || !cluster { + t.Fatalf("node out of its cluster: %v, cluster out of the view: %v (%v)", node, cluster, got) + } + // A cluster or node that was not laid out has no box and is skipped. + delete(g.clusterBox, "c") + delete(g.nodeBox, "n1") + _ = LayoutProblems(g) +} + +// scroller is a container that scrolls its child: the child may reach past it. +type scroller struct{ slack } + +func (*scroller) ScrollsContent() bool { return true } + +func TestLayoutProblemsIgnoresWhatAScrollViewportScrolls(t *testing.T) { + tall := Rect{X: 0, Y: 0, W: 100, H: 900} + sc := &scroller{slack{child: NewLabel("long"), give: tall}} + sc.SetBounds(Rect{W: 100, H: 100}) + if got := LayoutProblems(sc); len(got) != 0 { + t.Fatalf("a scroll viewport's content was reported: %v", got) + } + // The same overflow in a container that does not scroll is a defect. + bad := &slack{child: NewLabel("long"), give: tall} + bad.SetBounds(Rect{W: 100, H: 100}) + if got := LayoutProblems(bad); len(got) != 1 { + t.Fatalf("an overflowing child went unreported: %v", got) + } + if !NewScrollView(nil).ScrollsContent() { + t.Fatal("a ScrollView is a scroll viewport") + } + // A scroll viewport still reports a child nobody placed. + lazy := &scroller{slack{child: NewLabel("x")}} + lazy.SetBounds(Rect{W: 100, H: 100}) + if got := LayoutProblems(lazy); len(got) != 1 || got[0].Kind != LayoutUnplaced { + t.Fatalf("%v", got) + } +} diff --git a/layoutcheck.go b/layoutcheck.go index b9b6141..c4058ff 100644 --- a/layoutcheck.go +++ b/layoutcheck.go @@ -85,11 +85,15 @@ func LayoutProblems(root Widget) []LayoutProblem { // checkLayout is the recursive half: it compares each child against the parent // it was given, then descends. func checkLayout(parent Widget, path string, out *[]LayoutProblem) { + if g, ok := parent.(*GraphView); ok { + *out = append(*out, graphProblems(g, path)...) + } c, ok := parent.(childContainer) if !ok { return } pr := parent.Bounds() + _, scrolls := parent.(scrollViewport) for _, kid := range c.Children() { if kid == nil { continue @@ -104,6 +108,9 @@ func checkLayout(parent Widget, path string, out *[]LayoutProblem) { Path: where, Rect: kr, In: pr, }) } + case scrolls: + // A scroll viewport's content is meant to reach past it: that is what + // the scrolling is for. case !inside(kr, pr): *out = append(*out, LayoutProblem{ Kind: LayoutOutside, Widget: kid, Parent: parent, @@ -114,6 +121,48 @@ func checkLayout(parent Widget, path string, out *[]LayoutProblem) { } } +// scrollViewport is a container whose children may extend past its bounds +// because it scrolls them into view: LayoutProblems does not call that outside. +type scrollViewport interface{ ScrollsContent() bool } + +// ScrollsContent says a [ScrollView] is a scroll viewport. +func (*ScrollView) ScrollsContent() bool { return true } + +// graphProblems checks a GraphView's own geometry, which is not made of +// widgets: every node's box must be inside its cluster's box, and every cluster's +// box must be as wide as the area the graph flows in (the widget less its scroll +// bar), however narrow that is. A graph that scrolls vertically is not a problem; +// a box reaching past the right edge is, since nothing scrolls sideways. +func graphProblems(g *GraphView, path string) []LayoutProblem { + g.layout() + var out []LayoutProblem + r := g.Bounds() + right := r.X + r.W + if g.hasBar { + right -= scrollbarWidth + } + for _, c := range g.Model.Clusters.Slice() { + cb, ok := g.clusterBox[c.ID] + if !ok { + continue + } + where := path + " > cluster " + c.ID + if cb.X < r.X || cb.X+cb.W > right { + out = append(out, LayoutProblem{Kind: LayoutOutside, Widget: g, Parent: g, Path: where, Rect: cb, In: r}) + } + } + for _, n := range g.Model.Nodes.Slice() { + nb, ok := g.nodeBox[n.ID] + if !ok { + continue + } + if cb := g.clusterBox[n.Cluster]; !inside(nb, cb) { + out = append(out, LayoutProblem{Kind: LayoutOutside, Widget: g, Parent: g, Path: path + " > node " + n.ID, Rect: nb, In: cb}) + } + } + return out +} + // inside reports whether the whole of a is within b. An empty b contains // nothing, which is why the caller tests that first. func inside(a, b Rect) bool {