mirror of
https://github.com/taigrr/bubbletea.git
synced 2026-04-02 02:59:09 -07:00
doc: Add textarea examples (#357)
* chore: bump bubbles@master * doc(textarea): Add example of `chat` application with textarea * doc(textarea): Add example of `textarea` prompting the user to tell a story * doc(textarea): Add example of `split-editors` on how to manage multiple textareas
This commit is contained in:
82
examples/textarea/main.go
Normal file
82
examples/textarea/main.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
// A simple program demonstrating the text input component from the Bubbles
|
||||
// component library.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textarea"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
func main() {
|
||||
p := tea.NewProgram(initialModel())
|
||||
|
||||
if err := p.Start(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type tickMsg struct{}
|
||||
type errMsg error
|
||||
|
||||
type model struct {
|
||||
textarea textarea.Model
|
||||
err error
|
||||
}
|
||||
|
||||
func initialModel() model {
|
||||
ti := textarea.New()
|
||||
ti.Placeholder = "Once upon a time..."
|
||||
ti.Focus()
|
||||
|
||||
return model{
|
||||
textarea: ti,
|
||||
err: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func (m model) Init() tea.Cmd {
|
||||
return textarea.Blink
|
||||
}
|
||||
|
||||
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
var cmds []tea.Cmd
|
||||
var cmd tea.Cmd
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.Type {
|
||||
case tea.KeyEsc:
|
||||
if m.textarea.Focused() {
|
||||
m.textarea.Blur()
|
||||
}
|
||||
case tea.KeyCtrlC:
|
||||
return m, tea.Quit
|
||||
default:
|
||||
if !m.textarea.Focused() {
|
||||
cmd = m.textarea.Focus()
|
||||
cmds = append(cmds, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// We handle errors just like any other message
|
||||
case errMsg:
|
||||
m.err = msg
|
||||
return m, nil
|
||||
}
|
||||
|
||||
m.textarea, cmd = m.textarea.Update(msg)
|
||||
cmds = append(cmds, cmd)
|
||||
return m, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func (m model) View() string {
|
||||
return fmt.Sprintf(
|
||||
"Tell me a story.\n\n%s\n\n%s",
|
||||
m.textarea.View(),
|
||||
"(ctrl+c to quit)",
|
||||
) + "\n\n"
|
||||
}
|
||||
Reference in New Issue
Block a user