Skip to content

Instantly share code, notes, and snippets.

@bashbunni
Created January 11, 2023 03:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bashbunni/4573b0fc981123875a835f1a0aa412ca to your computer and use it in GitHub Desktop.
ValidateFunc Blocking Workaround
package main
import (
"fmt"
"log"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const maxWidth = 20
type errMsg error
var quitKeys = key.NewBinding(
key.WithKeys("q", "esc", "ctrl+c"),
key.WithHelp("", "press q to quit"),
)
var errStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("24")).Render
type model struct {
input textinput.Model
err errMsg
}
/*
using textinput.Validate; causes blocking behaviour for invalid strings
func checkLength() textinput.ValidateFunc {
return func(s string) error {
if len(s) > 0 {
letter := rune(s[0])
if !unicode.IsLetter(letter) {
return errors.New("not valid input")
}
}
return nil
}
}
*/
func checkLength(s string) error {
if len(s) > 10 {
return fmt.Errorf("length should be less than 10. current: %d", len(s))
}
return nil
}
func New() model {
input := textinput.New()
input.Focus()
input.Width = 50
return model{input, nil}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
if key.Matches(msg, quitKeys) {
return m, tea.Quit
}
case errMsg:
m.err = msg
return m, nil
}
m.input, cmd = m.input.Update(msg)
// if we were using textinput validate:
// m.err = m.input.Validate(m.input.Value())
m.err = checkLength(m.input.Value())
return m, cmd
}
func (m model) View() string {
if m.err != nil {
return lipgloss.JoinVertical(lipgloss.Left, m.input.View(), errStyle(m.err.Error()))
}
return m.input.View()
}
func main() {
p := tea.NewProgram(New())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment