Skip to main content

gpui_form_component/
file_picker.rs

1//! Runtime file picker support backed by GPUI's native path prompt.
2//!
3//! This module intentionally uses `gpui_kit::App::prompt_for_paths` from the
4//! GPUI Kit facade instead of adding a second native-dialog dependency. The
5//! rendered control follows GPUI Kit styling and emits
6//! form-friendly change events.
7
8use std::path::PathBuf;
9
10use gpui_es_fluent::localize_message;
11use gpui_kit::component::{
12    ActiveTheme as _, Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _,
13    ThemeStyled as _,
14    button::{Button, ButtonVariants as _},
15    h_flex,
16};
17use gpui_kit::{
18    App, ClickEvent, Context, ElementId, Entity, EventEmitter, FocusHandle, Focusable,
19    InteractiveElement as _, IntoElement, ParentElement as _, PathPromptOptions, Render,
20    RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window,
21    div, prelude::FluentBuilder as _,
22};
23
24use crate::i18n::FilePickerText;
25#[cfg(feature = "component-shape")]
26use gpui_form_runtime::shape::ValueChange;
27
28#[cfg(feature = "component-shape")]
29fn file_picker_form_value_change(event: &FilePickerEvent) -> ValueChange<Vec<PathBuf>> {
30    match event {
31        FilePickerEvent::Change(paths) if paths.is_empty() => ValueChange::Clear,
32        FilePickerEvent::Change(paths) => ValueChange::Set(paths.clone()),
33        _ => ValueChange::Unchanged,
34    }
35}
36
37/// Which path kinds a [`FilePicker`] should ask GPUI to select.
38#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
39pub enum FilePickerMode {
40    /// Select files only.
41    #[default]
42    File,
43    /// Select directories only.
44    Directory,
45    /// Select either files or directories when the platform supports it.
46    FileOrDirectory,
47}
48
49impl FilePickerMode {
50    /// Returns whether this mode allows files.
51    pub fn allows_files(self) -> bool {
52        matches!(self, Self::File | Self::FileOrDirectory)
53    }
54
55    /// Returns whether this mode allows directories.
56    pub fn allows_directories(self) -> bool {
57        matches!(self, Self::Directory | Self::FileOrDirectory)
58    }
59
60    fn icon_name(self) -> IconName {
61        match self {
62            Self::File => IconName::File,
63            Self::Directory => IconName::Folder,
64            Self::FileOrDirectory => IconName::FolderOpen,
65        }
66    }
67
68    fn default_placeholder(self, cx: &impl std::borrow::Borrow<App>) -> SharedString {
69        let message = match self {
70            Self::File => FilePickerText::SelectAFile,
71            Self::Directory => FilePickerText::SelectADirectory,
72            Self::FileOrDirectory => FilePickerText::SelectAFileOrDirectory,
73        };
74        localize_message(cx, &message).into()
75    }
76
77    fn default_prompt(self, cx: &impl std::borrow::Borrow<App>) -> SharedString {
78        let message = match self {
79            Self::File => FilePickerText::SelectFile,
80            Self::Directory => FilePickerText::SelectDirectory,
81            Self::FileOrDirectory => FilePickerText::SelectFileOrDirectory,
82        };
83        localize_message(cx, &message).into()
84    }
85}
86
87/// Events emitted by [`FilePickerState`].
88#[derive(Clone, Debug)]
89pub enum FilePickerEvent {
90    /// The selected paths changed. An empty list means the picker was cleared.
91    Change(Vec<PathBuf>),
92    /// The platform dialog was cancelled without changing the current value.
93    Cancel,
94    /// The platform dialog failed to open or return a result.
95    Error(SharedString),
96}
97
98/// Render and native-dialog options for [`FilePicker`].
99#[derive(Clone, Debug)]
100#[cfg_attr(feature = "component-shape", derive(bon::Builder))]
101pub struct FilePickerOptions {
102    #[cfg_attr(feature = "component-shape", builder(default))]
103    mode: FilePickerMode,
104    #[cfg_attr(feature = "component-shape", builder(default))]
105    multiple: bool,
106    prompt: Option<SharedString>,
107    placeholder: Option<SharedString>,
108    browse_label: Option<SharedString>,
109    #[cfg_attr(feature = "component-shape", builder(default))]
110    cleanable: bool,
111    #[cfg_attr(feature = "component-shape", builder(default = true))]
112    appearance: bool,
113    #[cfg_attr(feature = "component-shape", builder(default))]
114    disabled: bool,
115    #[cfg_attr(feature = "component-shape", builder(default))]
116    size: Size,
117}
118
119impl Default for FilePickerOptions {
120    fn default() -> Self {
121        Self {
122            mode: FilePickerMode::default(),
123            multiple: false,
124            prompt: None,
125            placeholder: None,
126            browse_label: None,
127            cleanable: false,
128            appearance: true,
129            disabled: false,
130            size: Size::default(),
131        }
132    }
133}
134
135impl FilePickerOptions {
136    /// Create file-picker options with default file-only selection.
137    pub fn new() -> Self {
138        Self::default()
139    }
140
141    /// Returns the selected path mode.
142    pub fn mode(&self) -> FilePickerMode {
143        self.mode
144    }
145
146    /// Returns whether the native prompt allows multiple selected paths.
147    pub fn multiple(&self) -> bool {
148        self.multiple
149    }
150}
151
152/// State for a native file picker control.
153pub struct FilePickerState {
154    focus_handle: FocusHandle,
155    paths: Vec<PathBuf>,
156    last_error: Option<SharedString>,
157    options: FilePickerOptions,
158}
159
160#[cfg(feature = "component-shape")]
161impl gpui_form_runtime::shape::GpuiComponentStateValueBinding<Vec<PathBuf>> for FilePickerState {
162    type Event = FilePickerEvent;
163
164    fn seed_value_binding_state(
165        state: &mut Self,
166        value: Option<&Vec<PathBuf>>,
167        window: &mut Window,
168        cx: &mut Context<'_, Self>,
169    ) {
170        match value {
171            Some(value) => state.set_paths(value.clone(), window, cx),
172            None => state.clear_paths(window, cx),
173        }
174    }
175
176    fn value_change(_state: &Self, event: &Self::Event) -> ValueChange<Vec<PathBuf>> {
177        file_picker_form_value_change(event)
178    }
179}
180
181impl Focusable for FilePickerState {
182    fn focus_handle(&self, _: &App) -> FocusHandle {
183        self.focus_handle.clone()
184    }
185}
186
187impl EventEmitter<FilePickerEvent> for FilePickerState {}
188
189impl FilePickerState {
190    /// Create an empty file-picker state.
191    pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
192        Self::new_with_options(FilePickerOptions::default(), cx)
193    }
194
195    /// Create an empty file-picker state with configured render/dialog options.
196    pub fn new_with_options(options: FilePickerOptions, cx: &mut Context<Self>) -> Self {
197        Self {
198            focus_handle: cx.focus_handle(),
199            paths: Vec::new(),
200            last_error: None,
201            options,
202        }
203    }
204
205    /// Returns the currently selected paths.
206    pub fn paths(&self) -> &[PathBuf] {
207        &self.paths
208    }
209
210    /// Returns the first selected path, when present.
211    pub fn path(&self) -> Option<&PathBuf> {
212        self.paths.first()
213    }
214
215    /// Returns true when no path is selected.
216    pub fn is_empty(&self) -> bool {
217        self.paths.is_empty()
218    }
219
220    /// Returns the latest platform-dialog error, if one occurred.
221    pub fn last_error(&self) -> Option<&SharedString> {
222        self.last_error.as_ref()
223    }
224
225    /// Returns the configured render/dialog options for this picker.
226    pub fn options(&self) -> &FilePickerOptions {
227        &self.options
228    }
229
230    /// Programmatically replace the current selection with one path.
231    pub fn set_path(
232        &mut self,
233        path: impl Into<PathBuf>,
234        window: &mut Window,
235        cx: &mut Context<Self>,
236    ) {
237        self.replace_paths(vec![path.into()], false, window, cx);
238    }
239
240    /// Programmatically replace the current selection with zero or more paths.
241    pub fn set_paths<I, P>(&mut self, paths: I, window: &mut Window, cx: &mut Context<Self>)
242    where
243        I: IntoIterator<Item = P>,
244        P: Into<PathBuf>,
245    {
246        self.replace_paths(
247            paths.into_iter().map(Into::into).collect(),
248            false,
249            window,
250            cx,
251        );
252    }
253
254    /// Programmatically clear the current selection.
255    pub fn clear_paths(&mut self, window: &mut Window, cx: &mut Context<Self>) {
256        self.replace_paths(Vec::new(), false, window, cx);
257    }
258
259    /// Get the focus handle owned by this state.
260    pub fn focus_handle(&self) -> &FocusHandle {
261        &self.focus_handle
262    }
263
264    /// Focus the picker.
265    pub fn focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
266        self.focus_handle.focus(window, cx);
267    }
268
269    fn replace_paths(
270        &mut self,
271        paths: Vec<PathBuf>,
272        emit: bool,
273        _: &mut Window,
274        cx: &mut Context<Self>,
275    ) {
276        self.paths = paths;
277        self.last_error = None;
278        if emit {
279            cx.emit(FilePickerEvent::Change(self.paths.clone()));
280        }
281        cx.notify();
282    }
283
284    fn emit_cancel(&mut self, cx: &mut Context<Self>) {
285        self.last_error = None;
286        cx.emit(FilePickerEvent::Cancel);
287        cx.notify();
288    }
289
290    fn emit_error(&mut self, message: impl Into<SharedString>, cx: &mut Context<Self>) {
291        let message = message.into();
292        self.last_error = Some(message.clone());
293        cx.emit(FilePickerEvent::Error(message));
294        cx.notify();
295    }
296
297    fn clear_from_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
298        cx.stop_propagation();
299        self.replace_paths(Vec::new(), true, window, cx);
300    }
301}
302
303impl Render for FilePickerState {
304    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
305        gpui_kit::Empty
306    }
307}
308
309/// A native file picker element using GPUI Kit visual primitives.
310#[cfg_attr(
311    feature = "component-shape",
312    derive(component_shape_gpui::GpuiComponentShape)
313)]
314#[cfg_attr(
315    feature = "component-shape",
316    gpui_component_shape(
317        state = FilePickerState,
318        value = Vec<std::path::PathBuf>,
319        field_suffix = "file_picker",
320        value_binding
321    )
322)]
323#[derive(IntoElement)]
324pub struct FilePicker {
325    id: ElementId,
326    style: StyleRefinement,
327    state: Entity<FilePickerState>,
328    mode: Option<FilePickerMode>,
329    multiple: Option<bool>,
330    prompt: Option<SharedString>,
331    placeholder: Option<SharedString>,
332    browse_label: Option<SharedString>,
333    cleanable: Option<bool>,
334    appearance: Option<bool>,
335    disabled: Option<bool>,
336    size: Option<Size>,
337}
338
339#[cfg(feature = "component-shape")]
340impl gpui_form_runtime::shape::GpuiFormComponentShapePolicy for FilePicker {
341    type ValueStoragePolicy = gpui_form_runtime::shape::DirectValueStorage;
342}
343
344impl Sizable for FilePicker {
345    fn with_size(mut self, size: impl Into<Size>) -> Self {
346        self.size = Some(size.into());
347        self
348    }
349}
350
351impl Focusable for FilePicker {
352    fn focus_handle(&self, cx: &App) -> FocusHandle {
353        self.state.focus_handle(cx)
354    }
355}
356
357impl Styled for FilePicker {
358    fn style(&mut self) -> &mut StyleRefinement {
359        &mut self.style
360    }
361}
362
363impl Disableable for FilePicker {
364    fn disabled(mut self, disabled: bool) -> Self {
365        self.disabled = Some(disabled);
366        self
367    }
368}
369
370impl FilePicker {
371    /// Use configured file-picker options as a component-shape builder.
372    #[cfg(feature = "component-shape")]
373    pub fn from(options: FilePickerOptions) -> FilePickerOptions {
374        options
375    }
376
377    /// Create a file-only picker with the given state.
378    pub fn new(state: &Entity<FilePickerState>) -> Self {
379        Self {
380            id: ("file-picker", state.entity_id()).into(),
381            state: state.clone(),
382            mode: None,
383            multiple: None,
384            prompt: None,
385            placeholder: None,
386            browse_label: None,
387            cleanable: None,
388            appearance: None,
389            disabled: None,
390            size: None,
391            style: StyleRefinement::default(),
392        }
393    }
394
395    /// Select files only.
396    pub fn files(mut self) -> Self {
397        self.mode = Some(FilePickerMode::File);
398        self
399    }
400
401    /// Select directories only.
402    pub fn directories(mut self) -> Self {
403        self.mode = Some(FilePickerMode::Directory);
404        self
405    }
406
407    /// Select either files or directories when the platform supports it.
408    pub fn files_or_directories(mut self) -> Self {
409        self.mode = Some(FilePickerMode::FileOrDirectory);
410        self
411    }
412
413    /// Set the picker mode.
414    pub fn mode(mut self, mode: FilePickerMode) -> Self {
415        self.mode = Some(mode);
416        self
417    }
418
419    /// Allow multiple selected paths.
420    pub fn multiple(mut self, multiple: bool) -> Self {
421        self.multiple = Some(multiple);
422        self
423    }
424
425    /// Set the native dialog prompt.
426    pub fn prompt(mut self, prompt: impl Into<SharedString>) -> Self {
427        self.prompt = Some(prompt.into());
428        self
429    }
430
431    /// Set the empty display placeholder.
432    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
433        self.placeholder = Some(placeholder.into());
434        self
435    }
436
437    /// Set the browse button label.
438    pub fn browse_label(mut self, label: impl Into<SharedString>) -> Self {
439        self.browse_label = Some(label.into());
440        self
441    }
442
443    /// Show a clear button when paths are selected.
444    pub fn cleanable(mut self, cleanable: bool) -> Self {
445        self.cleanable = Some(cleanable);
446        self
447    }
448
449    /// Set whether to render the picker with the default bordered input style.
450    pub fn appearance(mut self, appearance: bool) -> Self {
451        self.appearance = Some(appearance);
452        self
453    }
454}
455
456#[cfg(feature = "component-shape")]
457impl component_shape_gpui::GpuiComponentShapeBuilder<FilePicker> for FilePickerOptions {
458    fn build(self, _window: &mut Window, cx: &mut Context<'_, FilePickerState>) -> FilePickerState {
459        FilePickerState::new_with_options(self, cx)
460    }
461}
462
463impl RenderOnce for FilePicker {
464    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
465        let is_focused = self.focus_handle(cx).contains_focused(window, cx);
466        let entity_id = self.state.entity_id();
467        let state = self.state.read(cx);
468        let paths = state.paths.clone();
469        let last_error = state.last_error.clone();
470        let options = state.options.clone();
471        let mode = self.mode.unwrap_or(options.mode);
472        let multiple = self.multiple.unwrap_or(options.multiple);
473        let prompt = self.prompt.clone().or(options.prompt.clone());
474        let placeholder = self.placeholder.clone().or(options.placeholder.clone());
475        let browse_label = self.browse_label.clone().or(options.browse_label.clone());
476        let cleanable = self.cleanable.unwrap_or(options.cleanable);
477        let appearance = self.appearance.unwrap_or(options.appearance);
478        let disabled = self.disabled.unwrap_or(options.disabled);
479        let size = self.size.unwrap_or(options.size);
480        let has_paths = !paths.is_empty();
481        let show_clean = cleanable && has_paths;
482        let placeholder = placeholder.unwrap_or_else(|| mode.default_placeholder(cx));
483        let display_title = display_paths(&paths, placeholder, |count| {
484            localize_message(cx, &FilePickerText::PathsSelected { count }).into()
485        });
486        let prompt = prompt.or_else(|| Some(mode.default_prompt(cx)));
487        let browse_label =
488            browse_label.unwrap_or_else(|| localize_message(cx, &FilePickerText::Browse).into());
489        let text_state = self.state.clone();
490        let text_prompt = prompt.clone();
491        let browse_state = self.state.clone();
492        let browse_prompt = prompt;
493
494        div()
495            .id(self.id.clone())
496            .track_focus(&self.focus_handle(cx).tab_stop(true))
497            .flex_none()
498            .w_full()
499            .input_text_size(size)
500            .refine_style(&self.style)
501            .when(disabled, |this| this.opacity(0.5))
502            .child(
503                div()
504                    .id("file-picker-input")
505                    .flex()
506                    .items_center()
507                    .justify_between()
508                    .gap_2()
509                    .when(appearance, |this| {
510                        this.bg(cx.theme().background)
511                            .text_color(cx.theme().foreground)
512                            .border_1()
513                            .border_color(cx.theme().input)
514                            .rounded(cx.theme().radius)
515                            .when(cx.theme().shadow, |this| this.shadow_xs())
516                            .when(is_focused, |this| this.border_color(cx.theme().ring))
517                    })
518                    .when(is_focused && appearance && !disabled, |this| {
519                        this.focus_ring_style(window, cx)
520                    })
521                    .input_text_size(size)
522                    .input_size(size)
523                    .overflow_hidden()
524                    .child(
525                        h_flex()
526                            .id(("file-picker-display", entity_id))
527                            .w_full()
528                            .items_center()
529                            .gap_2()
530                            .overflow_hidden()
531                            .when(!disabled, |this| this.cursor_pointer())
532                            .when(!disabled, |this| {
533                                this.on_click(move |_, window, cx| {
534                                    prompt_for_selection(
535                                        text_state.clone(),
536                                        mode,
537                                        multiple,
538                                        text_prompt.clone(),
539                                        window,
540                                        cx,
541                                    );
542                                })
543                            })
544                            .child(
545                                Icon::new(mode.icon_name())
546                                    .xsmall()
547                                    .text_color(cx.theme().muted_foreground),
548                            )
549                            .child(
550                                div()
551                                    .w_full()
552                                    .overflow_hidden()
553                                    .when(!has_paths, |this| {
554                                        this.text_color(cx.theme().muted_foreground)
555                                    })
556                                    .child(display_title),
557                            ),
558                    )
559                    .when(!disabled && show_clean, |this| {
560                        this.child(
561                            Button::new(("clear-file-picker", entity_id))
562                                .small()
563                                .ghost()
564                                .icon(IconName::Close)
565                                .on_click(
566                                    window.listener_for(
567                                        &self.state,
568                                        FilePickerState::clear_from_click,
569                                    ),
570                                ),
571                        )
572                    })
573                    .child(
574                        Button::new(("browse-file-picker", entity_id))
575                            .with_size(size)
576                            .secondary()
577                            .icon(mode.icon_name())
578                            .label(browse_label)
579                            .disabled(disabled)
580                            .on_click(move |_, window, cx| {
581                                prompt_for_selection(
582                                    browse_state.clone(),
583                                    mode,
584                                    multiple,
585                                    browse_prompt.clone(),
586                                    window,
587                                    cx,
588                                );
589                            }),
590                    ),
591            )
592            .when_some(last_error, |this, message| {
593                this.child(
594                    div()
595                        .mt_1()
596                        .text_xs()
597                        .text_color(cx.theme().danger)
598                        .child(message),
599                )
600            })
601    }
602}
603
604fn prompt_for_selection(
605    state: Entity<FilePickerState>,
606    mode: FilePickerMode,
607    multiple: bool,
608    prompt: Option<SharedString>,
609    window: &mut Window,
610    cx: &mut App,
611) {
612    let options = path_prompt_options(mode, multiple, prompt, cx.can_select_mixed_files_and_dirs());
613    let paths = cx.prompt_for_paths(options);
614
615    window
616        .spawn(cx, async move |cx| {
617            let outcome = classify_prompt_result(paths.await);
618
619            _ = state.update_in(cx, |this, window, cx| match outcome {
620                FilePickerPromptOutcome::Selected(paths) => {
621                    this.replace_paths(paths, true, window, cx);
622                },
623                FilePickerPromptOutcome::Cancelled => this.emit_cancel(cx),
624                FilePickerPromptOutcome::Failed(message) => this.emit_error(message, cx),
625                FilePickerPromptOutcome::Dropped => {
626                    this.emit_error(localize_message(cx, &FilePickerText::DialogDropped), cx);
627                },
628            });
629        })
630        .detach();
631}
632
633fn path_prompt_options(
634    mode: FilePickerMode,
635    multiple: bool,
636    prompt: Option<SharedString>,
637    mixed_selection_supported: bool,
638) -> PathPromptOptions {
639    PathPromptOptions {
640        files: mode.allows_files(),
641        directories: mode.allows_directories()
642            && (!mode.allows_files() || mixed_selection_supported),
643        multiple,
644        prompt,
645    }
646}
647
648#[derive(Debug, Eq, PartialEq)]
649enum FilePickerPromptOutcome {
650    Selected(Vec<PathBuf>),
651    Cancelled,
652    Failed(String),
653    Dropped,
654}
655
656fn classify_prompt_result<E, D>(
657    result: Result<Result<Option<Vec<PathBuf>>, E>, D>,
658) -> FilePickerPromptOutcome
659where
660    E: std::fmt::Display,
661{
662    match result {
663        Ok(Ok(Some(paths))) => FilePickerPromptOutcome::Selected(paths),
664        Ok(Ok(None)) => FilePickerPromptOutcome::Cancelled,
665        Ok(Err(error)) => FilePickerPromptOutcome::Failed(error.to_string()),
666        Err(_) => FilePickerPromptOutcome::Dropped,
667    }
668}
669
670fn display_paths(
671    paths: &[PathBuf],
672    placeholder: SharedString,
673    multiple_label: impl FnOnce(usize) -> SharedString,
674) -> SharedString {
675    match paths {
676        [] => placeholder,
677        [path] => path.display().to_string().into(),
678        _ => multiple_label(paths.len()),
679    }
680}
681
682#[cfg(test)]
683mod prompt_tests {
684    use std::{io, path::PathBuf};
685
686    use super::{
687        FilePickerMode, FilePickerPromptOutcome, classify_prompt_result, path_prompt_options,
688    };
689
690    #[test]
691    fn classifies_every_native_dialog_completion() {
692        let paths = vec![PathBuf::from("one.txt"), PathBuf::from("two.txt")];
693        assert_eq!(
694            classify_prompt_result::<io::Error, ()>(Ok(Ok(Some(paths.clone())))),
695            FilePickerPromptOutcome::Selected(paths)
696        );
697        assert_eq!(
698            classify_prompt_result::<io::Error, ()>(Ok(Ok(None))),
699            FilePickerPromptOutcome::Cancelled
700        );
701        assert_eq!(
702            classify_prompt_result::<io::Error, ()>(Ok(Err(io::Error::other("denied")))),
703            FilePickerPromptOutcome::Failed("denied".to_string())
704        );
705        assert_eq!(
706            classify_prompt_result::<io::Error, ()>(Err(())),
707            FilePickerPromptOutcome::Dropped
708        );
709    }
710
711    #[test]
712    fn prompt_options_respect_mode_and_platform_mixed_selection_support() {
713        let files = path_prompt_options(FilePickerMode::File, true, Some("Pick".into()), false);
714        assert!(files.files);
715        assert!(!files.directories);
716        assert!(files.multiple);
717        assert_eq!(files.prompt.as_deref(), Some("Pick"));
718
719        let directories = path_prompt_options(FilePickerMode::Directory, false, None, false);
720        assert!(!directories.files);
721        assert!(directories.directories);
722        assert!(!directories.multiple);
723
724        let unsupported_mixed =
725            path_prompt_options(FilePickerMode::FileOrDirectory, false, None, false);
726        assert!(unsupported_mixed.files);
727        assert!(!unsupported_mixed.directories);
728
729        let supported_mixed =
730            path_prompt_options(FilePickerMode::FileOrDirectory, false, None, true);
731        assert!(supported_mixed.files);
732        assert!(supported_mixed.directories);
733    }
734}
735
736#[cfg(all(test, feature = "component-shape"))]
737mod tests {
738    use super::{
739        FilePicker, FilePickerEvent, FilePickerMode, FilePickerOptions, display_paths,
740        file_picker_form_value_change,
741    };
742    use gpui_form_runtime::shape::ValueChange;
743
744    #[test]
745    fn empty_file_picker_change_clears_form_value() {
746        let change = file_picker_form_value_change(&FilePickerEvent::Change(Vec::new()));
747
748        assert!(matches!(change, ValueChange::Clear));
749    }
750
751    #[test]
752    fn file_picker_options_are_shape_builders() {
753        fn accepts_file_picker_builder(
754            _: impl component_shape_gpui::GpuiComponentShapeBuilder<FilePicker>,
755        ) {
756        }
757
758        let options = FilePicker::from(
759            FilePickerOptions::builder()
760                .mode(FilePickerMode::Directory)
761                .multiple(true)
762                .build(),
763        );
764
765        assert_eq!(options.mode(), FilePickerMode::Directory);
766        assert!(options.multiple());
767        accepts_file_picker_builder(options);
768    }
769
770    #[test]
771    fn file_picker_modes_and_events_preserve_selection_contracts() {
772        assert!(FilePickerMode::File.allows_files());
773        assert!(!FilePickerMode::File.allows_directories());
774        assert!(!FilePickerMode::Directory.allows_files());
775        assert!(FilePickerMode::Directory.allows_directories());
776        assert!(FilePickerMode::FileOrDirectory.allows_files());
777        assert!(FilePickerMode::FileOrDirectory.allows_directories());
778
779        let paths = vec!["one.txt".into(), "two.txt".into()];
780        assert!(matches!(
781            file_picker_form_value_change(&FilePickerEvent::Change(paths.clone())),
782            ValueChange::Set(value) if value == paths
783        ));
784        assert!(matches!(
785            file_picker_form_value_change(&FilePickerEvent::Cancel),
786            ValueChange::Unchanged
787        ));
788        assert!(matches!(
789            file_picker_form_value_change(&FilePickerEvent::Error("failed".into())),
790            ValueChange::Unchanged
791        ));
792
793        let multiple_label = |count| format!("{count} paths selected").into();
794        assert_eq!(
795            display_paths(&[], "Choose".into(), multiple_label).as_ref(),
796            "Choose"
797        );
798        assert_eq!(
799            display_paths(&["one.txt".into()], "Choose".into(), multiple_label).as_ref(),
800            "one.txt"
801        );
802        assert_eq!(
803            display_paths(&paths, "Choose".into(), multiple_label).as_ref(),
804            "2 paths selected"
805        );
806    }
807}