Skip to content

Commit 171a9d6

Browse files
authored
feat(list): implement GlobalIndex helper (#574)
* feat(list): implement GlobalIndex helper This commit introduces a new `filteredItem` field called `index` which stores the index of the filtered item in the unfiltered list. This allows to get at runtime the unfiltered list index for the selected (and possibly filtered) item. This is the only solution I found to use `SetItem` with a filtered list. The name `GlobalIndex` might not be ideal, I'm happy to change it to something else. (`UnfilteredIndex`?) Fixes: #550 * docs(list): improve Index() documentation
1 parent 076b578 commit 171a9d6

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

list/list.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ type ItemDelegate interface {
5353
}
5454

5555
type filteredItem struct {
56+
index int // index in the unfiltered list
5657
item Item // item matched
5758
matches []int // rune indices of matched items
5859
}
@@ -484,12 +485,26 @@ func (m Model) MatchesForItem(index int) []int {
484485
return m.filteredItems[index].matches
485486
}
486487

487-
// Index returns the index of the currently selected item as it appears in the
488-
// entire slice of items.
488+
// Index returns the index of the currently selected item as it is stored in the
489+
// filtered list of items.
490+
// Using this value with SetItem() might be incorrect, consider using
491+
// GlobalIndex() instead.
489492
func (m Model) Index() int {
490493
return m.Paginator.Page*m.Paginator.PerPage + m.cursor
491494
}
492495

496+
// GlobalIndex returns the index of the currently selected item as it is stored
497+
// in the unfiltered list of items. This value can be used with SetItem().
498+
func (m Model) GlobalIndex() int {
499+
index := m.Index()
500+
501+
if m.filteredItems == nil || index >= len(m.filteredItems) {
502+
return index
503+
}
504+
505+
return m.filteredItems[index].index
506+
}
507+
493508
// Cursor returns the index of the cursor on the current page.
494509
func (m Model) Cursor() int {
495510
return m.cursor
@@ -1256,6 +1271,7 @@ func filterItems(m Model) tea.Cmd {
12561271
filterMatches := []filteredItem{}
12571272
for _, r := range m.Filter(m.FilterInput.Value(), targets) {
12581273
filterMatches = append(filterMatches, filteredItem{
1274+
index: r.Index,
12591275
item: items[r.Index],
12601276
matches: r.MatchedIndexes,
12611277
})

0 commit comments

Comments
 (0)