summaryrefslogtreecommitdiffstats
path: root/runtime/ui/components/keybinding_primitive.go
blob: 30966f373075e021343ea1239195171ac9ca8cb3 (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
91
92
93
94
95
96
97
98
package components

import (
	"fmt"
	"strings"

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
	"github.com/sirupsen/logrus"
	"github.com/wagoodman/dive/runtime/ui/format"
)

type BoundView interface {
	HasFocus() bool
	GetKeyBindings() []KeyBindingDisplay
}

type KeyMenuView struct {
	*tview.TextView
	boundList []BoundView
}

func NewKeyMenuView() *KeyMenuView {
	return &KeyMenuView{
		TextView:  tview.NewTextView(),
		boundList: []BoundView{},
	}
}

func (t *KeyMenuView) AddBoundViews(b ...BoundView) *KeyMenuView {
	t.boundList = append(t.boundList, b...)
	return t
}

func (t *KeyMenuView) RemoveViews(b ...BoundView) *KeyMenuView {
	newBoundList := []BoundView{}
	boundSet := map[BoundView]interface{}{}
	for _, v := range b {
		boundSet[v] = true
	}

	for _, bound := range t.boundList {
		if _, ok := boundSet[bound]; !ok {
			newBoundList = append(newBoundList, bound)
		}
	}

	t.boundList = newBoundList
	return t
}

func (t *KeyMenuView) GetKeyBindings() []KeyBindingDisplay {
	logrus.Debug("Getting binding keys from keybinding primitive")
	result := []KeyBindingDisplay{}
	for _, view := range t.boundList {
		if view.HasFocus() {
			result = append(result, view.GetKeyBindings()...)
		}
	}

	return result
}

func (t *KeyMenuView) Draw(screen tcell.Screen) {
	t.Box.Draw(screen)
	x, y, width, _ := t.Box.GetInnerRect()
	// TODO: add logic to highlight selected options

	lines := []string{}
	keyBindings := t.GetKeyBindings()
	for idx, binding := range keyBindings {
		if binding.Hide {
			continue
		}
		displayFormatter := format.StatusControlNormal
		keyBindingFormatter := format.StatusControlNormalBold
		if binding.Selected {
			displayFormatter = format.StatusControlSelected
			keyBindingFormatter = format.StatusControlSelectedBold
		}
		postfix := "⎹"
		//postfix := "▏"
		if idx == len(keyBindings)-1 {
			postfix = " "
		}
		prefix :=  " "
		if idx == 0 {
			prefix = ""
		}
		keyBindingContent := keyBindingFormatter(prefix + binding.Name() + " ")
		displayContnet := displayFormatter(binding.Display + postfix)
		lines = append(lines, fmt.Sprintf("%s%s", keyBindingContent, displayContnet))
	}
	joinedLine := strings.Join(lines, "")
	_, w := tview.PrintWithStyle(screen, joinedLine, x, y, width, tview.AlignLeft, tcell.StyleDefault)
	format.PrintLine(screen, format.StatusControlNormal(strings.Repeat(" ", intMax(0,width-w))), x+w, y, width, tview.AlignLeft, tcell.StyleDefault)

}