main.go
This file
Path
examples/textarea/main.go
112 lines · 2.0 KiB · Go
Last changed by
fix(examples): resolve nil pointer dereference (#1663)Matthew Caswellbefore adoptionee06e98
History of this fileTake it
1package main23// A simple program demonstrating the textarea component from the Bubbles4// component library.56import (7 "log"8 "strings"910 "charm.land/bubbles/v2/textarea"11 tea "charm.land/bubbletea/v2"12 "charm.land/lipgloss/v2"13)1415func main() {16 p := tea.NewProgram(initialModel())1718 if _, err := p.Run(); err != nil {19 log.Fatal(err)20 }21}2223type errMsg error2425type model struct {26 textarea textarea.Model27 err error28}2930func initialModel() model {31 ti := textarea.New()32 ti.Placeholder = "Once upon a time..."33 ti.SetVirtualCursor(false)34 ti.SetStyles(textarea.DefaultStyles(true)) // default to dark styles.35 ti.Focus()3637 return model{38 textarea: ti,39 err: nil,40 }41}4243func (m model) Init() tea.Cmd {44 return tea.Batch(textarea.Blink, tea.RequestBackgroundColor)45}4647func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {48 var cmds []tea.Cmd49 var cmd tea.Cmd5051 switch msg := msg.(type) {52 case tea.BackgroundColorMsg:53 // Update styling now that we know the background color.54 m.textarea.SetStyles(textarea.DefaultStyles(msg.IsDark()))5556 case tea.KeyPressMsg:57 switch msg.String() {58 case "esc":59 if m.textarea.Focused() {60 m.textarea.Blur()61 }62 case "ctrl+c":63 return m, tea.Quit64 default:65 if !m.textarea.Focused() {66 cmd = m.textarea.Focus()67 cmds = append(cmds, cmd)68 }69 }7071 // We handle errors just like any other message72 case errMsg:73 m.err = msg74 return m, nil75 }7677 m.textarea, cmd = m.textarea.Update(msg)78 cmds = append(cmds, cmd)79 return m, tea.Batch(cmds...)80}8182func (m model) headerView() string {83 return "Tell me a story.\n"84}8586func (m model) View() tea.View {87 const (88 footer = "\n(ctrl+c to quit)\n"89 )9091 var c *tea.Cursor92 if !m.textarea.VirtualCursor() {93 c = m.textarea.Cursor()9495 if c != nil {96 // Set the y offset of the cursor based on the position of the textarea97 // in the application.98 offset := lipgloss.Height(m.headerView())99 c.Y += offset100 }101 }102103 f := strings.Join([]string{104 m.headerView(),105 m.textarea.View(),106 footer,107 }, "\n")108109 v := tea.NewView(f)110 v.Cursor = c111 return v112}