Files
8bitMyGoUI/chart/legend.go
T
ZacharyZhang-NY 596c62e026 Add chart components 216-245; step-aware ticks, font-aware labels
Bars, lines, areas, pies, donuts, radar, histogram, scatter, bubbles,
heatmaps, gauge, bullet, funnel, waterfall, treemap, candles, box
plots, steps, rings, legend, axis, crosshair, polar area, pyramid,
spectrum bars and win-loss strips, each drawn dot by dot. Ticks follow
1-2-5 steps and print as precisely as their step needs; a label row
uses micro letters or the pixel font as a whole. Descriptions carry the
data in numbers. Bad data panics.
2026-10-12 00:58:44 -04:00

55 lines
1.4 KiB
Go

package chart
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"git.zacharyzhang.com/ZacharyZhang-NY/8bitMyGoUI/pixel"
)
type LegendOptions struct {
Disabled bool
}
type LegendResult struct {
Element *ui.Element
Changed bool
}
// Legend names series by swatch; clicks hide or show one.
func Legend(c *ui.Context, text string, series []Series, hidden []bool, o LegendOptions) LegendResult {
k := pixel.K(c)
if len(hidden) != len(series) {
panic(fmt.Sprintf("chart: Legend has %d series and %d hidden flags", len(series), len(hidden)))
}
row := ui.Row(c).Gap(k.D(8)).FocusGroup(ui.Horizontal).Role(ui.RoleGroup).Label(text)
res := LegendResult{Element: row}
row.Children(func() {
for i, s := range series {
shown := !hidden[i]
shell, base, st := pixel.Shell(c, func() *ui.Element { return ui.ToggleBase(c, &shown).Label(s.Name).Disabled(o.Disabled) })
if base.Changed() {
hidden[i], res.Changed = !shown, true
slog.Debug("8bit: legend", "label", text, "series", s.Name, "shown", shown)
}
ink := pick(s.Slot, i)
shell.Size(k.D(10+pixel.Measure(s.Name)), k.D(pixel.LineHeight)).Draw(func(p *ui.Painter, r ui.Rect) {
g := k.Canvas(p, r)
name := pixel.Ink
if shown {
g.Rect(0, 5, 6, 6, ink)
} else {
g.Rect(0, 5, 6, 6, pixel.Edge)
g.Rect(1, 6, 4, 4, pixel.Well)
name = pixel.Faint
}
g.Text(10, 0, s.Name, name, 1)
g.Finish(st)
})
}
})
return res
}