Skip to content
Myr

main.go

This file

Path

examples/dynamic-textarea/main.go

91 lines · 1.6 KiB · Go

Last changed by

docs(example): add textarea dynamic height example (#1639)Christian Rochabefore adoptionbbe4faf

History of this file

Take it

docs(example): add textarea dynamic height example (#1639)Christian Rochabefore adoptionbbe4faf

lines 1–91why, one step back
1package main
23import (4 "fmt"5 "log"6 "strings"78 "charm.land/bubbles/v2/textarea"9 tea "charm.land/bubbletea/v2"10)1112func main() {13 p := tea.NewProgram(initialModel())14 if _, err := p.Run(); err != nil {15 log.Fatal(err)16 }17}1819type model struct {20 textarea textarea.Model21}2223func initialModel() model {24 ti := textarea.New()25 ti.Placeholder = "Schnrr..."26 ti.ShowLineNumbers = true27 ti.DynamicHeight = true28 ti.MinHeight = 329 ti.MaxHeight = 1530 ti.MaxContentHeight = 2031 ti.SetWidth(60)32 ti.SetVirtualCursor(false)33 ti.Focus()3435 return model{textarea: ti}36}3738func (m model) Init() tea.Cmd {39 return tea.Batch(textarea.Blink, tea.RequestBackgroundColor)40}4142func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {43 var cmds []tea.Cmd44 var cmd tea.Cmd4546 switch msg := msg.(type) {47 case tea.BackgroundColorMsg:48 m.textarea.SetStyles(textarea.DefaultStyles(msg.IsDark()))49 case tea.KeyPressMsg:50 switch msg.String() {51 case "ctrl+c":52 return m, tea.Quit53 }54 }5556 m.textarea, cmd = m.textarea.Update(msg)57 cmds = append(cmds, cmd)58 return m, tea.Batch(cmds...)59}6061func (m model) statusView() string {62 return fmt.Sprintf(63 "\nHeight: %d · Lines: %d · Cursor: (%d, %d) · Scroll: %.0f%%",64 m.textarea.Height(),65 m.textarea.LineCount(),66 m.textarea.Line(),67 m.textarea.Column(),68 m.textarea.ScrollPercent()*100,69 )70}7172func (m model) View() tea.View {73 const gap = 17475 var c *tea.Cursor76 if !m.textarea.VirtualCursor() {77 c = m.textarea.Cursor()78 c.Y += gap79 }8081 f := strings.Repeat("\n", gap)82 f += strings.Join([]string{83 m.textarea.View(),84 m.statusView(),85 "\n(ctrl+c to quit)",86 }, "\n")8788 v := tea.NewView(f)89 v.Cursor = c90 return v91}