Skip to content

Commit bcf1f6d

Browse files
committed
docs(example): add textarea dynamic height example
1 parent f8926a7 commit bcf1f6d

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

examples/dynamic-textarea/main.go

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"strings"
7+
8+
"charm.land/bubbles/v2/textarea"
9+
tea "charm.land/bubbletea/v2"
10+
)
11+
12+
func main() {
13+
p := tea.NewProgram(initialModel())
14+
if _, err := p.Run(); err != nil {
15+
log.Fatal(err)
16+
}
17+
}
18+
19+
type model struct {
20+
textarea textarea.Model
21+
}
22+
23+
func initialModel() model {
24+
ti := textarea.New()
25+
ti.Placeholder = "Schnrr..."
26+
ti.ShowLineNumbers = true
27+
ti.DynamicHeight = true
28+
ti.MinHeight = 3
29+
ti.MaxHeight = 15
30+
ti.MaxContentHeight = 20
31+
ti.SetWidth(60)
32+
ti.SetVirtualCursor(false)
33+
ti.Focus()
34+
35+
return model{textarea: ti}
36+
}
37+
38+
func (m model) Init() tea.Cmd {
39+
return tea.Batch(textarea.Blink, tea.RequestBackgroundColor)
40+
}
41+
42+
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
43+
var cmds []tea.Cmd
44+
var cmd tea.Cmd
45+
46+
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.Quit
53+
}
54+
}
55+
56+
m.textarea, cmd = m.textarea.Update(msg)
57+
cmds = append(cmds, cmd)
58+
return m, tea.Batch(cmds...)
59+
}
60+
61+
func (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+
}
71+
72+
func (m model) View() tea.View {
73+
const gap = "\n"
74+
75+
var c *tea.Cursor
76+
if !m.textarea.VirtualCursor() {
77+
c = m.textarea.Cursor()
78+
c.Y += 1 // account for gap
79+
}
80+
81+
f := gap
82+
f += strings.Join([]string{
83+
m.textarea.View(),
84+
m.statusView(),
85+
"\n(ctrl+c to quit)",
86+
}, "\n")
87+
88+
v := tea.NewView(f)
89+
v.Cursor = c
90+
return v
91+
}

0 commit comments

Comments
 (0)