-
Notifications
You must be signed in to change notification settings - Fork 4
/
fileinput.go
128 lines (110 loc) · 2.27 KB
/
fileinput.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
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"io"
"os"
)
const (
ReadMode = iota
WriteMode
)
type FileInput struct {
id int
mode int
widget textinput.Model
visible bool
}
type OpenFileReadMsg struct{ Id int }
type OpenFileWriteMsg struct{ Id int }
func (f *FileInput) OpenFile() tea.Cmd {
switch f.mode {
case ReadMode:
return func() tea.Msg {
return OpenFileReadMsg{f.id}
}
case WriteMode:
return func() tea.Msg {
return OpenFileWriteMsg{f.id}
}
}
return nil
}
func (f *FileInput) SetTitle(s string) {
f.widget.Prompt = s
}
func (f *FileInput) SetVisible() {
f.visible = true
}
func (f *FileInput) Hide() {
f.widget.Blur()
f.visible = false
}
func (f *FileInput) IsVisible() bool {
return f.visible
}
func (f *FileInput) Focus() {
f.widget.Focus()
}
func (f *FileInput) Value() string {
return f.widget.Value()
}
func (f *FileInput) Reset() {
f.widget.Reset()
}
func (f *FileInput) Blur() {
f.widget.Blur()
}
func (f FileInput) View() string {
return f.widget.View()
}
func NewFileInput(id, mode int, title, placeholder string, colors ...lipgloss.Color) FileInput {
w := textinput.New()
w.Prompt = title
w.Placeholder = placeholder
w.Width = 25
w.PromptStyle = lipgloss.NewStyle().Foreground(colors[0]).Bold(true)
w.PlaceholderStyle = lipgloss.NewStyle().Foreground(colors[1])
w.TextStyle = lipgloss.NewStyle().Foreground(colors[2])
return FileInput{id: id, mode: mode, widget: w}
}
type FileInputReader struct {
Id int
Reader io.ReadCloser
Error error
Path string
}
type FileInputWriter struct {
Id int
Writer io.WriteCloser
Error error
Path string
}
func (f FileInput) Update(msg tea.Msg) (FileInput, tea.Cmd) {
var c1, c2 tea.Cmd
switch msg := msg.(type) {
case OpenFileReadMsg:
if msg.Id != f.id {
return f, nil
}
p := f.widget.Value()
r, err := os.Open(p)
c2 = func() tea.Msg {
return FileInputReader{f.id, r, err, p}
}
f.Hide()
case OpenFileWriteMsg:
if msg.Id != f.id {
return f, nil
}
p := f.widget.Value()
w, err := os.Create(p)
c2 = func() tea.Msg {
return FileInputWriter{f.id, w, err, p}
}
f.Hide()
}
f.widget, c1 = f.widget.Update(msg)
return f, tea.Batch(c1, c2)
}