gum/file/file.go

73 lines
1.5 KiB
Go
Raw Normal View History

2022-10-01 00:40:10 +02:00
// Package file provides an interface to pick a file from a folder (tree).
// The user is provided a file manager-like interface to navigate, to
// select a file.
//
// Let's pick a file from the current directory:
//
// $ gum file
// $ gum file .
//
// Let's pick a file from the home directory:
//
// $ gum file $HOME
package file
import (
2023-06-30 15:22:45 +02:00
"time"
"github.com/charmbracelet/bubbles/filepicker"
2022-10-01 00:40:10 +02:00
tea "github.com/charmbracelet/bubbletea"
2023-06-30 15:22:45 +02:00
"github.com/charmbracelet/gum/timeout"
2022-10-01 00:40:10 +02:00
)
type model struct {
filepicker filepicker.Model
selectedPath string
aborted bool
quitting bool
2023-06-30 15:22:45 +02:00
timeout time.Duration
hasTimeout bool
2022-10-01 00:40:10 +02:00
}
func (m model) Init() tea.Cmd {
2023-06-30 15:22:45 +02:00
return tea.Batch(
timeout.Init(m.timeout, nil),
m.filepicker.Init(),
)
2022-10-01 00:40:10 +02:00
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q", "esc":
m.aborted = true
m.quitting = true
2022-10-01 00:40:10 +02:00
return m, tea.Quit
}
2023-06-30 15:22:45 +02:00
case timeout.TickTimeoutMsg:
if msg.TimeoutValue <= 0 {
m.quitting = true
m.aborted = true
return m, tea.Quit
}
m.timeout = msg.TimeoutValue
return m, timeout.Tick(msg.TimeoutValue, msg.Data)
2022-10-01 00:40:10 +02:00
}
var cmd tea.Cmd
m.filepicker, cmd = m.filepicker.Update(msg)
if didSelect, path := m.filepicker.DidSelectFile(msg); didSelect {
m.selectedPath = path
m.quitting = true
return m, tea.Quit
}
return m, cmd
2022-10-01 00:40:10 +02:00
}
func (m model) View() string {
if m.quitting {
return ""
}
return m.filepicker.View()
2022-10-01 00:40:10 +02:00
}