Skip to content
Open
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
42 changes: 42 additions & 0 deletions table/cursor_shrink_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package table

import (
"testing"
)

func TestSetRows_CursorClampsToZeroOnEmpty(t *testing.T) {
cols := []Column{{Title: "Name", Width: 10}}
rows := []Row{{"a"}, {"b"}, {"c"}}
tbl := New(WithColumns(cols), WithRows(rows), WithHeight(5))

// Move to last row
tbl.GotoBottom()
if tbl.Cursor() != 2 {
t.Fatalf("expected cursor at 2, got %d", tbl.Cursor())
}

// Replace with empty rows
tbl.SetRows([]Row{})

got := tbl.Cursor()
if got < 0 {
t.Fatalf("SetRows(empty): Cursor() = %d, want >= 0 (got negative cursor on empty table)", got)
}
}

func TestSetRows_CursorClampsOnShrink(t *testing.T) {
cols := []Column{{Title: "Name", Width: 10}}
rows := []Row{{"a"}, {"b"}, {"c"}}
tbl := New(WithColumns(cols), WithRows(rows), WithHeight(5))

// Move to last row (index 2)
tbl.GotoBottom()

// Shrink to 1 row
tbl.SetRows([]Row{{"x"}})

got := tbl.Cursor()
if got != 0 {
t.Fatalf("SetRows(fewer rows): Cursor() = %d, want 0", got)
}
}
4 changes: 3 additions & 1 deletion table/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,9 @@ func (m Model) Columns() []Column {
func (m *Model) SetRows(r []Row) {
m.rows = r

if m.cursor > len(m.rows)-1 {
if len(m.rows) == 0 {
m.cursor = 0
} else if m.cursor > len(m.rows)-1 {
m.cursor = len(m.rows) - 1
}

Expand Down