Debian Codegraph @

field_filepicker.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "errors"
6 "io"
7 "os"
8 "strings"
9
10 "github.com/charmbracelet/bubbles/filepicker"
11 "github.com/charmbracelet/bubbles/key"
12 tea "github.com/charmbracelet/bubbletea"
13 "github.com/charmbracelet/huh/internal/accessibility"
14 "github.com/charmbracelet/lipgloss"
15 xstrings "github.com/charmbracelet/x/exp/strings"
16 )
17
18 // FilePicker is a form file file field.
19 type FilePicker struct {
20 accessor Accessor[string]
21 key string
22 picker filepicker.Model
23
24 // state
25 focused bool
26 picking bool
27
28 // customization
29 title string
30 description string
31
32 // error handling
33 validate func(string) error
34 err error
35
36 // options
37 width int
38 height int
39 accessible bool // Deprecated: use RunAccessible instead.
40 theme *Theme
41 keymap FilePickerKeyMap
42 }
43
44 // NewFilePicker returns a new file field.
45 func NewFilePicker() *FilePicker {
46 fp := filepicker.New()
47 fp.ShowSize = false
48
49 if cmd := fp.Init(); cmd != nil {
50 fp, _ = fp.Update(cmd())
51 }
52
53 return &FilePicker{
54 accessor: &EmbeddedAccessor[string]{},
55 validate: func(string) error { return nil },
56 picker: fp,
57 }
58 }
59
60 // CurrentDirectory sets the directory of the file field.
61 func (f *FilePicker) CurrentDirectory(directory string) *FilePicker {
62 f.picker.CurrentDirectory = directory
63 if cmd := f.picker.Init(); cmd != nil {
64 f.picker, _ = f.picker.Update(cmd())
65 }
66 return f
67 }
68
69 // Cursor sets the cursor of the file field.
70 func (f *FilePicker) Cursor(cursor string) *FilePicker {
71 f.picker.Cursor = cursor
72 return f
73 }
74
75 // Picking sets whether the file picker should be in the picking files state.
76 func (f *FilePicker) Picking(v bool) *FilePicker {
77 f.setPicking(v)
78 return f
79 }
80
81 // ShowHidden sets whether to show hidden files.
82 func (f *FilePicker) ShowHidden(v bool) *FilePicker {
83 f.picker.ShowHidden = v
84 return f
85 }
86
87 // ShowSize sets whether to show file sizes.
88 func (f *FilePicker) ShowSize(v bool) *FilePicker {
89 f.picker.ShowSize = v
90 return f
91 }
92
93 // ShowPermissions sets whether to show file permissions.
94 func (f *FilePicker) ShowPermissions(v bool) *FilePicker {
95 f.picker.ShowPermissions = v
96 return f
97 }
98
99 // FileAllowed sets whether to allow files to be selected.
100 func (f *FilePicker) FileAllowed(v bool) *FilePicker {
101 f.picker.FileAllowed = v
102 return f
103 }
104
105 // DirAllowed sets whether to allow directories to be selected.
106 func (f *FilePicker) DirAllowed(v bool) *FilePicker {
107 f.picker.DirAllowed = v
108 return f
109 }
110
111 // Value sets the value of the file field.
112 func (f *FilePicker) Value(value *string) *FilePicker {
113 return f.Accessor(NewPointerAccessor(value))
114 }
115
116 // Accessor sets the accessor of the file field.
117 func (f *FilePicker) Accessor(accessor Accessor[string]) *FilePicker {
118 f.accessor = accessor
119 return f
120 }
121
122 // Key sets the key of the file field which can be used to retrieve the value
123 // after submission.
124 func (f *FilePicker) Key(key string) *FilePicker {
125 f.key = key
126 return f
127 }
128
129 // Title sets the title of the file field.
130 func (f *FilePicker) Title(title string) *FilePicker {
131 f.title = title
132 return f
133 }
134
135 // Description sets the description of the file field.
136 func (f *FilePicker) Description(description string) *FilePicker {
137 f.description = description
138 return f
139 }
140
141 // AllowedTypes sets the allowed types of the file field. These will be the only
142 // valid file types accepted, other files will show as disabled.
143 func (f *FilePicker) AllowedTypes(types []string) *FilePicker {
144 f.picker.AllowedTypes = types
145 return f
146 }
147
148 // Height sets the height of the file field. If the number of options
149 // exceeds the height, the file field will become scrollable.
150 func (f *FilePicker) Height(height int) *FilePicker {
151 f.WithHeight(height)
152 return f
153 }
154
155 // Validate sets the validation function of the file field.
156 func (f *FilePicker) Validate(validate func(string) error) *FilePicker {
157 f.validate = validate
158 return f
159 }
160
161 // Error returns the error of the file field.
162 func (f *FilePicker) Error() error {
163 return f.err
164 }
165
166 // Skip returns whether the file should be skipped or should be blocking.
167 func (*FilePicker) Skip() bool {
168 return false
169 }
170
171 // Zoom returns whether the input should be zoomed.
172 func (f *FilePicker) Zoom() bool {
173 return f.picking
174 }
175
176 // Focus focuses the file field.
177 func (f *FilePicker) Focus() tea.Cmd {
178 f.focused = true
179 return f.picker.Init()
180 }
181
182 // Blur blurs the file field.
183 func (f *FilePicker) Blur() tea.Cmd {
184 f.focused = false
185 f.setPicking(false)
186 f.err = f.validate(f.accessor.Get())
187 return nil
188 }
189
190 // KeyBinds returns the help keybindings for the file field.
191 func (f *FilePicker) KeyBinds() []key.Binding {
192 return []key.Binding{f.keymap.Up, f.keymap.Down, f.keymap.Close, f.keymap.Open, f.keymap.Prev, f.keymap.Next, f.keymap.Submit}
193 }
194
195 // Init initializes the file field.
196 func (f *FilePicker) Init() tea.Cmd {
197 return f.picker.Init()
198 }
199
200 // Update updates the file field.
201 func (f *FilePicker) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
202 f.err = nil
203
204 switch msg := msg.(type) {
205 case tea.KeyMsg:
206 switch {
207 case key.Matches(msg, f.keymap.Open):
208 if f.picking {
209 break
210 }
211 f.setPicking(true)
212 return f, f.picker.Init()
213 case key.Matches(msg, f.keymap.Close):
214 f.setPicking(false)
215 return f, NextField
216 case key.Matches(msg, f.keymap.Next):
217 f.setPicking(false)
218 return f, NextField
219 case key.Matches(msg, f.keymap.Prev):
220 f.setPicking(false)
221 return f, PrevField
222 }
223 }
224
225 var cmd tea.Cmd
226 f.picker, cmd = f.picker.Update(msg)
227 didSelect, file := f.picker.DidSelectFile(msg)
228 if didSelect {
229 f.accessor.Set(file)
230 f.setPicking(false)
231 return f, NextField
232 }
233 didSelect, _ = f.picker.DidSelectDisabledFile(msg)
234 if didSelect {
235 f.err = errors.New(xstrings.EnglishJoin(f.picker.AllowedTypes, true) + " files only")
236 return f, nil
237 }
238
239 return f, cmd
240 }
241
242 func (f *FilePicker) activeStyles() *FieldStyles {
243 theme := f.theme
244 if theme == nil {
245 theme = ThemeCharm()
246 }
247 if f.focused {
248 return &theme.Focused
249 }
250 return &theme.Blurred
251 }
252
253 func (f *FilePicker) renderTitle() string {
254 styles := f.activeStyles()
255 maxWidth := f.width - styles.Base.GetHorizontalFrameSize()
256 return styles.Title.Render(wrap(f.title, maxWidth))
257 }
258
259 func (f FilePicker) renderDescription() string {
260 styles := f.activeStyles()
261 maxWidth := f.width - styles.Base.GetHorizontalFrameSize()
262 return styles.Description.Render(wrap(f.description, maxWidth))
263 }
264
265 // View renders the file field.
266 func (f *FilePicker) View() string {
267 styles := f.activeStyles()
268 var parts []string
269 if f.title != "" {
270 parts = append(parts, f.renderTitle())
271 }
272 if f.description != "" {
273 parts = append(parts, f.renderDescription())
274 }
275 parts = append(parts, f.pickerView())
276 return styles.Base.Width(f.width).Height(f.height).
277 Render(strings.Join(parts, "\n"))
278 }
279
280 func (f *FilePicker) pickerView() string {
281 if f.picking {
282 return f.picker.View()
283 }
284 styles := f.activeStyles()
285 if f.accessor.Get() != "" {
286 return styles.SelectedOption.Render(f.accessor.Get())
287 }
288 return styles.TextInput.Placeholder.Render("No file selected.")
289 }
290
291 func (f *FilePicker) setPicking(v bool) {
292 f.picking = v
293
294 f.keymap.Close.SetEnabled(v)
295 f.keymap.Up.SetEnabled(v)
296 f.keymap.Down.SetEnabled(v)
297 f.keymap.Select.SetEnabled(v)
298 f.keymap.Back.SetEnabled(v)
299
300 f.picker.KeyMap.Up.SetEnabled(v)
301 f.picker.KeyMap.Down.SetEnabled(v)
302 f.picker.KeyMap.GoToTop.SetEnabled(v)
303 f.picker.KeyMap.GoToLast.SetEnabled(v)
304 f.picker.KeyMap.Select.SetEnabled(v)
305 f.picker.KeyMap.Open.SetEnabled(v)
306 f.picker.KeyMap.Back.SetEnabled(v)
307 }
308
309 // Run runs the file field.
310 func (f *FilePicker) Run() error {
311 if f.accessible { // TODO: remove in a future release.
312 return f.RunAccessible(os.Stdout, os.Stdin)
313 }
314 return Run(f)
315 }
316
317 // RunAccessible runs an accessible file field.
318 func (f *FilePicker) RunAccessible(w io.Writer, r io.Reader) error {
319 styles := f.activeStyles()
320 prompt := styles.Title.
321 PaddingRight(1).
322 Render(cmp.Or(f.title, "Choose a file:"))
323
324 validateFile := func(s string) error {
325 // is the string a file?
326 if _, err := os.Open(s); err != nil {
327 return errors.New("not a file")
328 }
329
330 // is it one of the allowed types?
331 valid := len(f.picker.AllowedTypes) == 0
332 for _, ext := range f.picker.AllowedTypes {
333 if strings.HasSuffix(s, ext) {
334 valid = true
335 break
336 }
337 }
338 if !valid {
339 return errors.New("cannot select: " + s)
340 }
341
342 // does it pass user validation?
343 return f.validate(s)
344 }
345
346 f.accessor.Set(accessibility.PromptString(
347 w,
348 r,
349 prompt,
350 f.GetValue().(string),
351 validateFile,
352 ))
353 return nil
354 }
355
356 // copied from bubbles' filepicker.
357 const (
358 fileSizeWidth = 7
359 paddingLeft = 2
360 )
361
362 // WithTheme sets the theme of the file field.
363 func (f *FilePicker) WithTheme(theme *Theme) Field {
364 if f.theme != nil || theme == nil {
365 return f
366 }
367 f.theme = theme
368
369 // XXX: add specific themes
370 f.picker.Styles = filepicker.Styles{
371 DisabledCursor: lipgloss.Style{},
372 Cursor: theme.Focused.TextInput.Prompt,
373 Symlink: lipgloss.NewStyle(),
374 Directory: theme.Focused.Directory,
375 File: theme.Focused.File,
376 DisabledFile: theme.Focused.TextInput.Placeholder,
377 Permission: theme.Focused.TextInput.Placeholder,
378 Selected: theme.Focused.SelectedOption,
379 DisabledSelected: theme.Focused.TextInput.Placeholder,
380 FileSize: theme.Focused.TextInput.Placeholder.Width(fileSizeWidth).Align(lipgloss.Right),
381 EmptyDirectory: theme.Focused.TextInput.Placeholder.PaddingLeft(paddingLeft).SetString("No files found."),
382 }
383
384 return f
385 }
386
387 // WithKeyMap sets the keymap on a file field.
388 func (f *FilePicker) WithKeyMap(k *KeyMap) Field {
389 f.keymap = k.FilePicker
390 f.picker.KeyMap = filepicker.KeyMap{
391 GoToTop: k.FilePicker.GotoTop,
392 GoToLast: k.FilePicker.GotoBottom,
393 Down: k.FilePicker.Down,
394 Up: k.FilePicker.Up,
395 PageUp: k.FilePicker.PageUp,
396 PageDown: k.FilePicker.PageDown,
397 Back: k.FilePicker.Back,
398 Open: k.FilePicker.Open,
399 Select: k.FilePicker.Select,
400 }
401 f.setPicking(f.picking)
402 return f
403 }
404
405 // WithAccessible sets the accessible mode of the file field.
406 //
407 // Deprecated: you may now call [FilePicker.RunAccessible] directly to run the
408 // field in accessible mode.
409 func (f *FilePicker) WithAccessible(accessible bool) Field {
410 f.accessible = accessible
411 return f
412 }
413
414 // WithWidth sets the width of the file field.
415 func (f *FilePicker) WithWidth(width int) Field {
416 f.width = width
417 return f
418 }
419
420 // WithHeight sets the height of the file field.
421 func (f *FilePicker) WithHeight(height int) Field {
422 if height == 0 {
423 return f
424 }
425 adjust := 0
426 if f.title != "" {
427 adjust += lipgloss.Height(f.renderTitle())
428 }
429 if f.description != "" {
430 adjust += lipgloss.Height(f.renderDescription())
431 }
432 adjust++ // picker's own help height
433 f.picker.SetHeight(height - adjust)
434 return f
435 }
436
437 // WithPosition sets the position of the file field.
438 func (f *FilePicker) WithPosition(p FieldPosition) Field {
439 f.keymap.Prev.SetEnabled(!p.IsFirst())
440 f.keymap.Next.SetEnabled(!p.IsLast())
441 f.keymap.Submit.SetEnabled(p.IsLast())
442 return f
443 }
444
445 // GetKey returns the key of the field.
446 func (f *FilePicker) GetKey() string {
447 return f.key
448 }
449
450 // GetValue returns the value of the field.
451 func (f *FilePicker) GetValue() any {
452 return f.accessor.Get()
453 }