Appearance
テキスト入力を受け付ける
事前準備
パッケージをインストールします:
shell
go get charm.land/bubbles/v2/textinput実装
名前を入力し、それを参照したメッセージを出力します。
Model
入力を受け付けるtextInputおよび出力メッセージ格納用のoutputを定義します。
model.go
go
package main
import "charm.land/bubbles/v2/textinput"
type model struct {
textInput textinput.Model // 入力受付
output string // 出力メッセージ
}
func initialModel() model {
ti := textinput.New()
ti.Placeholder = "Input your name..."
ti.SetVirtualCursor(true)
ti.Focus()
ti.CharLimit = 20
ti.SetWidth(20)
return model{
textInput: ti,
output: "",
}
}View
入力プロンプトおよびメッセージを出力します。
view.go
go
package main
import (
"strings"
tea "charm.land/bubbletea/v2"
)
func (m model) View() tea.View {
var s strings.Builder
if m.output != "" {
s.WriteString("\n")
s.WriteString(m.output)
s.WriteString("\n\n")
}
s.WriteString(m.textInput.View())
return tea.NewView(s.String())
}Update
キー入力を受け付け、エンターキー押下時にはメッセージを出力します。
update.go
go
package main
import (
tea "charm.land/bubbletea/v2"
)
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyPressMsg:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "enter":
m.output = "Hello, " + m.textInput.Value() + "!"
m.textInput.Reset()
m.textInput.Focus()
}
}
var cmd tea.Cmd
m.textInput, cmd = m.textInput.Update(msg)
return m, cmd
}