GoSetup-bubble/setup/fields/select.go

158 lines
3.9 KiB
Go
Raw Normal View History

2025-12-26 17:45:37 +05:00
package fields
import (
"bubble/setup/utils"
2025-12-26 17:45:37 +05:00
"fmt"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// SelectModel структура описывающая модель поля выбора опции
2025-12-26 17:45:37 +05:00
type SelectModel struct {
label string //Имя поля
description string //Описание пол
options []string //Элементы выбора
focus int //Фокус для управления опциями
open bool //Открыт ли список
chosen string //Выбранный элемент
optionsCount int //Количество элементов к показу
validate textinput.ValidateFunc
err error
2025-12-26 17:45:37 +05:00
}
// NewSelectModel создаем новую поля выбора опции
func NewSelectModel(label, value, description string, options []string, validator textinput.ValidateFunc) *SelectModel {
//Проверка, что указанный по умолчанию элемент есть в списке опции
selectModel := &SelectModel{
options: options,
label: label,
description: description,
focus: len(options),
validate: validator,
optionsCount: 10,
}
2025-12-26 17:45:37 +05:00
found := false
for i := range options {
if options[i] == value {
found = true
}
}
if !found {
value = ""
}
selectModel.chosen = value
selectModel.SelectValidate()
return selectModel
2025-12-26 17:45:37 +05:00
}
func (m *SelectModel) Init() tea.Cmd {
return textinput.Blink
}
func (m *SelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
//Отслеживаем нажатия клавиш.
//Если список открыт, то отслеживаем клавиши отдельно
2025-12-26 17:45:37 +05:00
if m.open {
switch msg.String() {
case "esc":
//Закрываем список
2025-12-26 17:45:37 +05:00
m.open = false
case "up":
//Уменьшаем фокус, поднимаем его
2025-12-26 17:45:37 +05:00
m.focus--
if m.focus < 0 {
m.focus = len(m.options) - 1
}
case "down":
//Увеличиваем фокус, опускаем его
2025-12-26 17:45:37 +05:00
m.focus++
if m.focus == len(m.options) {
m.focus = 0
}
case "enter":
//Выбираем опцию из списка
if len(m.options) == 0 || m.focus >= len(m.options) {
2025-12-26 17:45:37 +05:00
return m, nil
}
m.chosen = m.options[m.focus]
m.open = false
m.focus = 0
m.SelectValidate()
return m, nil
2025-12-26 17:45:37 +05:00
}
} else {
//Если список не открыт и был нажат enter, открываем его и устанавливаем фокус на основе опций.
2025-12-26 17:45:37 +05:00
switch msg.String() {
case "enter":
m.open = true
for optionIdx := range m.options {
if m.options[optionIdx] == m.chosen {
m.focus = optionIdx
}
}
if m.chosen == "" && len(m.options) > 0 {
m.focus = 0
}
}
}
}
return m, cmd
}
func (m *SelectModel) View() string {
res := fmt.Sprintf("%s: %s", m.label, m.chosen)
if m.err != nil && !m.open {
res += fmt.Sprintf("\nОшибка валидации: %s", m.err)
} else if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
2025-12-26 17:45:37 +05:00
if m.open && len(m.options) > 0 {
start, end := utils.CalculateSelectOptionsIndex(m.focus, m.optionsCount, len(m.options))
for i := start; i < end; i++ {
option := m.options[i]
prefix := "\n\t"
2025-12-26 17:45:37 +05:00
if m.focus == i {
prefix += "-> "
2025-12-26 17:45:37 +05:00
} else {
prefix += " "
2025-12-26 17:45:37 +05:00
}
res += prefix + option
2025-12-26 17:45:37 +05:00
}
}
return res
}
func (m *SelectModel) Close() {
m.open = false
}
func (m *SelectModel) Focus() {
}
func (m *SelectModel) Blur() {
m.open = false
}
func (m *SelectModel) CaptureKeys() bool {
return m.open
}
func (m *SelectModel) GetLabel() string {
return m.label
}
func (m *SelectModel) GetValue() interface{} {
return m.chosen
}
func (m *SelectModel) SelectValidate() {
if m.validate != nil {
m.err = m.validate(m.chosen)
}
}