1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-01-26 05:37:18 +02:00
lazygit/pkg/gui/context/suggestions_context.go

93 lines
2.3 KiB
Go
Raw Normal View History

2022-02-05 17:04:10 +11:00
package context
import (
2023-03-21 20:57:52 +11:00
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
2022-02-05 17:04:10 +11:00
"github.com/jesseduffield/lazygit/pkg/gui/types"
2023-03-21 20:57:52 +11:00
"github.com/jesseduffield/lazygit/pkg/tasks"
2022-02-05 17:04:10 +11:00
)
type SuggestionsContext struct {
*ListViewModel[*types.Suggestion]
2022-02-05 17:04:10 +11:00
*ListContextTrait
2023-03-21 20:57:52 +11: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 17:04:10 +11:00
}
var _ types.IListContext = (*SuggestionsContext)(nil)
func NewSuggestionsContext(
c *ContextCommon,
2022-02-05 17:04:10 +11:00
) *SuggestionsContext {
2023-03-21 20:57:52 +11:00
state := &SuggestionsContextState{
AsyncHandler: tasks.NewAsyncHandler(c.OnWorker),
2023-03-21 20:57:52 +11:00
}
getModel := func() []*types.Suggestion {
return state.Suggestions
}
getDisplayStrings := func(_ int, _ int) [][]string {
2023-03-21 20:57:52 +11:00
return presentation.GetSuggestionListDisplayStrings(state.Suggestions)
}
viewModel := NewListViewModel(getModel)
2022-02-05 17:04:10 +11:00
return &SuggestionsContext{
State: state,
ListViewModel: viewModel,
2022-02-05 17:04:10 +11:00
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
2023-03-21 20:57:52 +11:00
View: c.Views().Suggestions,
2022-08-07 19:13:19 +10:00
WindowName: "suggestions",
Key: SUGGESTIONS_CONTEXT_KEY,
Kind: types.PERSISTENT_POPUP,
Focusable: true,
HasUncontrolledBounds: true,
2023-03-21 21:01:58 +11:00
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
2022-02-05 17:04:10 +11:00
},
}
}
func (self *SuggestionsContext) GetSelectedItemId() string {
item := self.GetSelected()
if item == nil {
return ""
}
return item.Value
}
2023-03-21 20:57:52 +11: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() {}
}
})
}