Skip to content
Myr

main.go

This file

Path

examples/query-term/main.go

102 lines · 2.0 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 1–102why, one step back
1// This example uses a textinput to send the terminal ANSI sequences to query
2// it for capabilities.3package main45import (6 "fmt"7 "io"8 "log"9 "os"10 "strconv"11 "strings"12 "unicode"1314 "charm.land/bubbles/v2/textinput"15 tea "charm.land/bubbletea/v2"16)1718func newModel() model {19 ti := textinput.New()20 ti.Focus()21 ti.CharLimit = 15622 ti.SetWidth(20)23 ti.SetVirtualCursor(false)24 return model{input: ti}25}2627type model struct {28 input textinput.Model29 err error30}3132func (m model) Init() tea.Cmd {33 return nil34}3536func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {37 var cmds []tea.Cmd3839 switch msg := msg.(type) {40 case tea.KeyPressMsg:41 m.err = nil42 switch msg.String() {43 case "ctrl+c":44 return m, tea.Quit45 case "enter":46 // Write the sequence to the terminal.47 val := m.input.Value()48 val = "\"" + val + "\""4950 // Unescape the sequence.51 seq, err := strconv.Unquote(val)52 if err != nil {53 m.err = err54 return m, nil55 }5657 if !strings.HasPrefix(seq, "\x1b") {58 m.err = fmt.Errorf("sequence is not an ANSI escape sequence")59 return m, nil60 }6162 m.input.SetValue("")6364 // Write the sequence to the terminal.65 return m, func() tea.Msg {66 io.WriteString(os.Stdout, seq)67 return nil68 }69 }70 default:71 _, typ, ok := strings.Cut(fmt.Sprintf("%T", msg), ".")72 if ok && unicode.IsUpper(rune(typ[0])) {73 // Only log messages that are exported types.74 cmds = append(cmds, tea.Printf("Received message: %T %+v", msg, msg))75 }76 }7778 var cmd tea.Cmd79 m.input, cmd = m.input.Update(msg)80 cmds = append(cmds, cmd)8182 return m, tea.Batch(cmds...)83}8485func (m model) View() tea.View {86 var s strings.Builder87 s.WriteString(m.input.View())88 if m.err != nil {89 s.WriteString("\n\nError: " + m.err.Error())90 }91 s.WriteString("\n\nPress ctrl+c to quit, enter to write the sequence to terminal")92 v := tea.NewView(s.String())93 v.Cursor = m.input.Cursor()94 return v95}9697func main() {98 p := tea.NewProgram(newModel())99 if _, err := p.Run(); err != nil {100 log.Fatal(err)101 }102}