Skip to main content

fc_ui/capabilities/media/
file_upload.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::icon::Icon;
3use crate::capabilities::primitives::spinner::{Spinner, SpinnerSize, SpinnerVariant};
4use gpui::{prelude::FluentBuilder as _, *};
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8#[derive(Clone, Debug)]
9pub struct SelectedFile {
10    pub name: String,
11    pub path: PathBuf,
12    pub size: u64,
13    pub mime_type: Option<String>,
14    pub is_image: bool,
15}
16
17impl SelectedFile {
18    pub fn new(path: PathBuf) -> Self {
19        let name = path
20            .file_name()
21            .map(|n| n.to_string_lossy().to_string())
22            .unwrap_or_else(|| "unknown".to_string());
23
24        let extension = path
25            .extension()
26            .map(|e| e.to_string_lossy().to_lowercase())
27            .unwrap_or_default();
28
29        let is_image = matches!(
30            extension.as_str(),
31            "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "svg" | "ico"
32        );
33
34        let mime_type = match extension.as_str() {
35            "png" => Some("image/png".to_string()),
36            "jpg" | "jpeg" => Some("image/jpeg".to_string()),
37            "gif" => Some("image/gif".to_string()),
38            "bmp" => Some("image/bmp".to_string()),
39            "webp" => Some("image/webp".to_string()),
40            "svg" => Some("image/svg+xml".to_string()),
41            "pdf" => Some("application/pdf".to_string()),
42            "txt" => Some("text/plain".to_string()),
43            "json" => Some("application/json".to_string()),
44            "zip" => Some("application/zip".to_string()),
45            _ => None,
46        };
47
48        let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
49
50        Self {
51            name,
52            path,
53            size,
54            mime_type,
55            is_image,
56        }
57    }
58
59    pub fn formatted_size(&self) -> String {
60        const KB: u64 = 1024;
61        const MB: u64 = KB * 1024;
62        const GB: u64 = MB * 1024;
63
64        if self.size >= GB {
65            format!("{:.1} GB", self.size as f64 / GB as f64)
66        } else if self.size >= MB {
67            format!("{:.1} MB", self.size as f64 / MB as f64)
68        } else if self.size >= KB {
69            format!("{:.1} KB", self.size as f64 / KB as f64)
70        } else {
71            format!("{} B", self.size)
72        }
73    }
74}
75
76#[derive(Clone, Debug)]
77pub struct FileUploadError {
78    pub file_name: String,
79    pub message: String,
80}
81
82pub struct FileUploadState {
83    pub files: Vec<SelectedFile>,
84    pub errors: Vec<FileUploadError>,
85    pub is_dragging: bool,
86    pub is_uploading: bool,
87}
88
89impl FileUploadState {
90    pub fn new() -> Self {
91        Self {
92            files: Vec::new(),
93            errors: Vec::new(),
94            is_dragging: false,
95            is_uploading: false,
96        }
97    }
98
99    pub fn add_file(&mut self, file: SelectedFile) {
100        self.files.push(file);
101    }
102
103    pub fn remove_file(&mut self, index: usize) {
104        if index < self.files.len() {
105            self.files.remove(index);
106        }
107    }
108
109    pub fn clear_files(&mut self) {
110        self.files.clear();
111    }
112
113    pub fn add_error(&mut self, error: FileUploadError) {
114        self.errors.push(error);
115    }
116
117    pub fn clear_errors(&mut self) {
118        self.errors.clear();
119    }
120
121    pub fn set_dragging(&mut self, dragging: bool) {
122        self.is_dragging = dragging;
123    }
124
125    pub fn set_uploading(&mut self, uploading: bool) {
126        self.is_uploading = uploading;
127    }
128
129    pub fn has_files(&self) -> bool {
130        !self.files.is_empty()
131    }
132
133    pub fn file_count(&self) -> usize {
134        self.files.len()
135    }
136}
137
138impl Default for FileUploadState {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144#[derive(Clone, Debug, PartialEq)]
145pub enum FileUploadSize {
146    Sm,
147    Md,
148    Lg,
149}
150
151impl FileUploadSize {
152    fn min_height(&self) -> Pixels {
153        match self {
154            FileUploadSize::Sm => px(120.0),
155            FileUploadSize::Md => px(180.0),
156            FileUploadSize::Lg => px(240.0),
157        }
158    }
159
160    fn icon_size(&self) -> Pixels {
161        match self {
162            FileUploadSize::Sm => px(32.0),
163            FileUploadSize::Md => px(48.0),
164            FileUploadSize::Lg => px(64.0),
165        }
166    }
167
168    fn text_size(&self) -> Pixels {
169        match self {
170            FileUploadSize::Sm => px(13.0),
171            FileUploadSize::Md => px(14.0),
172            FileUploadSize::Lg => px(16.0),
173        }
174    }
175}
176
177#[derive(Clone, Debug)]
178pub struct FileTypeFilter {
179    pub extensions: Vec<String>,
180    pub label: String,
181}
182
183impl FileTypeFilter {
184    pub fn new(extensions: Vec<&str>, label: impl Into<String>) -> Self {
185        Self {
186            extensions: extensions.into_iter().map(|s| s.to_string()).collect(),
187            label: label.into(),
188        }
189    }
190
191    pub fn images() -> Self {
192        Self::new(
193            vec!["png", "jpg", "jpeg", "gif", "bmp", "webp", "svg"],
194            "Images",
195        )
196    }
197
198    pub fn documents() -> Self {
199        Self::new(vec!["pdf", "doc", "docx", "txt", "rtf"], "Documents")
200    }
201
202    pub fn all() -> Self {
203        Self::new(vec![], "All files")
204    }
205
206    fn matches(&self, path: &Path) -> bool {
207        if self.extensions.is_empty() {
208            return true;
209        }
210
211        path.extension()
212            .and_then(|e| e.to_str())
213            .map(|ext| {
214                self.extensions
215                    .iter()
216                    .any(|allowed| allowed.eq_ignore_ascii_case(ext))
217            })
218            .unwrap_or(false)
219    }
220}
221
222type FilesChangedCallback = Rc<dyn Fn(&[SelectedFile], &mut Window, &mut App)>;
223type ErrorCallback = Rc<dyn Fn(&FileUploadError, &mut Window, &mut App)>;
224
225#[derive(Clone)]
226struct FileSelectionHandler {
227    state: Entity<FileUploadState>,
228    multiple: bool,
229    max_file_size: Option<u64>,
230    file_types: Option<FileTypeFilter>,
231    on_files_changed: Option<FilesChangedCallback>,
232    on_error: Option<ErrorCallback>,
233}
234
235#[derive(Default)]
236struct FileSelectionOutcome {
237    accepted: Vec<SelectedFile>,
238    rejected: Vec<FileUploadError>,
239}
240
241impl FileSelectionOutcome {
242    fn from_paths(
243        paths: Vec<PathBuf>,
244        file_types: Option<&FileTypeFilter>,
245        max_file_size: Option<u64>,
246    ) -> Self {
247        let mut outcome = Self::default();
248
249        for path in paths {
250            match validate_file(path, file_types, max_file_size) {
251                Ok(file) => outcome.accepted.push(file),
252                Err(error) => outcome.rejected.push(error),
253            }
254        }
255
256        outcome
257    }
258}
259
260impl FileSelectionHandler {
261    fn add_paths(&self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut App) {
262        let outcome =
263            FileSelectionOutcome::from_paths(paths, self.file_types.as_ref(), self.max_file_size);
264        if outcome.accepted.is_empty() && outcome.rejected.is_empty() {
265            return;
266        }
267
268        let files_changed = !outcome.accepted.is_empty();
269        let reported_errors = outcome.rejected.clone();
270        let committed_files = self.state.update(cx, |state, state_cx| {
271            if self.multiple {
272                state.files.extend(outcome.accepted);
273            } else if files_changed {
274                state.files = outcome.accepted;
275            }
276            state.errors.extend(outcome.rejected);
277            state_cx.notify();
278
279            files_changed.then(|| state.files.clone())
280        });
281
282        if let Some(handler) = &self.on_error {
283            for error in &reported_errors {
284                handler(error, window, cx);
285            }
286        }
287
288        if let (Some(handler), Some(files)) = (&self.on_files_changed, committed_files) {
289            handler(&files, window, cx);
290        }
291    }
292
293    fn remove_file(&self, index: usize, window: &mut Window, cx: &mut App) {
294        let committed_files = self.state.update(cx, |state, state_cx| {
295            if index >= state.files.len() {
296                return None;
297            }
298
299            state.remove_file(index);
300            state_cx.notify();
301            Some(state.files.clone())
302        });
303
304        if let (Some(handler), Some(files)) = (&self.on_files_changed, committed_files) {
305            handler(&files, window, cx);
306        }
307    }
308}
309
310fn validate_file(
311    path: PathBuf,
312    file_types: Option<&FileTypeFilter>,
313    max_file_size: Option<u64>,
314) -> Result<SelectedFile, FileUploadError> {
315    let file_name = path
316        .file_name()
317        .map(|name| name.to_string_lossy().to_string())
318        .unwrap_or_default();
319
320    if let Some(filter) = file_types {
321        if !filter.matches(&path) {
322            return Err(FileUploadError {
323                file_name,
324                message: format!(
325                    "File type not allowed. Accepted: {}",
326                    filter.extensions.join(", ")
327                ),
328            });
329        }
330    }
331
332    if let Some(max_size) = max_file_size {
333        let file_size = std::fs::metadata(&path)
334            .map(|metadata| metadata.len())
335            .unwrap_or(0);
336        if file_size > max_size {
337            let max_mb = max_size as f64 / (1024.0 * 1024.0);
338            return Err(FileUploadError {
339                file_name,
340                message: format!("File exceeds maximum size of {:.1} MB", max_mb),
341            });
342        }
343    }
344
345    Ok(SelectedFile::new(path))
346}
347
348#[derive(IntoElement)]
349pub struct FileUpload {
350    _id: ElementId,
351    base: Stateful<Div>,
352    state: Entity<FileUploadState>,
353    size: FileUploadSize,
354    multiple: bool,
355    max_file_size: Option<u64>,
356    file_types: Option<FileTypeFilter>,
357    disabled: bool,
358    show_file_list: bool,
359    show_previews: bool,
360    placeholder_text: Option<SharedString>,
361    placeholder_icon: Option<SharedString>,
362    on_files_changed: Option<FilesChangedCallback>,
363    on_error: Option<ErrorCallback>,
364    style: StyleRefinement,
365}
366
367impl FileUpload {
368    pub fn new(id: impl Into<ElementId>, state: Entity<FileUploadState>) -> Self {
369        let id = id.into();
370        Self {
371            _id: id.clone(),
372            base: div().id(id),
373            state,
374            size: FileUploadSize::Md,
375            multiple: false,
376            max_file_size: None,
377            file_types: None,
378            disabled: false,
379            show_file_list: true,
380            show_previews: true,
381            placeholder_text: None,
382            placeholder_icon: None,
383            on_files_changed: None,
384            on_error: None,
385            style: StyleRefinement::default(),
386        }
387    }
388
389    pub fn size(mut self, size: FileUploadSize) -> Self {
390        self.size = size;
391        self
392    }
393
394    pub fn multiple(mut self, multiple: bool) -> Self {
395        self.multiple = multiple;
396        self
397    }
398
399    pub fn max_file_size(mut self, bytes: u64) -> Self {
400        self.max_file_size = Some(bytes);
401        self
402    }
403
404    pub fn max_file_size_mb(mut self, mb: u64) -> Self {
405        self.max_file_size = Some(mb * 1024 * 1024);
406        self
407    }
408
409    pub fn file_types(mut self, filter: FileTypeFilter) -> Self {
410        self.file_types = Some(filter);
411        self
412    }
413
414    pub fn accept_images(self) -> Self {
415        self.file_types(FileTypeFilter::images())
416    }
417
418    pub fn accept_documents(self) -> Self {
419        self.file_types(FileTypeFilter::documents())
420    }
421
422    pub fn disabled(mut self, disabled: bool) -> Self {
423        self.disabled = disabled;
424        self
425    }
426
427    pub fn show_file_list(mut self, show: bool) -> Self {
428        self.show_file_list = show;
429        self
430    }
431
432    pub fn show_previews(mut self, show: bool) -> Self {
433        self.show_previews = show;
434        self
435    }
436
437    pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
438        self.placeholder_text = Some(text.into());
439        self
440    }
441
442    pub fn placeholder_icon(mut self, icon: impl Into<SharedString>) -> Self {
443        self.placeholder_icon = Some(icon.into());
444        self
445    }
446
447    pub fn on_files_changed<F>(mut self, handler: F) -> Self
448    where
449        F: Fn(&[SelectedFile], &mut Window, &mut App) + 'static,
450    {
451        self.on_files_changed = Some(Rc::new(handler));
452        self
453    }
454
455    pub fn on_error<F>(mut self, handler: F) -> Self
456    where
457        F: Fn(&FileUploadError, &mut Window, &mut App) + 'static,
458    {
459        self.on_error = Some(Rc::new(handler));
460        self
461    }
462
463    fn selection_handler(&self) -> FileSelectionHandler {
464        FileSelectionHandler {
465            state: self.state.clone(),
466            multiple: self.multiple,
467            max_file_size: self.max_file_size,
468            file_types: self.file_types.clone(),
469            on_files_changed: self.on_files_changed.clone(),
470            on_error: self.on_error.clone(),
471        }
472    }
473}
474
475impl Styled for FileUpload {
476    fn style(&mut self) -> &mut StyleRefinement {
477        &mut self.style
478    }
479}
480
481impl RenderOnce for FileUpload {
482    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
483        let selection_handler = self.selection_handler();
484        let theme = use_theme(cx);
485        let state = self.state.read(cx);
486        let is_dragging = state.is_dragging;
487        let is_uploading = state.is_uploading;
488        let has_files = state.has_files();
489        let files = state.files.clone();
490        let errors = state.errors.clone();
491        let user_style = self.style;
492
493        let disabled = self.disabled || is_uploading;
494
495        let border_color = if disabled {
496            theme.tokens.border.opacity(0.5)
497        } else if is_dragging {
498            theme.tokens.primary
499        } else {
500            theme.tokens.border
501        };
502
503        let bg_color = if disabled {
504            theme.tokens.muted.opacity(0.3)
505        } else if is_dragging {
506            theme.tokens.primary.opacity(0.1)
507        } else {
508            theme.tokens.background
509        };
510
511        let placeholder_text = self
512            .placeholder_text
513            .unwrap_or_else(|| "Drop files here or click to browse".into());
514
515        let placeholder_icon = self
516            .placeholder_icon
517            .unwrap_or_else(|| "cloud-upload".into());
518
519        let multiple = self.multiple;
520        let max_file_size = self.max_file_size;
521        let file_types = self.file_types.clone();
522        let drop_zone_state = self.state.clone();
523
524        let show_file_list = self.show_file_list;
525        let show_previews = self.show_previews;
526        let size = self.size.clone();
527
528        self.base
529            .flex()
530            .flex_col()
531            .gap(px(12.0))
532            .w_full()
533            .map(|mut this| {
534                this.style().refine(&user_style);
535                this
536            })
537            .child(
538                div()
539                    .id("drop-zone")
540                    .flex()
541                    .flex_col()
542                    .items_center()
543                    .justify_center()
544                    .gap(px(12.0))
545                    .w_full()
546                    .min_h(size.min_height())
547                    .px(px(24.0))
548                    .py(px(24.0))
549                    .rounded(theme.tokens.radius_lg)
550                    .border_2()
551                    .border_color(border_color)
552                    .bg(bg_color)
553                    .when(!disabled, |this| {
554                        this.cursor(CursorStyle::PointingHand).hover(move |style| {
555                            style
556                                .border_color(theme.tokens.primary.opacity(0.7))
557                                .bg(theme.tokens.primary.opacity(0.05))
558                        })
559                    })
560                    .when(disabled, |this| {
561                        this.cursor(CursorStyle::Arrow).opacity(0.6)
562                    })
563                    .when(!disabled, |this| {
564                        this.drag_over::<ExternalPaths>({
565                            let state = drop_zone_state.clone();
566                            move |style, _, _, cx| {
567                                state.update(cx, |s, cx| {
568                                    if !s.is_dragging {
569                                        s.set_dragging(true);
570                                        cx.notify();
571                                    }
572                                });
573                                style
574                                    .border_color(theme.tokens.primary)
575                                    .bg(theme.tokens.primary.opacity(0.1))
576                            }
577                        })
578                        .on_drop::<ExternalPaths>({
579                            let selection_handler = selection_handler.clone();
580                            let state = drop_zone_state.clone();
581                            move |paths: &ExternalPaths, window, cx| {
582                                selection_handler.add_paths(paths.paths().to_vec(), window, cx);
583                                state.update(cx, |s, cx| {
584                                    s.set_dragging(false);
585                                    cx.notify();
586                                });
587                            }
588                        })
589                        .on_file_drop_exit({
590                            let state = drop_zone_state.clone();
591                            move |_, _, cx| {
592                                state.update(cx, |s, cx| {
593                                    if s.is_dragging {
594                                        s.set_dragging(false);
595                                        cx.notify();
596                                    }
597                                });
598                            }
599                        })
600                    })
601                    .when(is_uploading, |this| {
602                        this.child(
603                            div()
604                                .flex()
605                                .flex_col()
606                                .items_center()
607                                .gap(px(12.0))
608                                .child(
609                                    Spinner::new()
610                                        .size(SpinnerSize::Lg)
611                                        .variant(SpinnerVariant::Primary),
612                                )
613                                .child(
614                                    div()
615                                        .text_size(size.text_size())
616                                        .text_color(theme.tokens.muted_foreground)
617                                        .child("Uploading..."),
618                                ),
619                        )
620                    })
621                    .when(!is_uploading, |this| {
622                        this.child(
623                            div()
624                                .flex()
625                                .flex_col()
626                                .items_center()
627                                .gap(px(8.0))
628                                .child(
629                                    Icon::new(placeholder_icon.to_string())
630                                        .size(size.icon_size())
631                                        .color(if is_dragging {
632                                            theme.tokens.primary
633                                        } else {
634                                            theme.tokens.muted_foreground
635                                        }),
636                                )
637                                .child(
638                                    div()
639                                        .text_size(size.text_size())
640                                        .text_color(if is_dragging {
641                                            theme.tokens.primary
642                                        } else {
643                                            theme.tokens.foreground
644                                        })
645                                        .font_weight(FontWeight::MEDIUM)
646                                        .child(placeholder_text.clone()),
647                                )
648                                .when_some(file_types.clone(), |this, filter| {
649                                    this.child(
650                                        div()
651                                            .text_size(px(12.0))
652                                            .text_color(theme.tokens.muted_foreground)
653                                            .child(if filter.extensions.is_empty() {
654                                                "All file types supported".to_string()
655                                            } else {
656                                                format!(
657                                                    "Accepted: {}",
658                                                    filter.extensions.join(", ")
659                                                )
660                                            }),
661                                    )
662                                })
663                                .when_some(max_file_size, |this, max_size| {
664                                    let max_mb = max_size as f64 / (1024.0 * 1024.0);
665                                    this.child(
666                                        div()
667                                            .text_size(px(12.0))
668                                            .text_color(theme.tokens.muted_foreground)
669                                            .child(format!("Max size: {:.0} MB", max_mb)),
670                                    )
671                                }),
672                        )
673                    })
674                    .on_click({
675                        let selection_handler = selection_handler.clone();
676                        move |_, window, cx| {
677                            if disabled {
678                                return;
679                            }
680
681                            let receiver = cx.prompt_for_paths(PathPromptOptions {
682                                files: true,
683                                directories: false,
684                                multiple,
685                                prompt: Some("Select files".into()),
686                            });
687
688                            let selection_handler = selection_handler.clone();
689                            window
690                                .spawn(cx, async move |cx| {
691                                    if let Ok(Ok(Some(paths))) = receiver.await {
692                                        cx.update(|window, cx| {
693                                            selection_handler.add_paths(paths, window, cx);
694                                        })
695                                        .ok();
696                                    }
697                                })
698                                .detach();
699                        }
700                    }),
701            )
702            .when(!errors.is_empty(), |this| {
703                this.child(
704                    div()
705                        .flex()
706                        .flex_col()
707                        .gap(px(8.0))
708                        .children(errors.iter().map(|error| {
709                            div()
710                                .flex()
711                                .items_center()
712                                .gap(px(8.0))
713                                .px(px(12.0))
714                                .py(px(8.0))
715                                .rounded(theme.tokens.radius_md)
716                                .bg(theme.tokens.destructive.opacity(0.1))
717                                .border_1()
718                                .border_color(theme.tokens.destructive.opacity(0.3))
719                                .child(
720                                    Icon::new("circle-alert")
721                                        .size(px(16.0))
722                                        .color(theme.tokens.destructive),
723                                )
724                                .child(
725                                    div()
726                                        .flex()
727                                        .flex_col()
728                                        .gap(px(2.0))
729                                        .child(
730                                            div()
731                                                .text_size(px(13.0))
732                                                .font_weight(FontWeight::MEDIUM)
733                                                .text_color(theme.tokens.destructive)
734                                                .child(error.file_name.clone()),
735                                        )
736                                        .child(
737                                            div()
738                                                .text_size(px(12.0))
739                                                .text_color(theme.tokens.destructive.opacity(0.8))
740                                                .child(error.message.clone()),
741                                        ),
742                                )
743                        })),
744                )
745            })
746            .when(show_file_list && has_files, |this| {
747                let selection_handler = selection_handler.clone();
748
749                this.child(div().flex().flex_col().gap(px(8.0)).children(
750                    files.iter().enumerate().map(|(index, file)| {
751                        let selection_handler = selection_handler.clone();
752                        let file_name = file.name.clone();
753                        let file_size = file.formatted_size();
754                        let is_image = file.is_image;
755                        let file_path = file.path.clone();
756
757                        div()
758                            .id(("file-item", index))
759                            .flex()
760                            .items_center()
761                            .gap(px(12.0))
762                            .px(px(12.0))
763                            .py(px(8.0))
764                            .rounded(theme.tokens.radius_md)
765                            .bg(theme.tokens.card)
766                            .border_1()
767                            .border_color(theme.tokens.border)
768                            .when(show_previews && is_image, |this| {
769                                this.child(
770                                    div()
771                                        .w(px(48.0))
772                                        .h(px(48.0))
773                                        .rounded(theme.tokens.radius_sm)
774                                        .bg(theme.tokens.muted)
775                                        .flex()
776                                        .items_center()
777                                        .justify_center()
778                                        .overflow_hidden()
779                                        .child(
780                                            img(file_path.to_string_lossy().to_string())
781                                                .w(px(48.0))
782                                                .h(px(48.0))
783                                                .object_fit(ObjectFit::Cover),
784                                        ),
785                                )
786                            })
787                            .when(!show_previews || !is_image, |this| {
788                                this.child(
789                                    div()
790                                        .w(px(40.0))
791                                        .h(px(40.0))
792                                        .rounded(theme.tokens.radius_sm)
793                                        .bg(theme.tokens.muted)
794                                        .flex()
795                                        .items_center()
796                                        .justify_center()
797                                        .child(
798                                            Icon::new(if is_image { "image" } else { "file" })
799                                                .size(px(20.0))
800                                                .color(theme.tokens.muted_foreground),
801                                        ),
802                                )
803                            })
804                            .child(
805                                div()
806                                    .flex_1()
807                                    .flex()
808                                    .flex_col()
809                                    .gap(px(2.0))
810                                    .overflow_hidden()
811                                    .child(
812                                        div()
813                                            .text_size(px(13.0))
814                                            .font_weight(FontWeight::MEDIUM)
815                                            .text_color(theme.tokens.foreground)
816                                            .overflow_hidden()
817                                            .text_ellipsis()
818                                            .whitespace_nowrap()
819                                            .child(file_name),
820                                    )
821                                    .child(
822                                        div()
823                                            .text_size(px(12.0))
824                                            .text_color(theme.tokens.muted_foreground)
825                                            .child(file_size),
826                                    ),
827                            )
828                            .when(!disabled, |this| {
829                                this.child(
830                                    div()
831                                        .id(("remove-btn", index))
832                                        .w(px(28.0))
833                                        .h(px(28.0))
834                                        .rounded(theme.tokens.radius_sm)
835                                        .flex()
836                                        .items_center()
837                                        .justify_center()
838                                        .cursor(CursorStyle::PointingHand)
839                                        .hover(|style| {
840                                            style.bg(theme.tokens.destructive.opacity(0.1))
841                                        })
842                                        .child(
843                                            Icon::new("x")
844                                                .size(px(16.0))
845                                                .color(theme.tokens.muted_foreground),
846                                        )
847                                        .on_click(move |_, window, cx| {
848                                            selection_handler.remove_file(index, window, cx);
849                                        }),
850                                )
851                            })
852                    }),
853                ))
854            })
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use super::*;
861    use crate::capabilities::foundation::theme::{install_theme, Theme};
862    use std::{cell::RefCell, rc::Rc};
863
864    struct EmptyTestView;
865
866    impl Render for EmptyTestView {
867        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
868            div()
869        }
870    }
871
872    struct FileUploadRenderTestView {
873        state: Entity<FileUploadState>,
874        render_count: Rc<RefCell<usize>>,
875    }
876
877    impl Render for FileUploadRenderTestView {
878        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
879            *self.render_count.borrow_mut() += 1;
880            FileUpload::new("file-upload-test", self.state.clone())
881        }
882    }
883
884    fn test_path(name: &str) -> PathBuf {
885        std::env::temp_dir().join(name)
886    }
887
888    fn file_names(files: &[SelectedFile]) -> Vec<String> {
889        files.iter().map(|file| file.name.clone()).collect()
890    }
891
892    #[gpui::test]
893    fn accepted_selection_notifies_once_with_the_committed_collection() {
894        let mut app = TestApp::new();
895        let state = app.update(|cx| cx.new(|_| FileUploadState::new()));
896        let changed_snapshots = Rc::new(RefCell::new(Vec::new()));
897        let state_for_callback = state.clone();
898        let snapshots_for_callback = changed_snapshots.clone();
899        let upload =
900            FileUpload::new("upload", state.clone()).on_files_changed(move |files, _, cx| {
901                let callback_names = file_names(files);
902                assert_eq!(
903                    callback_names,
904                    file_names(&state_for_callback.read(cx).files)
905                );
906                snapshots_for_callback.borrow_mut().push(callback_names);
907            });
908        let selection_handler = upload.selection_handler();
909        let mut window = app.open_window(|_, _| EmptyTestView);
910
911        window.update(|_, window, cx| {
912            selection_handler.add_paths(
913                vec![test_path("first.txt"), test_path("second.txt")],
914                window,
915                cx,
916            );
917        });
918
919        assert_eq!(
920            changed_snapshots.borrow().as_slice(),
921            &[vec!["first.txt".to_string(), "second.txt".to_string()]]
922        );
923        assert_eq!(
924            window.read(|_, cx| file_names(&state.read(cx).files)),
925            vec!["first.txt", "second.txt"]
926        );
927    }
928
929    #[gpui::test]
930    fn mixed_selection_reports_errors_and_notifies_one_final_collection() {
931        let mut app = TestApp::new();
932        let state = app.update(|cx| cx.new(|_| FileUploadState::new()));
933        let changed_snapshots = Rc::new(RefCell::new(Vec::new()));
934        let reported_errors = Rc::new(RefCell::new(Vec::new()));
935        let callback_order = Rc::new(RefCell::new(Vec::new()));
936        let snapshots_for_callback = changed_snapshots.clone();
937        let errors_for_callback = reported_errors.clone();
938        let order_for_change = callback_order.clone();
939        let order_for_error = callback_order.clone();
940        let state_for_error = state.clone();
941        let upload = FileUpload::new("upload", state.clone())
942            .file_types(FileTypeFilter::new(vec!["txt"], "Text"))
943            .on_files_changed(move |files, _, _| {
944                snapshots_for_callback.borrow_mut().push(file_names(files));
945                order_for_change.borrow_mut().push("changed".to_string());
946            })
947            .on_error(move |error, _, cx| {
948                assert_eq!(state_for_error.read(cx).files.len(), 2);
949                assert_eq!(state_for_error.read(cx).errors.len(), 2);
950                errors_for_callback
951                    .borrow_mut()
952                    .push(error.file_name.clone());
953                order_for_error
954                    .borrow_mut()
955                    .push(format!("error:{}", error.file_name));
956            });
957        let selection_handler = upload.selection_handler();
958        let mut window = app.open_window(|_, _| EmptyTestView);
959
960        window.update(|_, window, cx| {
961            selection_handler.add_paths(
962                vec![
963                    test_path("accepted.txt"),
964                    test_path("rejected.png"),
965                    test_path("also-accepted.txt"),
966                    test_path("also-rejected.pdf"),
967                ],
968                window,
969                cx,
970            );
971        });
972
973        assert_eq!(
974            reported_errors.borrow().as_slice(),
975            &["rejected.png", "also-rejected.pdf"]
976        );
977        assert_eq!(
978            changed_snapshots.borrow().as_slice(),
979            &[vec![
980                "accepted.txt".to_string(),
981                "also-accepted.txt".to_string(),
982            ]]
983        );
984        assert_eq!(
985            callback_order.borrow().as_slice(),
986            &["error:rejected.png", "error:also-rejected.pdf", "changed",]
987        );
988        assert_eq!(window.read(|_, cx| state.read(cx).errors.len()), 2);
989    }
990
991    #[gpui::test]
992    fn rejected_selection_does_not_report_a_collection_change() {
993        let mut app = TestApp::new();
994        let state = app.update(|cx| cx.new(|_| FileUploadState::new()));
995        let changed_calls = Rc::new(RefCell::new(0));
996        let error_calls = Rc::new(RefCell::new(0));
997        let changed_calls_for_callback = changed_calls.clone();
998        let error_calls_for_callback = error_calls.clone();
999        let upload = FileUpload::new("upload", state.clone())
1000            .max_file_size(1)
1001            .on_files_changed(move |_, _, _| {
1002                *changed_calls_for_callback.borrow_mut() += 1;
1003            })
1004            .on_error(move |_, _, _| {
1005                *error_calls_for_callback.borrow_mut() += 1;
1006            });
1007        let selection_handler = upload.selection_handler();
1008        let manifest_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
1009        let mut window = app.open_window(|_, _| EmptyTestView);
1010
1011        window.update(|_, window, cx| {
1012            selection_handler.add_paths(vec![manifest_path], window, cx);
1013        });
1014
1015        assert_eq!(*changed_calls.borrow(), 0);
1016        assert_eq!(*error_calls.borrow(), 1);
1017        assert!(window.read(|_, cx| state.read(cx).files.is_empty()));
1018        assert_eq!(window.read(|_, cx| state.read(cx).errors.len()), 1);
1019    }
1020
1021    #[gpui::test]
1022    fn removing_a_file_notifies_with_the_remaining_collection() {
1023        let mut app = TestApp::new();
1024        let state = app.update(|cx| {
1025            cx.new(|_| {
1026                let mut state = FileUploadState::new();
1027                state.add_file(SelectedFile::new(test_path("first.txt")));
1028                state.add_file(SelectedFile::new(test_path("second.txt")));
1029                state
1030            })
1031        });
1032        let changed_snapshots = Rc::new(RefCell::new(Vec::new()));
1033        let snapshots_for_callback = changed_snapshots.clone();
1034        let state_for_callback = state.clone();
1035        let upload =
1036            FileUpload::new("upload", state.clone()).on_files_changed(move |files, _, cx| {
1037                assert_eq!(
1038                    file_names(files),
1039                    file_names(&state_for_callback.read(cx).files)
1040                );
1041                snapshots_for_callback.borrow_mut().push(file_names(files));
1042            });
1043        let selection_handler = upload.selection_handler();
1044        let mut window = app.open_window(|_, _| EmptyTestView);
1045
1046        window.update(|_, window, cx| {
1047            selection_handler.remove_file(0, window, cx);
1048        });
1049
1050        assert_eq!(
1051            changed_snapshots.borrow().as_slice(),
1052            &[vec!["second.txt".to_string()]]
1053        );
1054        assert_eq!(
1055            window.read(|_, cx| file_names(&state.read(cx).files)),
1056            vec!["second.txt"]
1057        );
1058    }
1059
1060    #[gpui::test]
1061    fn selecting_a_file_invalidates_the_rendered_component() {
1062        let mut app = TestApp::new();
1063        app.update(|cx| install_theme(cx, Theme::light()));
1064        let render_count = Rc::new(RefCell::new(0));
1065        let mut window = app.open_window(|_, cx| FileUploadRenderTestView {
1066            state: cx.new(|_| FileUploadState::new()),
1067            render_count: render_count.clone(),
1068        });
1069        window.draw();
1070        let initial_render_count = *render_count.borrow();
1071
1072        window.update(|view, window, cx| {
1073            FileUpload::new("selection-handler", view.state.clone())
1074                .selection_handler()
1075                .add_paths(vec![test_path("selected.txt")], window, cx);
1076        });
1077        window.draw();
1078
1079        assert!(
1080            *render_count.borrow() > initial_render_count,
1081            "selecting a file should invalidate the rendered component"
1082        );
1083    }
1084}