Skip to content

Commit

Permalink
docs(examples): filepicker AllowedTypes example (#713)
Browse files Browse the repository at this point in the history
  • Loading branch information
maaslalani committed May 31, 2023
1 parent 8254e0e commit 444e04b
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion 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"
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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
}

Expand All @@ -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))
Expand All @@ -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{
Expand Down

0 comments on commit 444e04b

Please sign in to comment.