Добавление и исправление комментариев, начало добавление валидации, сообщение прокрути viewport на форме

This commit is contained in:
XeRo 2026-01-20 17:40:21 +05:00
parent c7ff7662ba
commit e37cabadcc
14 changed files with 371 additions and 297 deletions

View file

@ -2,47 +2,62 @@ package fields
import (
"fmt"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"strconv"
)
// CheckboxModel структура описывающая модель выбора из двух состояний да и нет
type CheckboxModel struct {
Label string
description string
Checked bool
label string //Имя поля
description string //Описание поля
checked bool //Выбранное состояние
validate textinput.ValidateFunc //Функция валидации
err error //Поле ошибки валидации
}
func NewCheckboxModel(label, description string, checked bool) *CheckboxModel {
return &CheckboxModel{
Label: label,
// NewCheckboxModel создаем новую модель выбора
func NewCheckboxModel(label, description string, checked bool, validator textinput.ValidateFunc) *CheckboxModel {
checkbox := &CheckboxModel{
label: label,
description: description,
Checked: checked,
validate: validator,
checked: checked,
}
checkbox.err = validator(strconv.FormatBool(checked))
return checkbox
}
func (m *CheckboxModel) Init() tea.Cmd {
return nil
}
// Update отслеживает действия с полем
func (m *CheckboxModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
//Отслеживает нажатия клавиш.
switch msg.String() {
case " ", "enter":
m.Checked = !m.Checked
//Если был нажат enter или space, то меняем текущее значение на противоположное
m.checked = !m.checked
m.err = m.validate(strconv.FormatBool(m.checked))
}
}
return m, nil
}
func (m *CheckboxModel) View() string {
res := ""
res += m.Label + ": "
if m.Checked {
res := fmt.Sprintf("%s: ", m.label)
if m.checked {
res += "[x]"
} else {
res += "[ ]"
}
if m.description != "" {
if m.err != nil {
res += fmt.Sprintf("\nОшибка валидации: %s", m.err)
} else if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
return res
@ -62,9 +77,9 @@ func (m *CheckboxModel) CaptureKeys() bool {
}
func (m *CheckboxModel) GetLabel() string {
return m.Label
return m.label
}
func (m *CheckboxModel) GetValue() interface{} {
return m.Checked
return m.checked
}

View file

@ -5,15 +5,17 @@ import (
tea "github.com/charmbracelet/bubbletea"
)
// ComputeModel структура описывающая модель вывода вычисляемых значений
type ComputeModel struct {
Label string
description string
value string
label string //Имя поля
description string //Описание поля
value string //Значение поля
}
// NewComputeModel создаем новую модель вывода вычисляемых значений
func NewComputeModel(label, value, description string) *ComputeModel {
return &ComputeModel{
Label: label,
label: label,
description: description,
value: value,
}
@ -23,12 +25,13 @@ func (m *ComputeModel) Init() tea.Cmd {
return nil
}
// Update отслеживает действия с полем. Так как поле нужно только для вывода, никаких действий не выполняем.
func (m *ComputeModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
return m, nil
}
func (m *ComputeModel) View() string {
res := fmt.Sprintf("%s: %s", m.Label, m.value)
res := fmt.Sprintf("%s: %s", m.label, m.value)
if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
@ -46,7 +49,7 @@ func (m *ComputeModel) CaptureKeys() bool {
}
func (m *ComputeModel) GetLabel() string {
return m.Label
return m.label
}
func (m *ComputeModel) GetValue() interface{} {

View file

@ -2,6 +2,7 @@ package fields
import (
"bubble/setup/ui"
"bubble/setup/utils"
"fmt"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
@ -11,20 +12,23 @@ import (
"strings"
)
// DirSelectModel структура описывающая модель поля выбора директории
type DirSelectModel struct {
input textinput.Model
label string
description string
focus int
open bool
dir string
currentDirectory string
options []os.FileInfo
optionsCount int
input textinput.Model //Готовый компонент input для ввода данных
label string //Имя поля
description string //Описание поля
focus int //Фокус для управления опциями
open bool //Открыт ли список
dir string //Имя выбранной директории
currentDirectory string //Директория текущего файла
options []os.FileInfo //Элементы выбора файлов
optionsCount int //Количество элементов к показу
}
func NewDirSelectModel(label, dir, description string) *DirSelectModel {
// NewDirSelectModel создает новую модель поля выбора директории
func NewDirSelectModel(label, dir, description string, validator textinput.ValidateFunc) *DirSelectModel {
inputModel := textinput.New()
inputModel.Validate = validator
inputModel.SetValue(dir)
return &DirSelectModel{
input: inputModel,
@ -41,27 +45,37 @@ func (m *DirSelectModel) Init() tea.Cmd {
return textinput.Blink
}
// Update отслеживает действия с полями
func (m *DirSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
//Отслеживает нажатия клавиш.
//Если список открыт, то отслеживаем клавиши отдельно
if m.open {
switch msg.String() {
case "esc":
//Закрываем список
m.open = false
case "up":
//Уменьшаем фокус, поднимаем его
m.focus--
if m.focus < 0 {
m.focus = len(m.options) - 1
}
case "down":
//Увеличиваем фокус, опуская его
m.focus++
if m.focus == len(m.options) {
m.focus = 0
}
case "enter":
if len(m.options) == 0 || m.focus == len(m.options) {
//Выбираем директорию из списка. Если список пуст ничего не делаем.
//Получаем имя файла.
//Если имя файла ".." возвращаемся в родительскую папку.
//Если файл является директорией, то записываем его и закрываем список.
if len(m.options) == 0 || m.focus >= len(m.options) {
return m, nil
}
file := m.options[m.focus]
@ -88,6 +102,8 @@ func (m *DirSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
}
} else {
//Если список не открыт и был нажат enter, открываем его и рисуем опции списка.
//Иначе просто передаем сообщения нажатия клавиш в input.
switch msg.String() {
case "enter":
m.open = true
@ -115,6 +131,7 @@ func (m *DirSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
}
default:
//Все прочие виды сообщений передаем в input если список закрыт
if !m.open {
var cmd tea.Cmd
m.input, cmd = m.input.Update(msg)
@ -126,27 +143,13 @@ func (m *DirSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
func (m *DirSelectModel) View() string {
res := fmt.Sprintf("%s: %s", m.label, m.input.View())
if m.description != "" {
if m.input.Err != nil && !m.open {
res += fmt.Sprintf("\nОшибка валидации: %s", m.input.Err)
} else if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
if m.open && len(m.options) > 0 {
visibleCount := m.optionsCount
if visibleCount > len(m.options) {
visibleCount = len(m.options)
}
half := visibleCount / 2
start := m.focus - half
if start < 0 {
start = 0
}
end := start + visibleCount
if end > len(m.options) {
end = len(m.options)
start = end - visibleCount
if start < 0 {
start = 0
}
}
start, end := utils.CalculateSelectOptionsIndex(m.focus, m.optionsCount, len(m.options))
for i := start; i < end; i++ {
file := m.options[i]
name := file.Name()
@ -188,21 +191,26 @@ func (m *DirSelectModel) GetValue() interface{} {
return m.dir
}
// RenderOptions заполняем список опций на основе директорий
func (m *DirSelectModel) RenderOptions() {
//Читаем файлы к текущей директории
filesInDir, err := os.ReadDir(m.currentDirectory)
if err != nil {
logrus.Errorf("Ошибка чтения директории: %v", err)
return
}
m.options = nil
//Если это не корень файловой системы, добавляем переход на родительскую директорию
var allOptions []os.FileInfo
if m.currentDirectory != "/" && filepath.Clean(m.currentDirectory) != "/" {
allOptions = append(allOptions, virtualDirInfo{name: ".."})
}
//Заполняем прочие опции
for _, entry := range filesInDir {
info, _ := entry.Info()
allOptions = append(allOptions, info)
}
//Заполняем фильтр для опций на основе значения поля ввода
filter := ""
if m.open {
inputValue := strings.TrimSpace(m.input.Value())
@ -213,6 +221,7 @@ func (m *DirSelectModel) RenderOptions() {
}
}
}
//Чистим опции и заполняем их правильными значениями
m.options = m.options[:0]
for _, opt := range allOptions {
name := opt.Name()

View file

@ -2,6 +2,7 @@ package fields
import tea "github.com/charmbracelet/bubbletea"
// FieldModel интерфейс работы с полями формы
type FieldModel interface {
Init() tea.Cmd //Метод инициализации поля
Update(msg tea.Msg) (FieldModel, tea.Cmd) //Метод отслеживания событий связанных с моделью

View file

@ -2,6 +2,7 @@ package fields
import (
"bubble/setup/ui"
"bubble/setup/utils"
"fmt"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
@ -28,8 +29,9 @@ type FileSelectModel struct {
}
// NewFileSelectModel создаем новую модель поля выбора файла
func NewFileSelectModel(label, file, description string, extensions []string) *FileSelectModel {
func NewFileSelectModel(label, file, description string, extensions []string, validator textinput.ValidateFunc) *FileSelectModel {
inputModel := textinput.New()
inputModel.Validate = validator
inputModel.SetValue(file)
return &FileSelectModel{
input: inputModel,
@ -78,7 +80,7 @@ func (m *FileSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
//Если имя файла ".." возвращаемся в родительскую папку.
//Если файл является директорией, то переходим в эту директорию.
//Если у файла совпадают расширения, то записываем его и закрываем список.
if len(m.options) == 0 || m.focus == len(m.options) {
if len(m.options) == 0 || m.focus >= len(m.options) {
return m, nil
}
file := m.options[m.focus]
@ -112,7 +114,7 @@ func (m *FileSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
}
} else {
//Если список не открыт и был нажат enter открываем его и рисуем опции списка.
//Если список не открыт и был нажат enter, открываем его и рисуем опции списка.
//Иначе просто передаем сообщение нажатия клавиш в input.
switch msg.String() {
case "enter":
@ -142,27 +144,13 @@ func (m *FileSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
func (m *FileSelectModel) View() string {
res := fmt.Sprintf("%s: %s", m.label, m.input.View())
if m.description != "" {
if m.input.Err != nil && !m.open {
res += fmt.Sprintf("\nОшибка валидации: %s", m.input.Err)
} else if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
if m.open && len(m.options) > 0 {
visibleCount := m.optionsCount //количество отображаемых
if visibleCount > len(m.options) { //если количество отображаемых больше, чем есть опций на самом деле
visibleCount = len(m.options) //то меняем количество видимых на количество опций
}
half := visibleCount / 2 //количество объектов сверху и снизу
start := m.focus - half //стартовая позиция
if start < 0 { //если стартовая позиция меньше 0, то меняем на 0
start = 0
}
end := start + visibleCount //последний элемент
if end > len(m.options) { //если последний элемент вне опций
end = len(m.options) //меняем на количество опций
start = end - visibleCount //перерасчет стартовой позиции
if start < 0 {
start = 0
}
}
start, end := utils.CalculateSelectOptionsIndex(m.focus, m.optionsCount, len(m.options))
for i := start; i < end; i++ {
file := m.options[i]
name := file.Name()

View file

@ -14,9 +14,13 @@ type InputModel struct {
input textinput.Model
}
type FieldValidator func(value any) error
// NewInputModel создает новую модель поля ввода данных
func NewInputModel(label, value, description string) *InputModel {
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{
@ -39,7 +43,9 @@ func (m *InputModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
func (m *InputModel) View() string {
res := fmt.Sprintf("%s: %v", m.label, m.input.View())
if m.description != "" {
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

View file

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