1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-03-25 22:01:14 +02:00
lazygit/pkg/gui/context/list_view_model.go
Jesse Duffield a5f3515ad8 Set groundwork for better disabled reasons with range select
Something dumb that we're currently doing is expecting list items
to define an ID method which returns a string. We use that when copying
items to clipboard with ctrl+o and when getting a ref name for diffing.

This commit gets us a little deeper into that hole by explicitly requiring
list items to implement that method so that we can easily use the new
helper functions in list_controller_trait.go.

In future we need to just remove the whole ID thing entirely but I'm too
lazy to do that right now.
2024-01-23 13:03:37 +11:00

80 lines
1.5 KiB
Go

package context
import (
"github.com/jesseduffield/lazygit/pkg/gui/context/traits"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type HasID interface {
ID() string
}
type ListViewModel[T HasID] struct {
*traits.ListCursor
getModel func() []T
}
func NewListViewModel[T HasID](getModel func() []T) *ListViewModel[T] {
self := &ListViewModel[T]{
getModel: getModel,
}
self.ListCursor = traits.NewListCursor(self)
return self
}
func (self *ListViewModel[T]) Len() int {
return len(self.getModel())
}
func (self *ListViewModel[T]) GetSelected() T {
if self.Len() == 0 {
return Zero[T]()
}
return self.getModel()[self.GetSelectedLineIdx()]
}
func (self *ListViewModel[T]) GetSelectedItemId() string {
if self.Len() == 0 {
return ""
}
return self.GetSelected().ID()
}
func (self *ListViewModel[T]) GetSelectedItems() ([]T, int, int) {
if self.Len() == 0 {
return nil, -1, -1
}
startIdx, endIdx := self.GetSelectionRange()
return self.getModel()[startIdx : endIdx+1], startIdx, endIdx
}
func (self *ListViewModel[T]) GetSelectedItemIds() ([]string, int, int) {
selectedItems, startIdx, endIdx := self.GetSelectedItems()
ids := lo.Map(selectedItems, func(item T, _ int) string {
return item.ID()
})
return ids, startIdx, endIdx
}
func (self *ListViewModel[T]) GetItems() []T {
return self.getModel()
}
func Zero[T any]() T {
return *new(T)
}
func (self *ListViewModel[T]) GetItem(index int) types.HasUrn {
item := self.getModel()[index]
return any(item).(types.HasUrn)
}