-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathlist.go
More file actions
99 lines (80 loc) · 1.81 KB
/
list.go
File metadata and controls
99 lines (80 loc) · 1.81 KB
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
//go:build !wasm
package interactive
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"strings"
tea "github.com/charmbracelet/bubbletea"
)
type ListPrompt struct {
// Prompt that will be printed when showing the list
Prompt string
Choices []string
// DefaultIndex is the element that will be selected when starting prompt
DefaultIndex int
cursor int
cancelled bool
}
func (m *ListPrompt) Init() tea.Cmd {
return nil
}
func (m *ListPrompt) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg, ok := msg.(tea.KeyMsg); ok {
// Key is pressed
switch msg.String() {
case "ctrl+c", "q":
m.cancelled = true
return m, tea.Quit
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(m.Choices)-1 {
m.cursor++
}
case "enter", " ":
return m, tea.Quit
}
}
return m, nil
}
func (m *ListPrompt) View() string {
var builder strings.Builder
builder.WriteString(m.Prompt + "\n\n")
for i, choice := range m.Choices {
if m.cursor == i {
fmt.Fprintf(&builder, "> %s\n", choice)
} else {
builder.WriteString(choice + "\n")
}
}
builder.WriteString("\nPress enter or space for select.\n")
return builder.String()
}
// Execute start the prompt and return the selected index
func (m *ListPrompt) Execute(ctx context.Context) (int, error) {
m.cursor = m.DefaultIndex
opts := []tea.ProgramOption{
tea.WithContext(ctx),
}
if hasMockedResponse(ctx) {
opts = append(opts, tea.WithInput(&mockResponseReader{
ctx: ctx,
defaultReader: os.Stdin,
}))
opts = append(opts, tea.WithOutput(bytes.NewBuffer([]byte{})))
}
p := tea.NewProgram(m, opts...)
_, err := p.Run()
if err != nil {
return -1, fmt.Errorf("error running prompt: %w", err)
}
if m.cancelled {
return -1, errors.New("prompt cancelled")
}
return m.cursor, nil
}