2021-02-26 18:38:52 -05:00
|
|
|
package main
|
|
|
|
|
2022-10-11 08:40:01 -04:00
|
|
|
// An example illustrating how to pipe in data to a Bubble Tea application.
|
2021-05-01 09:28:58 -04:00
|
|
|
// Moreso, this serves as proof that Bubble Tea will automatically listen for
|
|
|
|
// keystrokes when input is not a TTY, such as when data is piped or redirected
|
|
|
|
// in.
|
2021-02-26 18:38:52 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/charmbracelet/bubbles/textinput"
|
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
2021-04-13 21:28:39 -04:00
|
|
|
"github.com/charmbracelet/lipgloss"
|
2021-02-26 18:38:52 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
stat, err := os.Stdin.Stat()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {
|
|
|
|
fmt.Println("Try piping in some text.")
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
|
|
var b strings.Builder
|
|
|
|
|
|
|
|
for {
|
|
|
|
r, _, err := reader.ReadRune()
|
|
|
|
if err != nil && err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
_, err = b.WriteRune(r)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("Error getting input:", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
model := newModel(strings.TrimSpace(b.String()))
|
|
|
|
|
2022-10-07 17:56:12 -04:00
|
|
|
if _, err := tea.NewProgram(model).Run(); err != nil {
|
2021-02-26 18:38:52 -05:00
|
|
|
fmt.Println("Couldn't start program:", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type model struct {
|
|
|
|
userInput textinput.Model
|
|
|
|
}
|
|
|
|
|
|
|
|
func newModel(initialValue string) (m model) {
|
2022-01-10 20:42:10 -05:00
|
|
|
i := textinput.New()
|
2021-02-26 18:38:52 -05:00
|
|
|
i.Prompt = ""
|
2021-04-13 21:28:39 -04:00
|
|
|
i.CursorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))
|
2021-02-26 18:38:52 -05:00
|
|
|
i.Width = 48
|
|
|
|
i.SetValue(initialValue)
|
|
|
|
i.CursorEnd()
|
|
|
|
i.Focus()
|
|
|
|
|
|
|
|
m.userInput = i
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m model) Init() tea.Cmd {
|
|
|
|
return textinput.Blink
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
|
|
if key, ok := msg.(tea.KeyMsg); ok {
|
|
|
|
switch key.Type {
|
|
|
|
case tea.KeyCtrlC, tea.KeyEscape, tea.KeyEnter:
|
|
|
|
return m, tea.Quit
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var cmd tea.Cmd
|
|
|
|
m.userInput, cmd = m.userInput.Update(msg)
|
|
|
|
return m, cmd
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m model) View() string {
|
|
|
|
return fmt.Sprintf(
|
|
|
|
"\nYou piped in: %s\n\nPress ^C to exit",
|
|
|
|
m.userInput.View(),
|
|
|
|
)
|
|
|
|
}
|