Добавление и исправление комментариев, начало добавление валидации, сообщение прокрути 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,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()