-
Notifications
You must be signed in to change notification settings - Fork 3
/
menu_view.go
65 lines (55 loc) · 1.36 KB
/
menu_view.go
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
package main
import (
"fmt"
"io"
)
// MenuView is a view of the current key map.
type MenuView struct {
// Entries are the menu entries that should be displayed by
// this view.
Entries []*MenuEntry
}
// NewMenuView constructs a menu view for rendering Entries.
func NewMenuView(entries []*MenuEntry) *MenuView {
return &MenuView{
Entries: entries,
}
}
// Render displays the menu on out.
func (v *MenuView) Render(out io.Writer) error {
for _, entry := range v.Entries {
_, err := fmt.Fprintf(out, "[%c] %s\n\r", entry.Key, entry.Label)
if err != nil {
return err
}
}
return nil
}
// Erase erases this menu from the terminal.
func (v *MenuView) Erase(out io.Writer) error {
for range v.Entries {
_, err := fmt.Fprintf(out, "\033[A\033[2K")
if err != nil {
return err
}
}
return nil
}
// MenuEntry represents an entry in a menu that should be displayed in a terminal.
type MenuEntry struct {
// Key that needs to be pressed to select this menu entry.
Key rune
// Label that is shown to the user, describing the menu entry
Label string
}
// NewMenuEntryForKeyBinding returns a new menu entry for a given key binding.
func NewMenuEntryForKeyBinding(binding *KeyBinding) *MenuEntry {
label := binding.description
if binding.HasChildren() {
label = binding.Children().Name()
}
return &MenuEntry{
Key: binding.key,
Label: label,
}
}