1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-14 11:23:09 +02:00
lazygit/pkg/gui/context/suggestions_context.go

91 lines
2.3 KiB
Go
Raw Normal View History

2022-02-05 08:04:10 +02:00
package context
import (
2023-03-21 11:57:52 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
2022-02-05 08:04:10 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/types"
2023-03-21 11:57:52 +02:00
"github.com/jesseduffield/lazygit/pkg/tasks"
2022-02-05 08:04:10 +02:00
)
type SuggestionsContext struct {
*ListViewModel[*types.Suggestion]
2022-02-05 08:04:10 +02:00
*ListContextTrait
2023-03-21 11:57:52 +02:00
State *SuggestionsContextState
}
type SuggestionsContextState struct {
Suggestions []*types.Suggestion
OnConfirm func() error
OnClose func() error
AsyncHandler *tasks.AsyncHandler
// FindSuggestions will take a string that the user has typed into a prompt
// and return a slice of suggestions which match that string.
FindSuggestions func(string) []*types.Suggestion
2022-02-05 08:04:10 +02:00
}
var _ types.IListContext = (*SuggestionsContext)(nil)
func NewSuggestionsContext(
c *ContextCommon,
2022-02-05 08:04:10 +02:00
) *SuggestionsContext {
2023-03-21 11:57:52 +02:00
state := &SuggestionsContextState{
AsyncHandler: tasks.NewAsyncHandler(c.OnWorker),
2023-03-21 11:57:52 +02:00
}
getModel := func() []*types.Suggestion {
return state.Suggestions
}
getDisplayStrings := func(startIdx int, length int) [][]string {
return presentation.GetSuggestionListDisplayStrings(state.Suggestions)
}
viewModel := NewListViewModel(getModel)
2022-02-05 08:04:10 +02:00
return &SuggestionsContext{
State: state,
ListViewModel: viewModel,
2022-02-05 08:04:10 +02:00
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
2023-03-21 11:57:52 +02:00
View: c.Views().Suggestions,
2022-08-07 11:13:19 +02:00
WindowName: "suggestions",
Key: SUGGESTIONS_CONTEXT_KEY,
Kind: types.PERSISTENT_POPUP,
Focusable: true,
HasUncontrolledBounds: true,
2023-03-21 12:01:58 +02:00
})),
2022-02-05 08:04:10 +02:00
list: viewModel,
getDisplayStrings: getDisplayStrings,
c: c,
},
}
}
func (self *SuggestionsContext) GetSelectedItemId() string {
item := self.GetSelected()
if item == nil {
return ""
}
return item.Value
}
2023-03-21 11:57:52 +02:00
func (self *SuggestionsContext) SetSuggestions(suggestions []*types.Suggestion) {
self.State.Suggestions = suggestions
self.SetSelectedLineIdx(0)
self.c.ResetViewOrigin(self.GetView())
_ = self.HandleRender()
}
func (self *SuggestionsContext) RefreshSuggestions() {
self.State.AsyncHandler.Do(func() func() {
findSuggestionsFn := self.State.FindSuggestions
if findSuggestionsFn != nil {
suggestions := findSuggestionsFn(self.c.GetPromptInput())
return func() { self.SetSuggestions(suggestions) }
} else {
return func() {}
}
})
}