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