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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion a11ydisabled_audit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,7 @@ var disabledA11yExempt = exemptions(map[string][]string{
"ContrastBadge", "Diff", "Gauge", "GroupCard", "Image", "Kbd", "Label", "LevelBar", "LineChart",
"LinkCard", "LoadMask", "MarkdownView", "MediaCard", "Notification", "PieChart", "PostCard",
"ProgressBar", "ProgressCircle", "RadarChart", "SelectionBox",
"ScatterChart", "SegmentedBar", "Sparkline", "Spinner", "Stat", "TimeSeriesChart", "Timeline",
"ScatterChart", "SegmentedBar", "Sparkline", "Spinner", "Stat", "StackedBarChart", "TimeSeriesChart", "Timeline",
"Tooltip", "XYPlot",
},
exemptLayout: {
Expand Down
45 changes: 27 additions & 18 deletions graphview.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,25 @@ func (g *GraphView) strokeBox(p painter.Painter, r Rect, radius int, c RGBA) {
// nodeW is the width of a node box.
func (g *GraphView) nodeW() int {
if g.NodeWidth > 0 {
return g.NodeWidth
return scaled(g.NodeWidth)
}
return graphNodeW
return scaled(graphNodeW)
}

// The layout metrics, scaled by the global metric scale ([SetMetricScale]) so a
// graph drawn on a HiDPI surface grows with its text.
func gGap() int { return scaled(graphGap) }
func gNodeH() int { return scaled(graphNodeH) }
func gTitleH() int { return scaled(graphTitleH) }

// layout places clusters on a grid filling the bounds and nodes on a sub-grid
// inside each cluster. Deterministic: the same lists and bounds give the
// same boxes.
func (g *GraphView) layout() {
g.bind()
nw := g.nodeW()
// A change of node width (NodeWidth set late, or the metric scale changed)
// lays out again; an edge update never does.
if g.layoutValid && g.laidNodeW == nw {
return
}
Expand Down Expand Up @@ -243,7 +251,7 @@ func (g *GraphView) layout() {
// what is left of the width.
// A cluster is at least as wide as its title, so a long label never
// spills over the next cluster.
titleW := func(c GraphCluster) int { return g.textWidth(c.Label) + 2*graphGap }
titleW := func(c GraphCluster) int { return g.textWidth(c.Label) + 2*gGap() }
boxes, perRows, h := flowClusters(clusters, members, area.W, nw, titleW)
if h > area.H {
g.hasBar = true
Expand All @@ -257,8 +265,8 @@ func (g *GraphView) layout() {
g.clusterBox[c.ID] = box
for j, n := range members[c.ID] {
nc, nr := j%perRows[i], j/perRows[i]
g.nodeBox[n.ID] = Rect{X: box.X + graphGap + nc*(nw+graphGap),
Y: box.Y + graphTitleH + graphGap + nr*(graphNodeH+graphGap), W: nw, H: graphNodeH}
g.nodeBox[n.ID] = Rect{X: box.X + gGap() + nc*(nw+gGap()),
Y: box.Y + gTitleH() + gGap() + nr*(gNodeH()+gGap()), W: nw, H: gNodeH()}
g.order = append(g.order, n.ID)
}
}
Expand All @@ -269,26 +277,27 @@ func (g *GraphView) layout() {
// the boxes relative to the content origin, each cluster's nodes per row, and
// the content height.
func flowClusters(clusters []GraphCluster, members map[string][]GraphNode, width, nodeW int, titleW func(GraphCluster) int) (boxes []Rect, perRows []int, height int) {
x, y, rowH := graphGap, graphGap, 0
gap := gGap()
x, y, rowH := gap, gap, 0
for _, c := range clusters {
n := maxInt(1, len(members[c.ID]))
perRow := int(math.Ceil(math.Sqrt(float64(n))))
rowsIn := (n + perRow - 1) / perRow
cw := maxInt(perRow*(nodeW+graphGap)+graphGap, titleW(c))
ch := graphTitleH + rowsIn*(graphNodeH+graphGap) + graphGap
if x > graphGap && x+cw+graphGap > width {
x, y, rowH = graphGap, y+rowH+graphGap, 0
cw := maxInt(perRow*(nodeW+gap)+gap, titleW(c))
ch := gTitleH() + rowsIn*(gNodeH()+gap) + gap
if x > gap && x+cw+gap > width {
x, y, rowH = gap, y+rowH+gap, 0
}
boxes = append(boxes, Rect{X: x, Y: y, W: cw, H: ch})
perRows = append(perRows, perRow)
x += cw + graphGap
x += cw + gap
rowH = maxInt(rowH, ch)
}
return boxes, perRows, y + rowH + graphGap
return boxes, perRows, y + rowH + gap
}

// graphScrollStep is the pixels one wheel row moves the content.
const graphScrollStep = graphNodeH + graphGap
func graphScrollStep() int { return gNodeH() + gGap() }

// graphThumbMin is the smallest scrollbar thumb, in pixels.
const graphThumbMin = 12
Expand Down Expand Up @@ -343,9 +352,9 @@ func (g *GraphView) revealNode(id string) {
top := g.Bounds().Y
switch {
case b.Y < top:
g.ScrollBy(b.Y - top - graphGap)
g.ScrollBy(b.Y - top - gGap())
case b.Y+b.H > top+g.viewH:
g.ScrollBy(b.Y + b.H - (top + g.viewH) + graphGap)
g.ScrollBy(b.Y + b.H - (top + g.viewH) + gGap())
}
}

Expand Down Expand Up @@ -431,7 +440,7 @@ 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+graphGap, box.Y+2, labels[id], theme.OnSurface)
g.drawText(p, box.X+gGap(), box.Y+scaled(2), labels[id], theme.OnSurface)
}
nodes := g.Model.Nodes.Slice()
for _, n := range nodes {
Expand Down Expand Up @@ -609,7 +618,7 @@ func (g *GraphView) drawLegend(p painter.Painter, theme *Theme) {
top := r.Y + r.H - h + graphLegendPad
ty := top + (line-g.glyphHeight())/2 // text
sy := top + (line-graphSwatch)/2 // swatch
x := r.X + graphGap
x := r.X + gGap()
names := make([]string, len(g.categories))
for cat, i := range g.categories {
names[i] = cat
Expand Down Expand Up @@ -675,7 +684,7 @@ func (g *GraphView) OnEvent(ev Event) {
r := g.Bounds()
switch ev.Kind {
case EventScroll:
g.ScrollBy(ev.Delta * graphScrollStep)
g.ScrollBy(ev.Delta * graphScrollStep())
case EventMouseDrag:
sg, ok := g.scrollbarGeom()
g.sbDrag.drag(sg, ok, ev, g.ScrollTo)
Expand Down
40 changes: 40 additions & 0 deletions graphview_scale_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 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 "testing"

// A graph drawn on a HiDPI surface grows with the metric scale: nodes, gaps and
// the scroll step double at scale 2, and more clusters fit per row as the width
// grows (the layout is a flow).
func TestGraphViewHonoursTheMetricScale(t *testing.T) {
defer SetMetricScale(MetricScale())
laid := func(scale float64, w int) (*GraphView, Rect) {
SetMetricScale(scale)
g := NewGraphView(manyClusters(6, 4))
g.SetBounds(Rect{W: w, H: 2000})
g.layout()
return g, g.nodeBox["n0_0"]
}
_, one := laid(1, 800)
g2, two := laid(2, 1600)
if two.W != 2*one.W || two.H != 2*one.H {
t.Fatalf("node %v at scale 2 is not twice %v", two, one)
}
if got, want := graphScrollStep(), 2*(graphNodeH+graphGap); got != want {
t.Fatalf("scroll step %d, want %d", got, want)
}
if g2.clusterBox["c1"].Y != g2.clusterBox["c0"].Y {
t.Fatal("two clusters should share a row at this width")
}
narrow, _ := laid(2, 400)
if narrow.clusterBox["c1"].Y == narrow.clusterBox["c0"].Y {
t.Fatal("a narrow surface should wrap clusters onto more rows")
}
wide, _ := laid(2, 3000)
if wide.clusterBox["c5"].Y != wide.clusterBox["c0"].Y {
t.Fatal("a wide surface should hold more cluster columns")
}
}
2 changes: 1 addition & 1 deletion graphview_scroll_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestGraphViewScrollsWhenItOverflows(t *testing.T) {
}
// The wheel moves it, in rows.
g.OnEvent(Event{Kind: EventScroll, Delta: 3})
if g.ScrollY() != 3*graphScrollStep {
if g.ScrollY() != 3*graphScrollStep() {
t.Fatalf("wheel: scroll %d", g.ScrollY())
}
// Scrolling past the end clamps, and then the last node is reachable.
Expand Down
181 changes: 181 additions & 0 deletions stackedbarchart.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// 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 (
"fmt"
"time"

"github.com/go-widgets/painter"
)

// StackedBarChart plots a quantity over time as one bar per time bucket, each
// bar made of stacked layers (a token count split by model, a request count by
// status). It is the labelled, stacked companion to BarChart: a legend names
// every layer, the value axis shows 0, the middle and the top, and the time axis
// shows the first and last instant of TimeMin..TimeMax.
//
// Layers[l][b] is layer l's value in bucket b; buckets are equal slices of the
// time span, oldest on the left. Negative values count as zero. Display-only.
type StackedBarChart struct {
Base
Layers [][]float64
// Names label the layers in the legend, in Layers order; a layer without a
// name is left out of the legend.
Names []string
// Colors overrides the categorical palette, cycled by layer index.
Colors []RGBA
// TimeMin, TimeMax are the instants (Unix seconds) the first bucket starts
// at and the last ends at. Zero values draw no time labels.
TimeMin, TimeMax int64
// Max is the top of the value axis; when <= 0 it is [NiceCeiling] of the
// tallest stack.
Max float64
// FormatValue renders one value-axis label; nil uses "%.0f".
FormatValue func(float64) string
// FormatTime renders one time-axis label; nil uses "Jan 2 15:04".
FormatTime func(int64) string
}

// NewStackedBarChart builds a StackedBarChart over the given layers.
func NewStackedBarChart(layers [][]float64, names []string) *StackedBarChart {
return &StackedBarChart{Layers: layers, Names: names}
}

func (c *StackedBarChart) layerColor(i int) RGBA {
if len(c.Colors) > 0 {
return c.Colors[i%len(c.Colors)]
}
return piePalette[i%len(piePalette)]
}

// buckets is the number of bars: the longest layer.
func (c *StackedBarChart) buckets() int {
n := 0
for _, l := range c.Layers {
n = max(n, len(l))
}
return n
}

// top is the value axis maximum.
func (c *StackedBarChart) top() float64 {
if c.Max > 0 {
return c.Max
}
most := 0.0
for b := 0; b < c.buckets(); b++ {
most = max(most, c.stackTotal(b))
}
return NiceCeiling(most)
}

// stackTotal is the height of bucket b's whole stack.
func (c *StackedBarChart) stackTotal(b int) float64 {
sum := 0.0
for _, l := range c.Layers {
if b < len(l) && l[b] > 0 {
sum += l[b]
}
}
return sum
}

func (c *StackedBarChart) formatValue(v float64) string {
if c.FormatValue != nil {
return c.FormatValue(v)
}
return fmt.Sprintf("%.0f", v)
}

func (c *StackedBarChart) formatTime(at int64) string {
if c.FormatTime != nil {
return c.FormatTime(at)
}
return time.Unix(at, 0).Format("Jan 2 15:04")
}

// legendHeight is the legend strip's height: one text line plus padding.
func (c *StackedBarChart) legendHeight() int {
return c.glyphHeight() + 2*scaled(TimeSeriesChartPad)
}

// plot is the bar area, inside the legend, the value labels and the time labels.
func (c *StackedBarChart) plot() Rect {
r := c.Bounds()
yAxisW := 0
for _, v := range [3]float64{0, c.top() / 2, c.top()} {
yAxisW = max(yAxisW, c.textWidth(c.formatValue(v)))
}
yAxisW += scaled(TimeSeriesChartPad)
top := c.legendHeight()
return Rect{X: r.X + yAxisW, Y: r.Y + top, W: r.W - yAxisW,
H: r.H - top - c.glyphHeight() - scaled(TimeSeriesChartPad)}
}

// Draw paints the legend, the gridlines with their value labels, the stacked
// bars, and the time labels.
func (c *StackedBarChart) Draw(p painter.Painter, theme *Theme) {
r := c.Bounds()
pl := c.plot()
if r.W <= 0 || r.H <= 0 || pl.W <= 0 || pl.H <= 0 {
return
}
label := dimInk(theme)
gh := c.glyphHeight()
pad := scaled(TimeSeriesChartPad)

x := r.X + pad
for i, name := range c.Names {
if name == "" {
continue
}
fillRect(p, x, r.Y+pad, gh, gh, c.layerColor(i))
c.drawText(p, x+gh+pad, r.Y+pad, name, theme.OnSurface)
x += gh + 2*pad + c.textWidth(name) + 2*pad
}

top := c.top()
for _, frac := range [3]float64{0, 0.5, 1} {
y := pl.Y + int((1-frac)*float64(pl.H-1))
drawLine(p, pl.X, y, pl.X+pl.W-1, y, theme.Border)
text := c.formatValue(frac * top)
c.drawText(p, pl.X-pad-c.textWidth(text), y-gh/2, text, label)
}

n := c.buckets()
for b := 0; b < n; b++ {
x0 := pl.X + b*pl.W/n
x1 := pl.X + (b+1)*pl.W/n
w := max(1, x1-x0-1)
base := pl.Y + pl.H - 1
acc := 0.0
for l, layer := range c.Layers {
if b >= len(layer) || layer[b] <= 0 {
continue
}
acc += layer[b]
y := pl.Y + int((1-min(1, acc/top))*float64(pl.H-1))
if base > y {
fillRect(p, x0, y, w, base-y, c.layerColor(l))
}
base = min(base, y)
}
}

if c.TimeMax > c.TimeMin {
ty := pl.Y + pl.H - 1 + pad
endText := c.formatTime(c.TimeMax)
c.drawText(p, pl.X, ty, c.formatTime(c.TimeMin), label)
c.drawText(p, pl.X+pl.W-c.textWidth(endText), ty, endText, label)
}
}

// A11y describes the chart as an image with its layer and bucket counts.
func (c *StackedBarChart) A11y() A11yInfo {
return A11yInfo{Role: RoleImg, Value: fmt.Sprintf("%d layers, %d buckets", len(c.Layers), c.buckets())}
}

var _ Accessible = (*StackedBarChart)(nil)
Loading