GoSetup-bubble/setup/fields/input.go

73 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package fields
import (
"fmt"
"github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// InputModel структура описывающая модель поля ввода данных
type InputModel struct {
label string
description string
input textinput.Model
}
type FieldValidator func(value any) error
// NewInputModel создает новую модель поля ввода данных
func NewInputModel(label, value, description string, validator textinput.ValidateFunc) *InputModel {
t := textinput.New()
t.Validate = validator
t.SetValue(value)
t.Cursor.SetMode(cursor.CursorBlink)
return &InputModel{
label: label,
description: description,
input: t,
}
}
func (m *InputModel) Init() tea.Cmd {
return textinput.Blink
}
// Update отслеживает действия с полем
func (m *InputModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
var cmd tea.Cmd
m.input, cmd = m.input.Update(msg)
return m, cmd
}
func (m *InputModel) View() string {
res := fmt.Sprintf("%s: %v", m.label, m.input.View())
if m.input.Err != nil {
res += fmt.Sprintf("\nОшибка валидации: %s", m.input.Err)
} else if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
return res
}
func (m *InputModel) Focus() {
m.input.Focus()
}
func (m *InputModel) Blur() {
m.input.Blur()
}
func (m *InputModel) CaptureKeys() bool {
//return m.input.Focused()
return false
}
func (m *InputModel) GetLabel() string {
return m.label
}
func (m *InputModel) GetValue() interface{} {
return m.input.Value()
}