54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package tui
|
|||
|
|
|
||
|
|
// ListState is the filtered/cursor/scroll state of a list view: Filtered
|
||
|
|
// holds indexes into the view's own item slice.
|
||
|
|
type ListState struct {
|
||
|
|
Filtered []int
|
||
|
|
Cursor int
|
||
|
|
Scroll int
|
||
|
|
}
|
||
|
|
|
||
|
|
// Rebuild filters the n items with match and keeps the cursor in range.
|
||
|
|
func (l *ListState) Rebuild(n int, match func(i int) bool) {
|
||
|
|
l.Filtered = l.Filtered[:0]
|
||
|
|
for i := 0; i < n; i++ {
|
||
|
|
if match(i) {
|
||
|
|
l.Filtered = append(l.Filtered, i)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if l.Cursor >= len(l.Filtered) {
|
||
|
|
l.Cursor = max(0, len(l.Filtered)-1)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Move moves the cursor by delta, clamped to the filtered items.
|
||
|
|
func (l *ListState) Move(delta int) {
|
||
|
|
l.Cursor += delta
|
||
|
|
if l.Cursor >= len(l.Filtered) {
|
||
|
|
l.Cursor = len(l.Filtered) - 1
|
||
|
|
}
|
||
|
|
if l.Cursor < 0 {
|
||
|
|
l.Cursor = 0
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// ClampScroll scrolls so the cursor is visible in a window of rows lines.
|
||
|
|
func (l *ListState) ClampScroll(rows int) {
|
||
|
|
if l.Cursor < l.Scroll {
|
||
|
|
l.Scroll = l.Cursor
|
||
|
|
}
|
||
|
|
if l.Cursor >= l.Scroll+rows {
|
||
|
|
l.Scroll = l.Cursor - rows + 1
|
||
|
|
}
|
||
|
|
if l.Scroll < 0 {
|
||
|
|
l.Scroll = 0
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Index is the item index under the cursor, or -1.
|
||
|
|
func (l ListState) Index() int {
|
||
|
|
if l.Cursor < 0 || l.Cursor >= len(l.Filtered) {
|
||
|
|
return -1
|
||
|
|
}
|
||
|
|
return l.Filtered[l.Cursor]
|
||
|
|
}
|