Работа над 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

@ -1,18 +1,21 @@
package fields
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
)
type CheckboxModel struct {
Label string
Checked bool
Label string
description string
Checked bool
}
func NewCheckboxModel(label string, checked bool) *CheckboxModel {
func NewCheckboxModel(label, description string, checked bool) *CheckboxModel {
return &CheckboxModel{
Label: label,
Checked: checked,
Label: label,
description: description,
Checked: checked,
}
}
@ -39,6 +42,9 @@ func (m *CheckboxModel) View() string {
} else {
res += "[ ]"
}
if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
return res
}

View file

@ -6,14 +6,16 @@ import (
)
type ComputeModel struct {
Label string
value string
Label string
description string
value string
}
func NewComputeModel(label, value string) *ComputeModel {
func NewComputeModel(label, value, description string) *ComputeModel {
return &ComputeModel{
Label: label,
value: value,
Label: label,
description: description,
value: value,
}
}
@ -26,7 +28,11 @@ func (m *ComputeModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
}
func (m *ComputeModel) View() string {
return 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)
}
return res
}
func (m *ComputeModel) Focus() {}

View file

@ -14,6 +14,7 @@ import (
type DirSelectModel struct {
input textinput.Model
label string
description string
focus int
open bool
dir string
@ -22,16 +23,17 @@ type DirSelectModel struct {
optionsCount int
}
func NewDirSelectModel(label, dir string) *DirSelectModel {
func NewDirSelectModel(label, dir, description string) *DirSelectModel {
inputModel := textinput.New()
inputModel.SetValue(dir)
return &DirSelectModel{
input: inputModel,
label: label,
description: description,
currentDirectory: filepath.Dir(dir),
open: false,
dir: dir,
optionsCount: 3,
optionsCount: 10,
}
}
@ -124,6 +126,9 @@ 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 != "" {
res += fmt.Sprintf("\n%s", m.description)
}
if m.open && len(m.options) > 0 {
visibleCount := m.optionsCount
if visibleCount > len(m.options) {

View file

@ -2,15 +2,13 @@ package fields
import tea "github.com/charmbracelet/bubbletea"
// todo комментарии к полям
// todo описание поля выводить
type FieldModel interface {
Init() tea.Cmd
Update(msg tea.Msg) (FieldModel, tea.Cmd)
View() string
Focus()
Blur()
CaptureKeys() bool
GetLabel() string
GetValue() interface{}
Init() tea.Cmd //Метод инициализации поля
Update(msg tea.Msg) (FieldModel, tea.Cmd) //Метод отслеживания событий связанных с моделью
View() string //Метод отрисовки модели
Focus() //Метод установки фокуса
Blur() //Метод удаления фокуса
CaptureKeys() bool //Метод проверяющий захват событий
GetLabel() string //Получить имя поля
GetValue() interface{} //Получить значение поля
}

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()

View file

@ -7,18 +7,22 @@ import (
tea "github.com/charmbracelet/bubbletea"
)
// InputModel структура описывающая модель поля ввода данных
type InputModel struct {
label string
input textinput.Model
label string
description string
input textinput.Model
}
func NewInputModel(label, value string) *InputModel {
// NewInputModel создает новую модель поля ввода данных
func NewInputModel(label, value, description string) *InputModel {
t := textinput.New()
t.SetValue(value)
t.Cursor.SetMode(cursor.CursorBlink)
return &InputModel{
label: label,
input: t,
label: label,
description: description,
input: t,
}
}
@ -26,6 +30,7 @@ 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)
@ -34,6 +39,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 != "" {
res += fmt.Sprintf("\n%s", m.description)
}
return res
}

View file

@ -7,14 +7,15 @@ import (
)
type SelectModel struct {
label string
options []string
focus int
open bool
chosen string
label string
description string
options []string
focus int
open bool
chosen string
}
func NewSelectModel(label, value string, options []string) *SelectModel {
func NewSelectModel(label, value, description string, options []string) *SelectModel {
found := false
for i := range options {
if options[i] == value {
@ -25,10 +26,11 @@ func NewSelectModel(label, value string, options []string) *SelectModel {
value = ""
}
return &SelectModel{
options: options,
label: label,
focus: len(options),
chosen: value,
options: options,
label: label,
description: description,
focus: len(options),
chosen: value,
}
}
@ -85,6 +87,9 @@ func (m *SelectModel) Update(msg tea.Msg) (FieldModel, tea.Cmd) {
func (m *SelectModel) View() string {
res := fmt.Sprintf("%s: %s", m.label, m.chosen)
if m.description != "" {
res += fmt.Sprintf("\n%s", m.description)
}
if m.open && len(m.options) > 0 {
for i := range m.options {
if m.focus == i {