-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprogram.go
62 lines (52 loc) · 1.12 KB
/
program.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
package tapioca
import (
"bytes"
"io"
"sync"
tea "github.com/charmbracelet/bubbletea"
)
// Adds an io.Writer interface to tea.Program
type Program struct {
*tea.Program
buf bytes.Buffer
mutex sync.Mutex
}
func (program *Program) Write(p []byte) (int, error) {
// Buffer everything
n, err := program.buf.Write(p)
if err != nil {
return n, err
}
// Write when a new line is found
program.mutex.Lock()
defer program.mutex.Unlock()
for {
line, err := program.buf.ReadBytes('\n')
if err == io.EOF {
// Put back the read data if newline not found.
program.buf.Write(line)
return n, nil
}
if err != nil {
return n, err
}
// Print everything but the \n
program.Println(string(line[:len(line)-1]))
}
}
func (program *Program) GoRun(afterRun ...func(tea.Model, error)) *Program {
go func() {
m, err := program.Run()
for _, fn := range afterRun {
fn(m, err)
}
}()
return program
}
func (program *Program) QuitAndWait() {
program.Quit()
program.Wait()
}
func NewProgram(model tea.Model, opts ...tea.ProgramOption) *Program {
return &Program{Program: tea.NewProgram(model, opts...)}
}