summaryrefslogtreecommitdiffstats
path: root/pkg/gui/context/suggestions_context.go
blob: 8a28ce51479a7abc71313d8a57850c5e24f9c9bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package context

import (
	"github.com/jesseduffield/lazygit/pkg/gui/presentation"
	"github.com/jesseduffield/lazygit/pkg/gui/types"
	"github.com/jesseduffield/lazygit/pkg/tasks"
)

type SuggestionsContext struct {
	*BasicViewModel[*types.Suggestion]
	*ListContextTrait

	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
}

var _ types.IListContext = (*SuggestionsContext)(nil)

func NewSuggestionsContext(
	c *types.HelperCommon,
) *SuggestionsContext {
	state := &SuggestionsContextState{
		AsyncHandler: tasks.NewAsyncHandler(),
	}
	getModel := func() []*types.Suggestion {
		return state.Suggestions
	}

	getDisplayStrings := func(startIdx int, length int) [][]string {
		return presentation.GetSuggestionListDisplayStrings(state.Suggestions)
	}

	viewModel := NewBasicViewModel(getModel)

	return &SuggestionsContext{
		State:          state,
		BasicViewModel: viewModel,
		ListContextTrait: &ListContextTrait{
			Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
				View:                  c.Views().Suggestions,
				WindowName:            "suggestions",
				Key:                   SUGGESTIONS_CONTEXT_KEY,
				Kind:                  types.PERSISTENT_POPUP,
				Focusable:             true,
				HasUncontrolledBounds: true,
			}), ContextCallbackOpts{}),
			list:              viewModel,
			getDisplayStrings: getDisplayStrings,
			c:                 c,
		},
	}
}

func (self *SuggestionsContext) GetSelectedItemId() string {
	item := self.GetSelected()
	if item == nil {
		return ""
	}

	return item.Value
}

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() {}
		}
	})
}