-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtui.go
116 lines (105 loc) · 2.25 KB
/
tui.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package tui
import (
"bytes"
"fmt"
"github.com/charmbracelet/bubbles/key"
tea "github.com/charmbracelet/bubbletea"
"os"
"strings"
)
type Mode int
const (
ModeFunc Mode = iota
ModeConsole
)
type Model struct {
FuncModel tea.Model
Help HelpModel
*bytes.Buffer
console tea.Model
currentMode Mode
isConsole bool
}
func NewModel(funcModel tea.Model, handler func(value string), isConsole bool, isShortHelp bool) Model {
consoleModel := NewConsoleModel()
consoleModel = consoleModel.OnEnter(handler)
return Model{
FuncModel: funcModel,
Help: NewHelpModel(isShortHelp),
console: consoleModel,
isConsole: isConsole,
Buffer: bytes.NewBuffer([]byte{}),
}
}
func (t Model) Run() error {
p := tea.NewProgram(t)
_, err := p.Run()
if err != nil {
return err
}
fmt.Printf(HelpStyle("<Press enter to exit>\n"))
os.Stdin.Write([]byte("\n"))
ClearLines(1)
return nil
}
func (t Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch t.currentMode {
case ModeFunc:
if msg.String() == ":" {
if t.isConsole {
t.currentMode = ModeConsole
return t, nil
}
} else if msg.String() == "enter" || msg.String() == "ctrl+c" || msg.String() == "ctrl+q" ||
msg.String() == "esc" {
t.Help.Quitting = true
}
case ModeConsole:
if msg.String() == "esc" {
t.currentMode = ModeFunc
return t, nil
}
}
switch {
case key.Matches(msg, DefaultKeys.Help):
t.Help.Model.ShowAll = !t.Help.Model.ShowAll
return t, nil
}
}
switch t.currentMode {
case ModeFunc:
newFuncModel, cmd := t.FuncModel.Update(msg)
t.FuncModel = newFuncModel
return t, cmd
case ModeConsole:
newConsoleModel, _ := t.console.Update(msg)
t.console = newConsoleModel
switch msg := msg.(type) {
case tea.KeyMsg:
if msg.Type == tea.KeyEnter {
t.currentMode = ModeFunc
}
t.console.Update(tea.Quit())
}
return t, nil
}
return t, nil
}
func (t Model) View() string {
var s strings.Builder
s.WriteString(t.FuncModel.View())
s.WriteString(t.Help.View())
switch t.currentMode {
case ModeFunc:
case ModeConsole:
s.WriteString(t.console.View())
default:
}
s.WriteString(t.Buffer.String())
return s.String()
}
func (t Model) Init() tea.Cmd {
return nil
}