Files
beatglow/ui/widget/list.go
T
2026-10-29 17:29:41 +01:00

90 lines
1.9 KiB
Go

package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/beatglow/hardware"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
)
type List struct {
base
Items []string
Index int
OnSelect func(index int)
fontHeight int
top int
changed bool
}
func NewList(display display.Display, at image.Point, width, height int) *List {
w := &List{
base: makeBase(display, at, width, height),
}
w.SetStyle(w.style)
return w
}
func (w *List) Rotary(event hardware.RotaryEvent) {
w.Index = (w.Index + event.Delta) % len(w.Items)
w.changed = true
}
func (w *List) RotaryPress(event hardware.RotaryPressEvent) {
if w.OnSelect != nil {
w.OnSelect(w.Index)
}
}
func (w *List) SetStyle(style ui.Style) {
w.style = style
_, w.fontHeight = w.style.Font.MeasureText("^<>%MX#gjy")
w.changed = true
}
func (w *List) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
ui.Clear(w.buffer)
var (
bounds = w.buffer.Bounds()
point = bounds.Min
max = bounds.Dy() / w.fontHeight
fg = image.NewUniform(w.style.Foreground)
bg = w.style.Background
)
if w.top >= max {
w.top = w.Index - max + 1
} else if w.Index < w.top {
w.top = w.Index
}
for row := w.top; row < len(w.Items) && point.Y < bounds.Max.Y; row++ {
box := image.Rectangle{Min: point, Max: point.Add(image.Pt(bounds.Dx(), w.fontHeight))}
if row == w.Index {
draw.Draw(w.buffer, box, fg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, bg, w.Items[row])
} else {
draw.Draw(w.buffer, box, bg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, fg, w.Items[row])
}
point = point.Add(image.Pt(0, w.fontHeight))
}
_ = ui.Refresh(w.display, w.buffer)
return true
}
var (
_ ui.Widget = (*List)(nil)
_ hardware.RotaryHandler = (*List)(nil)
_ hardware.RotaryPressHandler = (*List)(nil)
)