Работа над viewport формы, добавление описания для поля формы, комментарии к fileSelect модели

This commit is contained in:
XeRo 2026-01-19 17:44:49 +05:00
parent ecc89e34c5
commit c7ff7662ba
9 changed files with 333 additions and 207 deletions

View file

@ -13,29 +13,33 @@ import (
"time"
)
// FileSelectModel структура описывающая модель поля выбора файла
type FileSelectModel struct {
input textinput.Model
label string
focus int
open bool
file string
currentDirectory string
options []os.FileInfo
extensions []string
optionsCount int
input textinput.Model //Готовый компонент input для ввода данных
label string //Имя поля
description string //Описание поля
focus int //Фокус для управления опциями
open bool //Открыт ли список
file string //Имя выбранного файла
currentDirectory string //Директория текущего файла
options []os.FileInfo //Элементы выбора файла
extensions []string //Допустимые расширения файла
optionsCount int //Количество элементов к показу
}
func NewFileSelectModel(label, file string, extensions []string) *FileSelectModel {
inputModel := textinput.NewModel()
// NewFileSelectModel создаем новую модель поля выбора файла
func NewFileSelectModel(label, file, description string, extensions []string) *FileSelectModel {
inputModel := textinput.New()
inputModel.SetValue(file)
return &FileSelectModel{
input: inputModel,
label: label,
description: description,
extensions: extensions,
currentDirectory: filepath.Dir(file),
open: false,
file: file,
optionsCount: 3,
optionsCount: 10,
}
}
@ -43,26 +47,37 @@ func (m *FileSelectModel) Init() tea.Cmd {
return textinput.Blink
}
// Update отслеживает действия с полем
func (m *FileSelectModel) 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) {
return m, nil
}
@ -97,6 +112,8 @@ func (m *FileSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
}
} else {
//Если список не открыт и был нажат enter открываем его и рисуем опции списка.
//Иначе просто передаем сообщение нажатия клавиш в input.
switch msg.String() {
case "enter":
m.open = true
@ -113,6 +130,7 @@ func (m *FileSelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
}
default:
//Все прочие виды сообщений передаем в input если список закрыт
if !m.open {
var cmd tea.Cmd
m.input, cmd = m.input.Update(msg)
@ -124,6 +142,9 @@ 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 != "" {
res += fmt.Sprintf("\n%s", m.description)
}
if m.open && len(m.options) > 0 {
visibleCount := m.optionsCount //количество отображаемых
if visibleCount > len(m.options) { //если количество отображаемых больше, чем есть опций на самом деле
@ -174,6 +195,7 @@ func (m *FileSelectModel) Blur() {
m.input.Blur()
}
// CaptureKeys возвращает открыт ли список опций
func (m *FileSelectModel) CaptureKeys() bool {
return m.open
}
@ -186,7 +208,9 @@ func (m *FileSelectModel) GetValue() interface{} {
return m.file
}
// RenderOptions заполняем список опций на основе директорий
func (m *FileSelectModel) RenderOptions() {
//Читаем файлы в текущей директории
filesInDir, err := os.ReadDir(m.currentDirectory)
if err != nil {
logrus.Errorf("Ошибка чтения директории: %v", err)
@ -195,15 +219,16 @@ func (m *FileSelectModel) RenderOptions() {
m.options = nil
var allOptions []os.FileInfo
//Если это не корень файловой системы, добавляем переход на родительскую директорию
if m.currentDirectory != "/" && filepath.Clean(m.currentDirectory) != "/" {
allOptions = append(allOptions, virtualDirInfo{name: ".."})
//m.options = append(m.options, virtualDirInfo{name: ".."})
}
//Заполняем прочие опции
for _, entry := range filesInDir {
info, _ := entry.Info()
allOptions = append(allOptions, info)
//m.options = append(m.options, info)
}
//Заполняем фильтр для опций на основе значения поля ввода
filter := ""
if m.open {
inputValue := strings.TrimSpace(m.input.Value())
@ -214,6 +239,7 @@ func (m *FileSelectModel) RenderOptions() {
}
}
}
//Чистим опции и заполняем их правильными значениями
m.options = m.options[:0]
for _, opt := range allOptions {
name := opt.Name()