neofeels/ui/list.go

106 lines
1.8 KiB
Go
Raw Normal View History

2025-01-05 23:06:35 +00:00
/**
* vaxis/widget/list, edited to support wraparounds and number seeking
* soon to support confirmations, once i get around to that
*/
package ui
import (
2025-01-05 23:11:39 +00:00
"fmt"
"strconv"
2025-01-05 23:06:35 +00:00
"git.sr.ht/~rockorager/vaxis"
)
type List struct {
index int
items []string
offset int
}
2025-01-09 02:54:03 +00:00
func NewList(items []string, index int) List {
2025-01-05 23:06:35 +00:00
return List{
items: items,
2025-01-09 02:54:03 +00:00
index: index,
2025-01-05 23:06:35 +00:00
}
}
func (m *List) Draw(win vaxis.Window) {
_, height := win.Size()
if m.index >= m.offset+height {
m.offset = m.index - height + 1
} else if m.index < m.offset {
m.offset = m.index
}
defaultStyle := vaxis.Style{}
selectedStyle := vaxis.Style{Attribute: vaxis.AttrReverse}
index := m.index - m.offset
for i, subject := range m.items[m.offset:] {
var style vaxis.Style
if i == index {
style = selectedStyle
} else {
style = defaultStyle
}
2025-01-05 23:11:39 +00:00
win.Println(i, vaxis.Segment{Text: fmt.Sprintf(" %-"+strconv.Itoa(win.Width-2)+"s", subject), Style: style})
2025-01-05 23:06:35 +00:00
}
}
func (m *List) Down() {
if m.index == len(m.items)-1 {
m.index = 0
} else {
m.index++
}
}
func (m *List) Up() {
if m.index == 0 {
m.index = len(m.items) - 1
} else {
m.index--
}
}
func (m *List) Home() {
m.index = 0
}
func (m *List) End() {
m.index = len(m.items) - 1
}
func (m *List) PageDown(win vaxis.Window) {
_, height := win.Size()
m.index = min(len(m.items)-1, m.index+height)
}
func (m *List) PageUp(win vaxis.Window) {
_, height := win.Size()
m.index = max(0, m.index-height)
}
func (m *List) Items() []string {
return m.items
}
2025-01-05 23:06:35 +00:00
func (m *List) SetItems(items []string) {
m.items = items
m.index = min(len(items)-1, m.index)
}
2025-01-07 11:50:02 +00:00
func (m *List) SetItem(index int, item string) {
m.items[index] = item
}
2025-01-05 23:06:35 +00:00
// Returns the index of the currently selected item.
func (m *List) Index() int {
return m.index
}
func (m *List) SetIndex(index int) {
m.index = index
}