Skip to main content

arc_ui/inputs/
file_dropzone.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/file-dropzone/file-dropzone.tsx` & `.module.css`
3//!
4//! P4 Component #25: `file-dropzone`
5//!
6//! - A drop target + file list:
7//!   - Rows carry a name, size, and status (`uploading` with a progress bar + percent,
8//!     `uploaded`, `failed` with the reason); the prompt copy swaps; failures reveal the
9//!     reason through the field message.
10//!   - `file_dropzone_add` filters name duplicates and `max_files`; a single-file zone
11//!     (`multiple == false`) replaces its row.
12//!
13//! Known deviations from upstream:
14//! - Rows model files by name + size (GPUI's window file-drop hands over real paths, so the
15//!   caller maps them into items); there is no OS file-picker hookup (tests and callers add
16//!   items directly) and no image thumbnails — type icons stand in.
17//! - Uploads are simulated by the caller through `on_items_change`; removal just stops
18//!   emitting progress for the row. The drag glow, pointer-follow wash, and shake animation
19//!   are omitted (no OS drag hover events reach the window in this backend).
20
21use std::rc::Rc;
22
23use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
24use gpui_kit::{
25    AnyElement, App, ElementId, ExternalPaths, IntoElement, ParentElement, PathPromptOptions,
26    Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
27    base::{Button as BaseButton, StyledExt as _},
28    div,
29    prelude::*,
30    px,
31};
32
33/// The upload status of one row.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum FileDropzoneStatus {
36    Uploading,
37    Uploaded,
38    Failed,
39}
40
41/// One row in the file list. A row without a status is a plain selection.
42#[derive(Clone, Debug, PartialEq)]
43pub struct FileDropzoneItem {
44    pub id: SharedString,
45    pub name: SharedString,
46    /// Size in bytes.
47    pub size: u64,
48    pub status: Option<FileDropzoneStatus>,
49    /// 0..=100 while uploading.
50    pub progress: Option<f32>,
51    pub error: Option<SharedString>,
52    pub retryable: bool,
53}
54
55impl FileDropzoneItem {
56    /// A plain selection (no upload).
57    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>, size: u64) -> Self {
58        Self {
59            id: id.into(),
60            name: name.into(),
61            size,
62            status: None,
63            progress: None,
64            error: None,
65            retryable: false,
66        }
67    }
68
69    pub fn status(mut self, status: FileDropzoneStatus) -> Self {
70        self.status = Some(status);
71        self
72    }
73
74    pub fn progress(mut self, progress: f32) -> Self {
75        self.progress = Some(progress);
76        self
77    }
78
79    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
80        self.error = Some(error.into());
81        self
82    }
83
84    pub fn retryable(mut self, retryable: bool) -> Self {
85        self.retryable = retryable;
86        self
87    }
88}
89
90/// Formats a byte count as `512 B`, `12 KB`, or `3.2 MB`.
91pub fn format_file_size(bytes: u64) -> String {
92    if bytes < 1024 {
93        return format!("{bytes} B");
94    }
95    if bytes < 1024 * 1024 {
96        return format!("{} KB", bytes / 1024);
97    }
98    let mb = bytes as f64 / (1024.0 * 1024.0);
99    if mb >= 10.0 {
100        format!("{} MB", mb.round() as u64)
101    } else {
102        format!("{:.1} MB", mb)
103    }
104}
105
106/// Render the file list under the drop target or inside its edge.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum FileDropzoneListPlacement {
109    Below,
110    Inside,
111}
112
113#[derive(Clone)]
114struct FileDropzoneInternal {
115    items: Vec<FileDropzoneItem>,
116    seen_external: Vec<FileDropzoneItem>,
117    dragging: bool,
118    next_file_id: usize,
119    notice: Option<SharedString>,
120}
121
122impl FileDropzoneInternal {
123    fn new(default_items: Vec<FileDropzoneItem>, _cx: &mut App) -> Self {
124        let next_file_id = default_items.len() + 1;
125        Self {
126            seen_external: default_items.clone(),
127            items: default_items,
128            dragging: false,
129            next_file_id,
130            notice: None,
131        }
132    }
133}
134
135fn items_from_os_paths(
136    paths: &[std::path::PathBuf],
137    next_file_id: &mut usize,
138    max_size: Option<u64>,
139    sim_upload: bool,
140) -> Vec<FileDropzoneItem> {
141    let mut flat_paths = Vec::new();
142    for path in paths {
143        if path.is_dir() {
144            if let Ok(entries) = std::fs::read_dir(path) {
145                for entry in entries.flatten() {
146                    let p = entry.path();
147                    if p.is_file() {
148                        flat_paths.push(p);
149                    }
150                }
151            }
152        } else {
153            flat_paths.push(path.clone());
154        }
155    }
156    let mut incoming = Vec::with_capacity(flat_paths.len());
157    for path in flat_paths {
158        let Some(name_os) = path.file_name() else {
159            continue;
160        };
161        let name = name_os.to_string_lossy().into_owned();
162        if name.is_empty() {
163            continue;
164        }
165        let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
166        let id = SharedString::from(format!("file-{}", *next_file_id));
167        *next_file_id += 1;
168        let mut item = FileDropzoneItem::new(id, name, bytes);
169        if let Some(limit) = max_size
170            && bytes > limit
171        {
172            item = item
173                .status(FileDropzoneStatus::Failed)
174                .error(SharedString::from(format!(
175                    "Exceeds {} limit",
176                    format_file_size(limit)
177                )))
178                .retryable(true);
179        } else if sim_upload {
180            item = item.status(FileDropzoneStatus::Uploading).progress(6.0);
181        } else {
182            item = item.status(FileDropzoneStatus::Uploaded);
183        }
184        incoming.push(item);
185    }
186    incoming
187}
188
189/// Arc `FileDropzone` — a drop target with a staged file list and upload simulation.
190#[derive(IntoElement)]
191pub struct FileDropzone {
192    id: ElementId,
193    label: SharedString,
194    description: SharedString,
195    items: Vec<FileDropzoneItem>,
196    /// Uploads each added row: the row's progress advances on a smooth spring to 100 and the
197    /// row settles as uploaded (simulated; see deviations).
198    simulate_upload: bool,
199    max_files: usize,
200    max_size: Option<u64>,
201    list_placement: FileDropzoneListPlacement,
202    compact_at: Option<usize>,
203    disabled: bool,
204    width: Option<Pixels>,
205    #[allow(clippy::type_complexity)]
206    on_items_change: Option<Rc<dyn Fn(&[FileDropzoneItem], &mut Window, &mut App)>>,
207}
208
209/// Render the file list under the drop target or inside its edge.
210impl FileDropzone {
211    pub fn new(id: impl Into<ElementId>) -> Self {
212        Self {
213            id: id.into(),
214            label: "Add files".into(),
215            description: "Drop files here or choose from your device".into(),
216            items: Vec::new(),
217            simulate_upload: true,
218            max_files: 5,
219            max_size: None,
220            list_placement: FileDropzoneListPlacement::Below,
221            compact_at: None,
222            disabled: false,
223            width: None,
224            on_items_change: None,
225        }
226    }
227
228    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
229        self.label = label.into();
230        self
231    }
232
233    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
234        self.description = description.into();
235        self
236    }
237
238    /// Rows present at mount render in place without an entrance.
239    pub fn max_files(mut self, max_files: usize) -> Self {
240        self.max_files = max_files.max(1);
241        self
242    }
243
244    pub fn items(mut self, items: Vec<FileDropzoneItem>) -> Self {
245        self.items = items;
246        self
247    }
248
249    /// Uploads each added row: the row's progress advances on a smooth spring to 100 and the
250    /// row settles as uploaded (simulated; see deviations).
251    pub fn simulate_upload(mut self, simulate: bool) -> Self {
252        self.simulate_upload = simulate;
253        self
254    }
255
256    /// Files above this many bytes fail with a size reason and never upload.
257    pub fn max_size(mut self, max: u64) -> Self {
258        self.max_size = Some(max);
259        self
260    }
261
262    /// Render the file list under the drop target or inside its edge.
263    pub fn list_placement(mut self, placement: FileDropzoneListPlacement) -> Self {
264        self.list_placement = placement;
265        self
266    }
267
268    /// Once the list holds this many files, the prompt folds to a slim bar.
269    pub fn compact_at(mut self, count: usize) -> Self {
270        self.compact_at = Some(count);
271        self
272    }
273
274    pub fn disabled(mut self, disabled: bool) -> Self {
275        self.disabled = disabled;
276        self
277    }
278
279    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
280        self.width = Some(width.into());
281        self
282    }
283
284    pub fn on_items_change(
285        mut self,
286        handler: impl Fn(&[FileDropzoneItem], &mut Window, &mut App) + 'static,
287    ) -> Self {
288        self.on_items_change = Some(Rc::new(handler));
289        self
290    }
291}
292
293/// Adds incoming entries to the list, filtering name duplicates and `max_files`. A single-file
294/// zone (`multiple == false`) replaces its row.
295pub fn file_dropzone_add(
296    items: &[FileDropzoneItem],
297    incoming: &[FileDropzoneItem],
298    max_files: usize,
299    multiple: bool,
300) -> Result<Vec<FileDropzoneItem>, SharedString> {
301    let kept: Vec<FileDropzoneItem> = if multiple { items.to_vec() } else { Vec::new() };
302    if kept.len() + incoming.len() > max_files {
303        return Err(SharedString::from(format!(
304            "You can add up to {max_files} files."
305        )));
306    }
307    let mut next = kept;
308    for item in incoming {
309        if next.len() >= max_files {
310            break;
311        }
312        if next.iter().any(|existing| existing.name == item.name) {
313            continue;
314        }
315        next.push(item.clone());
316    }
317    Ok(next)
318}
319
320impl RenderOnce for FileDropzone {
321    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
322        let theme = cx.arc_theme().clone();
323        let colors = theme.colors;
324
325        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-dropzone-state".into());
326        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
327            FileDropzoneInternal::new(self.items.clone(), cx)
328        });
329        if !self.items.is_empty() && internal.read(cx).seen_external != self.items {
330            internal.update(cx, |s, _| {
331                s.seen_external = self.items.clone();
332                s.items = self.items.clone();
333            });
334        }
335
336        // Advance active simulated uploads smoothly towards 100%.
337        if self.simulate_upload {
338            let mut any_uploading = false;
339            let mut finished_any = false;
340            internal.update(cx, |s, _| {
341                for it in &mut s.items {
342                    if it.status == Some(FileDropzoneStatus::Uploading) {
343                        let p = it.progress.unwrap_or(0.0);
344                        let next_p = (p + 1.8).min(100.0);
345                        if next_p >= 100.0 {
346                            it.progress = Some(100.0);
347                            it.status = Some(FileDropzoneStatus::Uploaded);
348                            finished_any = true;
349                        } else {
350                            it.progress = Some(next_p);
351                            any_uploading = true;
352                        }
353                    }
354                }
355            });
356            if any_uploading {
357                window.request_animation_frame();
358            }
359            if finished_any && let Some(cb) = self.on_items_change.clone() {
360                let latest = internal.read(cx).items.clone();
361                window.defer(cx, move |window, cx| {
362                    cb(&latest, window, cx);
363                });
364            }
365        }
366
367        let snap = internal.read(cx).clone();
368        let items = snap.items.clone();
369        let dragging = snap.dragging;
370        let compact = self.compact_at.is_some_and(|at| items.len() >= at);
371
372        let note_copy = snap
373            .notice
374            .clone()
375            .unwrap_or_else(|| SharedString::from(format!("Up to {} files", self.max_files)));
376        let drop_copy = SharedString::from("Drop to upload");
377
378        // File rows.
379        let on_change_rows = self.on_items_change.clone();
380        let row_els: Vec<AnyElement> = items
381            .iter()
382            .map(|item| {
383                let st_remove = internal.clone();
384                let st_retry = internal.clone();
385                let cb_remove = on_change_rows.clone();
386                let cb_retry = on_change_rows.clone();
387                let item_id = item.id.clone();
388                let item_id_retry = item.id.clone();
389                let is_failed = item.status == Some(FileDropzoneStatus::Failed);
390                let status_text = match item.status {
391                    Some(FileDropzoneStatus::Uploading) => SharedString::from(format!(
392                        "Uploading {}%",
393                        item.progress.unwrap_or(0.0).round() as i64
394                    )),
395                    Some(FileDropzoneStatus::Uploaded) => SharedString::from("Uploaded"),
396                    Some(FileDropzoneStatus::Failed) => {
397                        item.error.clone().unwrap_or_else(|| "Upload failed".into())
398                    }
399                    None => SharedString::from(""),
400                };
401                let status_color = match item.status {
402                    Some(FileDropzoneStatus::Uploaded) => colors.success,
403                    Some(FileDropzoneStatus::Failed) => colors.danger,
404                    _ => colors.text_muted,
405                };
406                let progress_pct = item.progress.unwrap_or(0.0).clamp(0.0, 100.0);
407                let progress_bar = match item.status {
408                    Some(FileDropzoneStatus::Uploading) => Some(
409                        div()
410                            .w_full()
411                            .mt(px(4.0))
412                            .h(px(3.0))
413                            .rounded_full()
414                            .overflow_hidden()
415                            .bg(colors.control_track)
416                            .child(
417                                gpui_kit::canvas(
418                                    |_, _, _| {},
419                                    move |bounds, _, window, _| {
420                                        let w = f32::from(bounds.size.width)
421                                            * (progress_pct / 100.0).clamp(0.0, 1.0);
422                                        if w > 0.5 {
423                                            window.paint_quad(gpui_kit::fill(
424                                                gpui_kit::Bounds::new(
425                                                    bounds.origin,
426                                                    gpui_kit::size(px(w), bounds.size.height),
427                                                ),
428                                                colors.control_fill,
429                                            ));
430                                        }
431                                    },
432                                )
433                                .size_full(),
434                            ),
435                    ),
436                    _ => None,
437                };
438                div()
439                    .id(ElementId::NamedChild(
440                        self.id.clone().into(),
441                        SharedString::from(format!("row-{}", item.id)),
442                    ))
443                    .test_support()
444                    .role(Role::ListItem)
445                    .aria_label(item.name.clone())
446                    .w_full()
447                    .flex()
448                    .flex_row()
449                    .items_center()
450                    .gap(px(8.0))
451                    .py(px(6.0))
452                    .border_b_1()
453                    .border_color(colors.border_subtle)
454                    .child(
455                        div()
456                            .flex()
457                            .flex_col()
458                            .min_w_0()
459                            .flex_1()
460                            .child(
461                                div()
462                                    .text_size(Typography::TEXT_SM)
463                                    .font_medium()
464                                    .text_color(colors.foreground)
465                                    .truncate()
466                                    .child(item.name.clone()),
467                            )
468                            .child(
469                                div()
470                                    .flex()
471                                    .flex_row()
472                                    .items_center()
473                                    .gap(px(4.0))
474                                    .text_size(Typography::TEXT_XS)
475                                    .text_color(colors.text_muted)
476                                    .child(SharedString::from(format_file_size(item.size)))
477                                    .when(!status_text.is_empty(), |this| {
478                                        this.child(SharedString::from("·")).child(
479                                            div().text_color(status_color).child(status_text),
480                                        )
481                                    }),
482                            )
483                            .when_some(progress_bar, |this, bar| this.child(bar)),
484                    )
485                    .when(is_failed, |this| {
486                        this.child(
487                            BaseButton::new(ElementId::NamedChild(
488                                self.id.clone().into(),
489                                SharedString::from(format!("retry-{}", item.id)),
490                            ))
491                            .accessibility_label(SharedString::from(format!("Retry {}", item.name)))
492                            .on_click(move |_, window, cx| {
493                                let mut latest = Vec::new();
494                                st_retry.update(cx, |s, _| {
495                                    if let Some(target) =
496                                        s.items.iter_mut().find(|it| it.id == item_id_retry)
497                                    {
498                                        target.status = Some(FileDropzoneStatus::Uploading);
499                                        target.progress = Some(4.0);
500                                        target.error = None;
501                                    }
502                                    s.seen_external = s.items.clone();
503                                    latest = s.items.clone();
504                                });
505                                if let Some(ref cb) = cb_retry {
506                                    cb(&latest, window, cx);
507                                }
508                                window.refresh();
509                            })
510                            .h(px(22.0))
511                            .px(px(8.0))
512                            .flex()
513                            .items_center()
514                            .justify_center()
515                            .rounded(px(6.0))
516                            .bg(colors.surface_muted)
517                            .text_size(Typography::TEXT_XS)
518                            .text_color(colors.foreground)
519                            .cursor_pointer()
520                            .child(SharedString::from("Retry")),
521                        )
522                    })
523                    .child(
524                        BaseButton::new(ElementId::NamedChild(
525                            self.id.clone().into(),
526                            SharedString::from(format!("remove-{}", item.id)),
527                        ))
528                        .accessibility_label(SharedString::from(format!("Remove {}", item.name)))
529                        .on_click(move |_, window, cx| {
530                            let mut latest = Vec::new();
531                            st_remove.update(cx, |s, _| {
532                                s.items.retain(|it| it.id != item_id);
533                                s.seen_external = s.items.clone();
534                                s.notice = None;
535                                latest = s.items.clone();
536                            });
537                            if let Some(ref cb) = cb_remove {
538                                cb(&latest, window, cx);
539                            }
540                            window.refresh();
541                        })
542                        .w(px(22.0))
543                        .h(px(22.0))
544                        .flex()
545                        .items_center()
546                        .justify_center()
547                        .rounded(px(6.0))
548                        .cursor_pointer()
549                        .text_color(colors.text_muted)
550                        .hover(move |s| s.bg(colors.surface_muted))
551                        .child(
552                            div()
553                                .text_size(Typography::TEXT_XS)
554                                .child(SharedString::from("×")),
555                        ),
556                    )
557                    .into_any_element()
558            })
559            .collect();
560
561        let st_drop_click = internal.clone();
562        let st_drop_ext = internal.clone();
563        let max_files = self.max_files;
564        let max_size = self.max_size;
565        let sim_upload = self.simulate_upload;
566        let disabled_drop = self.disabled;
567        let on_change_drop = self.on_items_change.clone();
568        let on_change_ext = self.on_items_change.clone();
569
570        div()
571            .id(self.id.clone())
572            .test_support()
573            .when_some(self.width, |this, w| this.w(w))
574            .when(self.width.is_none(), |this| this.w_full())
575            .flex()
576            .flex_col()
577            .gap(Spacing::S2)
578            .child(
579                // Drop target.
580                div()
581                    .id(ElementId::NamedChild(
582                        self.id.clone().into(),
583                        "dropzone".into(),
584                    ))
585                    .test_support()
586                    .role(Role::Button)
587                    .aria_label(self.label.clone())
588                    .w_full()
589                    .h(if compact { px(56.0) } else { px(120.0) })
590                    .flex()
591                    .flex_col()
592                    .items_center()
593                    .justify_center()
594                    .gap(px(6.0))
595                    .rounded(Radii::PANEL)
596                    .border_1()
597                    .border_color(if dragging {
598                        colors.control_fill
599                    } else {
600                        colors.border
601                    })
602                    .bg(if dragging {
603                        oklab_mix(colors.control_fill, colors.surface, 0.06)
604                    } else {
605                        colors.surface
606                    })
607                    .when(!self.disabled, |this| {
608                        this.cursor_pointer()
609                            .hover(move |s| s.bg(colors.surface_muted))
610                            .can_drop(|payload, _, _| payload.is::<ExternalPaths>())
611                            .drag_over::<ExternalPaths>(move |style, _, _, _| {
612                                style.border_color(colors.control_fill).bg(oklab_mix(
613                                    colors.control_fill,
614                                    colors.surface,
615                                    0.06,
616                                ))
617                            })
618                            .on_drop(move |paths: &ExternalPaths, window, cx| {
619                                if disabled_drop {
620                                    return;
621                                }
622                                let mut updated: Option<Vec<FileDropzoneItem>> = None;
623                                st_drop_ext.update(cx, |s, _| {
624                                    s.dragging = false;
625                                    let incoming = items_from_os_paths(
626                                        paths.paths(),
627                                        &mut s.next_file_id,
628                                        max_size,
629                                        sim_upload,
630                                    );
631                                    if incoming.is_empty() {
632                                        return;
633                                    }
634                                    match file_dropzone_add(
635                                        &s.items,
636                                        &incoming,
637                                        max_files,
638                                        max_files > 1,
639                                    ) {
640                                        Ok(next) => {
641                                            s.items = next.clone();
642                                            s.seen_external = next.clone();
643                                            s.notice = None;
644                                            updated = Some(next);
645                                        }
646                                        Err(err) => {
647                                            s.notice = Some(err);
648                                        }
649                                    }
650                                });
651                                if let Some(list) = updated
652                                    && let Some(ref cb) = on_change_ext
653                                {
654                                    cb(&list, window, cx);
655                                }
656                                window.refresh();
657                            })
658                            .on_click(move |_, window, cx| {
659                                if disabled_drop {
660                                    return;
661                                }
662                                let rx = cx.prompt_for_paths(PathPromptOptions {
663                                    files: true,
664                                    directories: false,
665                                    multiple: max_files > 1,
666                                    prompt: None,
667                                });
668                                let st_picked = st_drop_click.clone();
669                                let cb_picked = on_change_drop.clone();
670                                window
671                                    .spawn(cx, async move |cx| {
672                                        let Ok(Ok(Some(paths))) = rx.await else {
673                                            return;
674                                        };
675                                        let _ = cx.update(|window, cx| {
676                                            let mut updated: Option<Vec<FileDropzoneItem>> = None;
677                                            st_picked.update(cx, |s, _| {
678                                                let incoming = items_from_os_paths(
679                                                    &paths,
680                                                    &mut s.next_file_id,
681                                                    max_size,
682                                                    sim_upload,
683                                                );
684                                                if incoming.is_empty() {
685                                                    return;
686                                                }
687                                                match file_dropzone_add(
688                                                    &s.items,
689                                                    &incoming,
690                                                    max_files,
691                                                    max_files > 1,
692                                                ) {
693                                                    Ok(next) => {
694                                                        s.items = next.clone();
695                                                        s.seen_external = next.clone();
696                                                        s.notice = None;
697                                                        updated = Some(next);
698                                                    }
699                                                    Err(err) => {
700                                                        s.notice = Some(err);
701                                                    }
702                                                }
703                                            });
704                                            if let Some(list) = updated
705                                                && let Some(ref cb) = cb_picked
706                                            {
707                                                cb(&list, window, cx);
708                                            }
709                                            window.refresh();
710                                        });
711                                    })
712                                    .detach();
713                            })
714                    })
715                    .child(
716                        div()
717                            .text_size(Typography::TEXT_SM)
718                            .font_medium()
719                            .text_color(colors.foreground)
720                            .child(if dragging {
721                                drop_copy.clone()
722                            } else {
723                                self.label.clone()
724                            }),
725                    )
726                    .child(
727                        div()
728                            .text_size(Typography::TEXT_XS)
729                            .text_color(colors.text_muted)
730                            .child(self.description.clone()),
731                    )
732                    .child(
733                        div()
734                            .text_size(Typography::TEXT_XS)
735                            .text_color(colors.text_muted)
736                            .child(note_copy),
737                    ),
738            )
739            .child(div().flex().flex_col().children(row_els))
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use std::cell::RefCell;
746
747    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
748    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
749
750    use super::*;
751
752    struct DropzoneHost {
753        events: Rc<RefCell<Vec<String>>>,
754    }
755
756    impl Render for DropzoneHost {
757        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
758            let _ = &self.events;
759            div().w(px(480.0)).p(px(16.0)).child(
760                FileDropzone::new("dropzone-test")
761                    .label("Add files")
762                    .max_files(5)
763                    .items(vec![
764                        FileDropzoneItem::new("f1", "spec.pdf", 1024 * 512)
765                            .status(FileDropzoneStatus::Uploaded),
766                        FileDropzoneItem::new("f2", "model.bin", 1024 * 1024 * 3)
767                            .status(FileDropzoneStatus::Uploading)
768                            .progress(45.0),
769                        FileDropzoneItem::new("f3", "dump.zip", 1024 * 1024 * 12)
770                            .status(FileDropzoneStatus::Failed)
771                            .error("Server unreachable"),
772                    ]),
773            )
774        }
775    }
776
777    fn dropzone_element(name: &str) -> ElementId {
778        ElementId::NamedChild(ElementId::Name("dropzone-test".into()).into(), name.into())
779    }
780
781    #[gpui_kit::test]
782    fn dropzone_renders_rows_and_statuses(cx: &mut TestAppContext) {
783        cx.update(|cx| {
784            gpui_kit::init(cx);
785            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
786        });
787
788        let host = DropzoneHost {
789            events: Rc::new(RefCell::new(Vec::new())),
790        };
791        let (_view, cx) = cx.add_window_view(|_, _| host);
792
793        cx.update(|window, cx| {
794            window.render_frame(cx);
795            let zone = window.find(dropzone_element("dropzone"));
796            assert_eq!(zone.role(), Some(Role::Button));
797            for id in ["f1", "f2", "f3"] {
798                let row = window.find(dropzone_element(&format!("row-{id}")));
799                assert_eq!(row.role(), Some(Role::ListItem));
800            }
801        });
802    }
803
804    #[gpui_kit::test]
805    fn dropzone_rows_expose_file_names(cx: &mut TestAppContext) {
806        cx.update(|cx| {
807            gpui_kit::init(cx);
808            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
809        });
810
811        let host = DropzoneHost {
812            events: Rc::new(RefCell::new(Vec::new())),
813        };
814        let (_view, cx) = cx.add_window_view(|_, _| host);
815
816        cx.update(|window, cx| {
817            window.render_frame(cx);
818            let row = window.find(dropzone_element("row-f1"));
819            assert_eq!(row.role(), Some(Role::ListItem));
820            let row2 = window.find(dropzone_element("row-f3"));
821            assert_eq!(row2.role(), Some(Role::ListItem));
822        });
823    }
824
825    #[gpui_kit::test]
826    fn dropzone_reduced_motion_renders(cx: &mut TestAppContext) {
827        cx.update(|cx| {
828            gpui_kit::init(cx);
829            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
830            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
831        });
832
833        let host = DropzoneHost {
834            events: Rc::new(RefCell::new(Vec::new())),
835        };
836        let (_view, cx) = cx.add_window_view(|_, _| host);
837
838        cx.update(|window, cx| {
839            window.render_frame(cx);
840            assert!(window.try_find(dropzone_element("row-f1")).is_some());
841        });
842    }
843
844    #[test]
845    fn file_dropzone_add_filters_and_caps() {
846        let existing = vec![FileDropzoneItem::new("f1", "a.pdf", 100)];
847        let incoming = vec![
848            FileDropzoneItem::new("f2", "b.pdf", 200),
849            FileDropzoneItem::new("f3", "a.pdf", 100), // duplicate name
850            FileDropzoneItem::new("f4", "c.pdf", 300),
851        ];
852        let next = file_dropzone_add(&existing, &incoming, 4, true).unwrap();
853        assert_eq!(next.len(), 3);
854        assert!(next.iter().all(|i| i.name != "a.pdf" || i.id == "f1"));
855
856        // Single-file mode replaces.
857        let next = file_dropzone_add(&existing, &incoming[..1], 5, false).unwrap();
858        assert_eq!(next.len(), 1);
859        assert_eq!(next[0].name, "b.pdf");
860
861        // Over the cap: an error.
862        let err = file_dropzone_add(&existing, &incoming, 2, true).unwrap_err();
863        assert_eq!(err, "You can add up to 2 files.");
864    }
865
866    #[test]
867    fn format_file_size_units() {
868        assert_eq!(format_file_size(512), "512 B");
869        assert_eq!(format_file_size(1024), "1 KB");
870        assert_eq!(format_file_size(1024 * 512), "512 KB");
871        assert_eq!(format_file_size(1024 * 1024 * 3), "3.0 MB");
872        assert_eq!(format_file_size((1024.0 * 1024.0 * 3.2) as u64), "3.2 MB");
873    }
874}