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
This commit is contained in:
nobe4
2024-07-31 12:10:37 +02:00
parent a9344b5953
commit 1fc1edf21d
+14
View File
@@ -52,6 +52,7 @@ type ItemDelegate interface {
}
type filteredItem struct {
index int // index in the unfiltered list
item Item // item matched
matches []int // rune indices of matched items
}
@@ -461,6 +462,18 @@ func (m Model) Index() int {
return m.Paginator.Page*m.Paginator.PerPage + m.cursor
}
// GlobalIndex returns the index of the currently selected item as it is stored
// in the unfiltered list of items. This value can be used with SetItem().
func (m Model) GlobalIndex() int {
index := m.Index()
if m.filteredItems == nil || index >= len(m.filteredItems) {
return index
}
return m.filteredItems[index].index
}
// Cursor returns the index of the cursor on the current page.
func (m Model) Cursor() int {
return m.cursor
@@ -1227,6 +1240,7 @@ func filterItems(m Model) tea.Cmd {
filterMatches := []filteredItem{}
for _, r := range m.Filter(m.FilterInput.Value(), targets) {
filterMatches = append(filterMatches, filteredItem{
index: r.Index,
item: items[r.Index],
matches: r.MatchedIndexes,
})