diff --git a/examples/file-picker/main.go b/examples/file-picker/main.go index 727b880..f0470cd 100644 --- a/examples/file-picker/main.go +++ b/examples/file-picker/main.go @@ -1,9 +1,11 @@ package main import ( + "errors" "fmt" "os" "strings" + "time" "github.com/charmbracelet/bubbles/filepicker" tea "github.com/charmbracelet/bubbletea" @@ -13,6 +15,15 @@ type model struct { filepicker filepicker.Model selectedFile string quitting bool + err error +} + +type clearErrorMsg struct{} + +func clearErrorAfter(t time.Duration) tea.Cmd { + return tea.Tick(t, func(_ time.Time) tea.Msg { + return clearErrorMsg{} + }) } func (m model) Init() tea.Cmd { @@ -27,6 +38,8 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.quitting = true return m, tea.Quit } + case clearErrorMsg: + m.err = nil } var cmd tea.Cmd @@ -38,6 +51,15 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.selectedFile = path } + // Did the user select a disabled file? + // This is only necessary to display an error to the user. + if didSelect, path := m.filepicker.DidSelectDisabledFile(msg); didSelect { + // Let's clear the selectedFile and display an error. + m.err = errors.New(path + " is not valid.") + m.selectedFile = "" + return m, tea.Batch(cmd, clearErrorAfter(2*time.Second)) + } + return m, cmd } @@ -47,7 +69,9 @@ func (m model) View() string { } var s strings.Builder s.WriteString("\n ") - if m.selectedFile == "" { + if m.err != nil { + s.WriteString(m.filepicker.Styles.DisabledFile.Render(m.err.Error())) + } else if m.selectedFile == "" { s.WriteString("Pick a file:") } else { s.WriteString("Selected file: " + m.filepicker.Styles.Selected.Render(m.selectedFile)) @@ -58,6 +82,7 @@ func (m model) View() string { func main() { fp := filepicker.New() + fp.AllowedTypes = []string{".mod", ".sum", ".go", ".txt", ".md"} fp.CurrentDirectory, _ = os.UserHomeDir() m := model{