1use super::{child_id, text};
7use crate::format_file_size;
8use arc_motion::{
9 ArcPresence, ArcPresenceConfig, arc_spring, arc_spring_with_options, is_reduced_motion,
10 spring::SpringOptions,
11};
12use arc_tokens::{ActiveArcTheme as _, Radii, Typography};
13use gpui_kit::{
14 App, ElementId, Entity, ExternalPaths, IntoElement, ParentElement, PathPromptOptions,
15 RenderOnce, Role, SharedString, Styled, TestSupportExt as _, WeakEntity, Window,
16 assets::IconName, base::StyledExt as _, div, prelude::*, px, relative, svg,
17};
18use std::{
19 collections::HashMap,
20 path::PathBuf,
21 rc::Rc,
22 sync::{
23 Arc,
24 atomic::{AtomicBool, Ordering},
25 },
26};
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct FileUploadItem {
29 pub id: SharedString,
30 pub path: PathBuf,
31 pub name: SharedString,
32 pub size: u64,
33 pub mime: SharedString,
34 pub error: Option<SharedString>,
35}
36impl FileUploadItem {
37 pub fn new(
38 id: impl Into<SharedString>,
39 path: impl Into<PathBuf>,
40 size: u64,
41 mime: impl Into<SharedString>,
42 ) -> Self {
43 let path = path.into();
44 let name = path
45 .file_name()
46 .unwrap_or_default()
47 .to_string_lossy()
48 .into_owned()
49 .into();
50 Self {
51 id: id.into(),
52 path,
53 name,
54 size,
55 mime: mime.into(),
56 error: None,
57 }
58 }
59}
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum UploadStatus {
62 Uploading,
63 Done,
64 Failed,
65}
66#[derive(Clone, Debug)]
67struct Upload {
68 status: UploadStatus,
69 progress: f32,
70 generation: u64,
71 cancel: Arc<AtomicBool>,
72}
73#[derive(Clone)]
74struct State {
75 files: Vec<FileUploadItem>,
76 retained: Vec<FileUploadItem>,
77 uploads: HashMap<SharedString, Upload>,
78 serial: u64,
79 notice: SharedString,
80}
81impl Drop for State {
82 fn drop(&mut self) {
83 for upload in self.uploads.values() {
84 upload.cancel.store(true, Ordering::Release);
85 }
86 }
87}
88#[derive(Clone)]
90pub struct UploadRequest {
91 pub item: FileUploadItem,
92 state: WeakEntity<State>,
93 generation: u64,
94 cancel: Arc<AtomicBool>,
95}
96impl UploadRequest {
97 pub fn is_cancelled(&self) -> bool {
98 self.cancel.load(Ordering::Acquire) || self.state.upgrade().is_none()
99 }
100 pub fn report_progress(&self, percent: f32, w: &mut Window, cx: &mut App) {
101 self.update(None, percent, w, cx)
102 }
103 pub fn finish(&self, result: Result<(), SharedString>, w: &mut Window, cx: &mut App) {
104 self.update(Some(result), 100.0, w, cx)
105 }
106 fn update(
107 &self,
108 result: Option<Result<(), SharedString>>,
109 percent: f32,
110 w: &mut Window,
111 cx: &mut App,
112 ) {
113 if self.is_cancelled() {
114 return;
115 }
116 let _ =
117 self.state.update(cx, |s, _| {
118 let Some(upload) = s.uploads.get_mut(&self.item.id).filter(|u| {
119 u.generation == self.generation && u.status == UploadStatus::Uploading
120 }) else {
121 return;
122 };
123 if let Some(result) = result {
124 upload.status = if result.is_ok() {
125 UploadStatus::Done
126 } else {
127 UploadStatus::Failed
128 };
129 if upload.status == UploadStatus::Done {
130 upload.progress = 100.0;
131 }
132 s.notice = if let Err(error) = result {
133 error
134 } else {
135 format!("{} uploaded.", self.item.name).into()
136 };
137 } else if percent.is_finite() {
138 upload.progress = percent.clamp(upload.progress, 100.0);
139 }
140 });
141 w.refresh();
142 }
143}
144type Change = Rc<dyn Fn(&[FileUploadItem], &mut Window, &mut App)>;
145type Start = Rc<dyn Fn(UploadRequest, &mut Window, &mut App)>;
146#[derive(Clone)]
147struct Options {
148 accept: SharedString,
149 max_size: Option<u64>,
150 multiple: bool,
151 disabled: bool,
152 controlled: Option<Vec<FileUploadItem>>,
153 change: Option<Change>,
154 start: Option<Start>,
155}
156pub fn file_upload_accepts(name: &str, mime: &str, accept: &str) -> bool {
157 let types = accept
158 .split(',')
159 .map(str::trim)
160 .filter(|s| !s.is_empty())
161 .map(str::to_ascii_lowercase)
162 .collect::<Vec<_>>();
163 types.is_empty()
164 || types.iter().any(|t| {
165 if t.starts_with('.') {
166 name.to_ascii_lowercase().ends_with(t)
167 } else if let Some(prefix) = t.strip_suffix('*') {
168 mime.to_ascii_lowercase().starts_with(prefix)
169 } else {
170 mime.eq_ignore_ascii_case(t)
171 }
172 })
173}
174fn inferred_mime(path: &std::path::Path) -> &'static str {
175 match path
176 .extension()
177 .and_then(|e| e.to_str())
178 .unwrap_or_default()
179 .to_ascii_lowercase()
180 .as_str()
181 {
182 "png" => "image/png",
183 "jpg" | "jpeg" => "image/jpeg",
184 "gif" => "image/gif",
185 "svg" => "image/svg+xml",
186 "pdf" => "application/pdf",
187 "txt" | "md" | "rs" => "text/plain",
188 "csv" => "text/csv",
189 "json" => "application/json",
190 "zip" => "application/zip",
191 _ => "application/octet-stream",
192 }
193}
194fn start_upload(
195 state: &Entity<State>,
196 item: &FileUploadItem,
197 start: &Option<Start>,
198 w: &mut Window,
199 cx: &mut App,
200) {
201 if item.error.is_some() || start.is_none() {
202 return;
203 }
204 let cancel = Arc::new(AtomicBool::new(false));
205 let generation = state.update(cx, |s, _| {
206 s.serial += 1;
207 if let Some(old) = s.uploads.remove(&item.id) {
208 old.cancel.store(true, Ordering::Release);
209 }
210 s.uploads.insert(
211 item.id.clone(),
212 Upload {
213 status: UploadStatus::Uploading,
214 progress: 0.0,
215 generation: s.serial,
216 cancel: cancel.clone(),
217 },
218 );
219 s.serial
220 });
221 if let Some(start) = start {
222 start(
223 UploadRequest {
224 item: item.clone(),
225 state: state.downgrade(),
226 generation,
227 cancel,
228 },
229 w,
230 cx,
231 )
232 }
233}
234fn add_paths(
235 state: &Entity<State>,
236 paths: &[PathBuf],
237 options: &Options,
238 w: &mut Window,
239 cx: &mut App,
240) {
241 if options.disabled || paths.is_empty() {
242 return;
243 }
244 let mut incoming = vec![];
245 for path in paths
246 .iter()
247 .take(if options.multiple { usize::MAX } else { 1 })
248 {
249 let metadata = std::fs::metadata(path);
250 let serial = state.update(cx, |s, _| {
251 s.serial += 1;
252 s.serial
253 });
254 let mut item = FileUploadItem::new(
255 format!("upload-{serial}"),
256 path,
257 metadata.as_ref().map(|m| m.len()).unwrap_or(0),
258 inferred_mime(path),
259 );
260 item.error = if !metadata.is_ok_and(|m| m.is_file()) {
261 Some("Cannot read this file.".into())
262 } else if !file_upload_accepts(&item.name, &item.mime, &options.accept) {
263 Some("This file type is not accepted.".into())
264 } else if options.max_size.is_some_and(|limit| item.size > limit) {
265 Some("File exceeds the size limit.".into())
266 } else {
267 None
268 };
269 incoming.push(item);
270 }
271 let mut files = options
272 .controlled
273 .clone()
274 .unwrap_or_else(|| state.read(cx).files.clone());
275 if !options.multiple {
276 files.clear();
277 state.update(cx, |s, _| {
278 for upload in s.uploads.values() {
279 upload.cancel.store(true, Ordering::Release);
280 }
281 s.uploads.clear();
282 });
283 }
284 files.extend(incoming.clone());
285 state.update(cx, |s, _| {
286 if options.controlled.is_none() {
287 s.files = files.clone();
288 }
289 s.notice = format!(
290 "{} files added; {} need attention.",
291 incoming.len(),
292 incoming.iter().filter(|i| i.error.is_some()).count()
293 )
294 .into();
295 });
296 if let Some(cb) = &options.change {
297 cb(&files, w, cx)
298 }
299 for item in incoming {
300 start_upload(state, &item, &options.start, w, cx)
301 }
302 w.refresh();
303}
304#[derive(IntoElement)]
305pub struct FileUpload {
306 id: ElementId,
307 label: SharedString,
308 description: SharedString,
309 options: Options,
310}
311impl FileUpload {
312 pub fn new(id: impl Into<ElementId>) -> Self {
313 Self {
314 id: id.into(),
315 label: "Upload files".into(),
316 description: "Drop files here or browse from your device.".into(),
317 options: Options {
318 accept: "".into(),
319 max_size: None,
320 multiple: true,
321 disabled: false,
322 controlled: None,
323 change: None,
324 start: None,
325 },
326 }
327 }
328 pub fn label(mut self, v: impl Into<SharedString>) -> Self {
329 self.label = v.into();
330 self
331 }
332 pub fn description(mut self, v: impl Into<SharedString>) -> Self {
333 self.description = v.into();
334 self
335 }
336 pub fn accept(mut self, v: impl Into<SharedString>) -> Self {
337 self.options.accept = v.into();
338 self
339 }
340 pub fn max_size(mut self, v: u64) -> Self {
341 self.options.max_size = Some(v);
342 self
343 }
344 pub fn multiple(mut self, v: bool) -> Self {
345 self.options.multiple = v;
346 self
347 }
348 pub fn disabled(mut self, v: bool) -> Self {
349 self.options.disabled = v;
350 self
351 }
352 pub fn value(mut self, v: impl IntoIterator<Item = FileUploadItem>) -> Self {
353 self.options.controlled = Some(v.into_iter().collect());
354 self
355 }
356 pub fn on_change(
357 mut self,
358 f: impl Fn(&[FileUploadItem], &mut Window, &mut App) + 'static,
359 ) -> Self {
360 self.options.change = Some(Rc::new(f));
361 self
362 }
363 pub fn on_upload(mut self, f: impl Fn(UploadRequest, &mut Window, &mut App) + 'static) -> Self {
364 self.options.start = Some(Rc::new(f));
365 self
366 }
367}
368impl RenderOnce for FileUpload {
369 fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
370 let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, _| State {
371 files: vec![],
372 retained: vec![],
373 uploads: HashMap::new(),
374 serial: 0,
375 notice: "".into(),
376 });
377 let colors = cx.arc_theme().colors;
378 let reduced = is_reduced_motion(cx);
379 let files = self
380 .options
381 .controlled
382 .clone()
383 .unwrap_or_else(|| state.read(cx).files.clone());
384 let options = self.options;
385 let pick = options.clone();
386 let drop = options.clone();
387 let drop_disabled = options.disabled;
388 let st = state.clone();
389 let drop_state = state.clone();
390
391 let dropzone = div()
393 .id(child_id(&self.id, "dropzone"))
394 .test_support()
395 .role(Role::Button)
396 .aria_label(self.label.clone())
397 .tab_index(0)
398 .tab_stop(true)
399 .cursor_pointer()
400 .flex()
401 .flex_row()
402 .items_center()
403 .gap(px(12.0))
404 .min_h(px(92.0))
405 .p(px(16.0))
406 .w_full()
407 .border_1()
408 .border_dashed()
409 .rounded(Radii::PANEL)
410 .border_color(colors.border_strong)
411 .bg(colors.surface)
412 .when(!options.disabled, |zone| {
413 zone.on_click(move |_, w, cx| {
414 let rx = cx.prompt_for_paths(PathPromptOptions {
415 files: true,
416 directories: false,
417 multiple: pick.multiple,
418 prompt: None,
419 });
420 let st = st.downgrade();
421 let opts = pick.clone();
422 w.spawn(cx, async move |cx| {
423 if let Ok(Ok(Some(paths))) = rx.await {
424 let _ = cx.update(|w, cx| {
425 if let Some(st) = st.upgrade() {
426 add_paths(&st, &paths, &opts, w, cx)
427 }
428 });
429 }
430 })
431 .detach();
432 })
433 .hover(move |s| s.border_color(colors.accent).bg(colors.accent_subtle))
434 .drag_over::<ExternalPaths>(move |style, _, _, _| {
435 style.border_color(colors.accent).bg(colors.accent_subtle)
436 })
437 })
438 .when(options.disabled, |zone| zone.opacity(0.52))
439 .can_drop(move |payload, _, _| !drop_disabled && payload.is::<ExternalPaths>())
440 .on_drop(move |paths: &ExternalPaths, w, cx| {
441 add_paths(&drop_state, paths.paths(), &drop, w, cx)
442 })
443 .child(
444 div().flex_none().text_color(colors.accent_strong).child(
446 svg()
447 .path(IconName::CloudUpload.path())
448 .size(px(20.0))
449 .text_color(colors.accent_strong),
450 ),
451 )
452 .child(
453 div()
454 .min_w(px(0.0))
455 .flex_1()
456 .flex()
457 .flex_col()
458 .gap(px(3.0))
459 .child(
460 div()
461 .text_size(Typography::TEXT_SM)
462 .font_medium()
463 .text_color(colors.foreground)
464 .child(self.label.clone()),
465 )
466 .child(
467 div()
468 .text_size(Typography::TEXT_XS)
469 .text_color(colors.text_muted)
470 .child(self.description.clone()),
471 ),
472 )
473 .child(
474 div()
475 .flex_none()
476 .text_size(Typography::TEXT_XS)
477 .font_medium()
478 .text_color(colors.accent_strong)
479 .child("Browse"),
480 );
481 let mut root = super::surface(cx)
482 .id(self.id.clone())
483 .child(dropzone)
484 .child(
485 div()
486 .id(child_id(&self.id, "status"))
487 .role(Role::Status)
488 .when(!state.read(cx).notice.is_empty(), |s| {
489 s.mt(px(8.0)).child(text(state.read(cx).notice.clone(), cx))
490 }),
491 );
492 let mut retained = state.read(cx).retained.clone();
493 for item in &files {
494 if let Some(old) = retained.iter_mut().find(|i| i.id == item.id) {
495 *old = item.clone()
496 } else {
497 retained.push(item.clone())
498 }
499 }
500 let mut keep = vec![];
501 for item in retained {
502 let present = files.iter().any(|i| i.id == item.id);
503 let id = child_id(&self.id, format!("file-{}", item.id));
504 let presence = ArcPresence::new((id.clone(), "presence"), present)
505 .animate_initial(false)
506 .sample(w, cx);
507 if !presence.should_render() {
508 continue;
509 }
510 keep.push(item.clone());
511 let upload = state.read(cx).uploads.get(&item.id).cloned();
512 let st = state.clone();
513 let removed = item.clone();
514 let opts = options.clone();
515 let row = file_row(
516 id.clone(),
517 &item,
518 upload,
519 present,
520 presence.progress,
521 reduced,
522 options.disabled,
523 state.clone(),
524 opts.start.clone(),
525 st,
526 removed,
527 opts,
528 w,
529 cx,
530 );
531 root = root.child(row);
532 }
533 state.update(cx, |s, _| {
534 s.retained = keep;
535 let valid = files
536 .iter()
537 .map(|i| i.id.clone())
538 .collect::<std::collections::HashSet<_>>();
539 s.uploads.retain(|id, u| {
540 if valid.contains(id) {
541 true
542 } else {
543 u.cancel.store(true, Ordering::Release);
544 false
545 }
546 });
547 });
548 root.text_size(Typography::TEXT_SM)
549 }
550}
551
552#[allow(clippy::too_many_arguments)]
555fn file_row(
556 id: ElementId,
557 item: &FileUploadItem,
558 upload: Option<Upload>,
559 present: bool,
560 presence: f32,
561 reduced: bool,
562 disabled: bool,
563 state: Entity<State>,
564 start: Option<Start>,
565 st: Entity<State>,
566 removed: FileUploadItem,
567 opts: Options,
568 w: &mut Window,
569 cx: &mut App,
570) -> gpui_kit::AnyElement {
571 let colors = cx.arc_theme().colors;
572 let status = upload.as_ref().map(|u| u.status);
573 let filled = match status {
576 Some(UploadStatus::Done) => {
577 reduced
578 || arc_spring_with_options(
579 (id.clone(), "progress"),
580 100.0,
581 SpringOptions::new(cx.arc_theme().motion.spring.smooth),
582 w,
583 cx,
584 )
585 .value
586 >= 99.5
587 }
588 Some(UploadStatus::Uploading) => false,
589 _ => true,
590 };
591 let shown = match status {
592 Some(UploadStatus::Done) if !filled => Some(UploadStatus::Uploading),
593 other => other,
594 };
595 let progress = status.is_some().then(|| {
596 arc_spring(
597 (id.clone(), "progress"),
598 if status == Some(UploadStatus::Done) {
599 100.0
600 } else {
601 upload.as_ref().map(|u| u.progress).unwrap_or(0.0)
602 },
603 cx.arc_theme().motion.spring.smooth,
604 w,
605 cx,
606 )
607 .clamp(0.0, 100.0)
608 });
609 let phase_text = match shown {
610 Some(UploadStatus::Uploading) => {
611 format!("Uploading {:.0}%", progress.unwrap_or(0.0))
612 }
613 Some(UploadStatus::Done) => "Uploaded".to_owned(),
614 Some(UploadStatus::Failed) => "Upload failed".to_owned(),
615 None => String::new(),
616 };
617
618 let bar_presence =
620 ArcPresence::new((id.clone(), "bar"), shown == Some(UploadStatus::Uploading))
621 .config(ArcPresenceConfig {
622 enter_duration: cx.arc_theme().motion.duration.standard,
623 exit_duration: cx.arc_theme().motion.duration.exit
624 + cx.arc_theme().motion.duration.fast,
625 ..ArcPresenceConfig::default()
626 })
627 .animate_initial(false)
628 .sample(w, cx);
629
630 let mut copy = div()
631 .min_w(px(0.0))
632 .flex_1()
633 .flex()
634 .flex_col()
635 .gap(px(2.0))
636 .child(
637 div()
638 .text_size(Typography::TEXT_SM)
639 .font_medium()
640 .text_color(colors.foreground)
641 .truncate()
642 .child(item.name.clone()),
643 )
644 .child(
645 div()
646 .text_size(Typography::TEXT_XS)
647 .text_color(colors.text_muted)
648 .flex()
649 .flex_row()
650 .flex_wrap()
651 .child(format_file_size(item.size))
652 .when(phase_text.is_empty() && item.error.is_none(), |d| d)
653 .when(!phase_text.is_empty(), |d| {
654 d.child(div().px(px(5.0)).child("·"))
655 .child(div().child(phase_text.clone()))
656 }),
657 );
658 if let Some(error) = &item.error {
659 copy = copy.child(
660 div()
661 .text_size(Typography::TEXT_XS)
662 .text_color(colors.danger)
663 .child(error.clone()),
664 );
665 }
666 if bar_presence.should_render() && progress.is_some() {
667 let frac = (progress.unwrap_or(0.0) / 100.0).clamp(0.0, 1.0);
668 copy = copy.child(
669 div()
670 .id(child_id(&id, "bar"))
671 .test_support()
672 .mt(px(5.0))
673 .mb(px(1.0))
674 .h(px(3.0))
675 .overflow_hidden()
676 .rounded_full()
677 .bg(colors.border)
678 .opacity(bar_presence.progress)
679 .child(
680 div()
681 .h_full()
682 .w(relative(frac))
683 .min_w(px(0.0))
684 .rounded_full()
685 .bg(colors.accent),
686 ),
687 );
688 }
689
690 let status_slot = div()
692 .flex_none()
693 .size(px(26.0))
694 .flex()
695 .items_center()
696 .justify_center()
697 .id(child_id(&id, "status-slot"))
698 .test_support();
699 let status_slot = if shown == Some(UploadStatus::Failed) {
700 let retry_state = state.clone();
701 let retry = item.clone();
702 let retry_start = start.clone();
703 status_slot.child(
704 div()
705 .id(child_id(&id, "retry"))
706 .test_support()
707 .role(Role::Button)
708 .aria_label(format!("Retry {}", item.name))
709 .tab_index(0)
710 .tab_stop(true)
711 .cursor_pointer()
712 .size(px(26.0))
713 .rounded_full()
714 .flex()
715 .items_center()
716 .justify_center()
717 .text_color(colors.text_secondary)
718 .when(disabled || !present, |d| d.opacity(0.52))
719 .hover(move |s| s.bg(colors.surface).text_color(colors.foreground))
720 .on_click(move |_, w, cx| {
721 if disabled || !present {
722 return;
723 }
724 start_upload(&retry_state, &retry, &retry_start, w, cx);
725 w.refresh()
726 })
727 .child(
728 svg()
729 .path(IconName::RotateCw.path())
730 .size(px(14.0))
731 .text_color(colors.text_secondary),
732 ),
733 )
734 } else if shown == Some(UploadStatus::Done) {
735 status_slot.child(
736 svg()
737 .path(IconName::Check.path())
738 .size(px(14.0))
739 .text_color(colors.success),
740 )
741 } else {
742 status_slot
743 };
744
745 let remove_state = st.clone();
746 let removed_item = removed.clone();
747 let remove_opts = opts.clone();
748 let row = div()
749 .id(id.clone())
750 .test_support()
751 .opacity(presence)
752 .mt(px(6.0))
753 .flex()
754 .flex_row()
755 .items_center()
756 .gap(px(12.0))
757 .p(px(10.0))
758 .pl(px(12.0))
759 .rounded(Radii::CONTROL)
760 .border_1()
761 .border_color(colors.border_subtle)
762 .bg(colors.surface_muted)
763 .child(
764 div()
765 .flex_none()
766 .size(px(24.0))
767 .flex()
768 .items_center()
769 .justify_center()
770 .child(
771 svg()
772 .path(file_type_icon(&item.mime, &item.name).path())
773 .size(px(16.0))
774 .text_color(colors.text_secondary),
775 ),
776 )
777 .child(copy)
778 .child(status_slot)
779 .child(
780 div()
781 .id(child_id(&id, "remove"))
782 .test_support()
783 .role(Role::Button)
784 .aria_label(format!("Remove {}", item.name))
785 .tab_index(0)
786 .tab_stop(true)
787 .cursor_pointer()
788 .size(px(26.0))
789 .rounded_full()
790 .flex()
791 .items_center()
792 .justify_center()
793 .text_color(colors.text_muted)
794 .when(disabled || !present, |d| d.opacity(0.52))
795 .hover(move |s| s.bg(colors.surface).text_color(colors.foreground))
796 .on_click(move |_, w, cx| {
797 if disabled || !present {
798 return;
799 }
800 remove_state.update(cx, |s, _| {
801 if let Some(upload) = s.uploads.remove(&removed_item.id) {
802 upload.cancel.store(true, Ordering::Release);
803 }
804 });
805 let next = remove_opts
806 .controlled
807 .clone()
808 .unwrap_or_else(|| remove_state.read(cx).files.clone())
809 .into_iter()
810 .filter(|i| i.id != removed_item.id)
811 .collect::<Vec<_>>();
812 if remove_opts.controlled.is_none() {
813 remove_state.update(cx, |s, _| s.files = next.clone());
814 }
815 if let Some(cb) = &remove_opts.change {
816 cb(&next, w, cx)
817 }
818 w.refresh();
819 })
820 .child(
821 svg()
822 .path(IconName::Close.path())
823 .size(px(15.0))
824 .text_color(colors.text_muted),
825 ),
826 );
827 row.into_any_element()
828}
829
830fn file_type_icon(mime: &str, name: &str) -> IconName {
832 if mime.starts_with("image/") {
833 IconName::FileImage
834 } else if mime.starts_with("text/") {
835 IconName::FileText
836 } else if mime.contains("zip") || name.to_ascii_lowercase().ends_with(".gz") {
837 IconName::FileArchive
838 } else {
839 IconName::File
840 }
841}
842#[cfg(test)]
843mod tests {
844 use super::*;
845 use gpui_kit::TestAppContext;
846 use std::cell::RefCell;
847
848 struct UploadTestHost;
849 impl gpui_kit::Render for UploadTestHost {
850 fn render(&mut self, _: &mut Window, _: &mut gpui_kit::Context<Self>) -> impl IntoElement {
851 div()
852 }
853 }
854
855 fn state(cx: &mut App) -> Entity<State> {
856 cx.new(|_| State {
857 files: vec![],
858 retained: vec![],
859 uploads: HashMap::new(),
860 serial: 0,
861 notice: "".into(),
862 })
863 }
864
865 #[gpui_kit::test]
866 fn upload_reports_are_monotonic_and_stale_requests_are_cancelled(cx: &mut TestAppContext) {
867 let (_, cx) = cx.add_window_view(|_, _| UploadTestHost);
868 let completed = Rc::new(RefCell::new(None));
869 let captured_result = completed.clone();
870 cx.update(|w, cx| {
871 let state = state(cx);
872 let item = FileUploadItem::new("a", "example.txt", 4, "text/plain");
873 let requests = Rc::new(RefCell::new(Vec::new()));
874 let captured = requests.clone();
875 let start: Option<Start> = Some(Rc::new(move |r, _, _| captured.borrow_mut().push(r)));
876 start_upload(&state, &item, &start, w, cx);
877 let first = requests.borrow()[0].clone();
878 first.report_progress(60.0, w, cx);
879 first.report_progress(10.0, w, cx);
880 first.report_progress(f32::NAN, w, cx);
881 assert_eq!(state.read(cx).uploads[&item.id].progress, 60.0);
882 first.finish(Err("Retry me".into()), w, cx);
883 assert_eq!(
884 state.read(cx).uploads[&item.id].status,
885 UploadStatus::Failed
886 );
887 start_upload(&state, &item, &start, w, cx);
888 assert!(first.is_cancelled());
889 first.finish(Ok(()), w, cx);
890 assert_eq!(
891 state.read(cx).uploads[&item.id].status,
892 UploadStatus::Uploading
893 );
894 let retry = requests.borrow()[1].clone();
895 retry.report_progress(150.0, w, cx);
896 assert_eq!(state.read(cx).uploads[&item.id].progress, 100.0);
897 retry.finish(Ok(()), w, cx);
898 retry.finish(Err("Late result".into()), w, cx);
899 assert_eq!(state.read(cx).uploads[&item.id].status, UploadStatus::Done);
900 *captured_result.borrow_mut() = Some(retry);
901 drop(state);
902 });
903 cx.update(|_, _| {});
905 assert!(completed.borrow().as_ref().unwrap().is_cancelled());
906 }
907
908 #[gpui_kit::test]
909 fn add_paths_enforces_size_type_single_selection_and_disabled(cx: &mut TestAppContext) {
910 let (_, cx) = cx.add_window_view(|_, _| UploadTestHost);
911 cx.update(|w, cx| {
912 let state = state(cx);
913 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/blocks/file_upload.rs");
915 let mut options = FileUpload::new("validation").options;
916 options.multiple = false;
917 options.accept = ".rs".into();
918 options.max_size = Some(1);
919 add_paths(&state, &[path.clone(), path.clone()], &options, w, cx);
920 assert_eq!(state.read(cx).files.len(), 1);
921 assert_eq!(
922 state.read(cx).files[0].error.as_deref(),
923 Some("File exceeds the size limit.")
924 );
925 options.max_size = None;
926 options.accept = "image/*".into();
927 add_paths(&state, std::slice::from_ref(&path), &options, w, cx);
928 assert_eq!(
929 state.read(cx).files[0].error.as_deref(),
930 Some("This file type is not accepted.")
931 );
932 options.accept = ".rs".into();
933 add_paths(&state, std::slice::from_ref(&path), &options, w, cx);
934 assert!(state.read(cx).files[0].error.is_none());
935 let original = state.read(cx).files.clone();
936 add_paths(&state, &[], &options, w, cx);
937 assert_eq!(state.read(cx).files, original);
938 options.disabled = true;
939 add_paths(&state, &[path], &options, w, cx);
940 assert_eq!(state.read(cx).files, original);
941 });
942 }
943
944 #[test]
945 fn accept_handles_extensions_mime_and_wildcards() {
946 assert!(file_upload_accepts("A.PNG", "image/png", ".png"));
947 assert!(file_upload_accepts("x", "image/png", "image/*"));
948 assert!(file_upload_accepts(
949 "x",
950 "application/pdf",
951 "text/*,application/pdf"
952 ));
953 assert!(!file_upload_accepts(
954 "a.exe",
955 "application/octet-stream",
956 "image/*"
957 ));
958 }
959}