arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/file-dropzone/file-dropzone.tsx` & `.module.css`
//!
//! P4 Component #25: `file-dropzone`
//!
//! - A drop target + file list:
//!   - Rows carry a name, size, and status (`uploading` with a progress bar + percent,
//!     `uploaded`, `failed` with the reason); the prompt copy swaps; failures reveal the
//!     reason through the field message.
//!   - `file_dropzone_add` filters name duplicates and `max_files`; a single-file zone
//!     (`multiple == false`) replaces its row.
//!
//! Known deviations from upstream:
//! - Rows model files by name + size (GPUI's window file-drop hands over real paths, so the
//!   caller maps them into items); there is no OS file-picker hookup (tests and callers add
//!   items directly) and no image thumbnails — type icons stand in.
//! - Uploads are simulated by the caller through `on_items_change`; removal just stops
//!   emitting progress for the row. The drag glow, pointer-follow wash, and shake animation
//!   are omitted (no OS drag hover events reach the window in this backend).

use std::rc::Rc;

use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, ElementId, ExternalPaths, IntoElement, ParentElement, PathPromptOptions,
    Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    div,
    prelude::*,
    px,
};

/// The upload status of one row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileDropzoneStatus {
    Uploading,
    Uploaded,
    Failed,
}

/// One row in the file list. A row without a status is a plain selection.
#[derive(Clone, Debug, PartialEq)]
pub struct FileDropzoneItem {
    pub id: SharedString,
    pub name: SharedString,
    /// Size in bytes.
    pub size: u64,
    pub status: Option<FileDropzoneStatus>,
    /// 0..=100 while uploading.
    pub progress: Option<f32>,
    pub error: Option<SharedString>,
    pub retryable: bool,
}

impl FileDropzoneItem {
    /// A plain selection (no upload).
    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>, size: u64) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            size,
            status: None,
            progress: None,
            error: None,
            retryable: false,
        }
    }

    pub fn status(mut self, status: FileDropzoneStatus) -> Self {
        self.status = Some(status);
        self
    }

    pub fn progress(mut self, progress: f32) -> Self {
        self.progress = Some(progress);
        self
    }

    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
        self.error = Some(error.into());
        self
    }

    pub fn retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }
}

/// Formats a byte count as `512 B`, `12 KB`, or `3.2 MB`.
pub fn format_file_size(bytes: u64) -> String {
    if bytes < 1024 {
        return format!("{bytes} B");
    }
    if bytes < 1024 * 1024 {
        return format!("{} KB", bytes / 1024);
    }
    let mb = bytes as f64 / (1024.0 * 1024.0);
    if mb >= 10.0 {
        format!("{} MB", mb.round() as u64)
    } else {
        format!("{:.1} MB", mb)
    }
}

/// Render the file list under the drop target or inside its edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileDropzoneListPlacement {
    Below,
    Inside,
}

#[derive(Clone)]
struct FileDropzoneInternal {
    items: Vec<FileDropzoneItem>,
    seen_external: Vec<FileDropzoneItem>,
    dragging: bool,
    next_file_id: usize,
    notice: Option<SharedString>,
}

impl FileDropzoneInternal {
    fn new(default_items: Vec<FileDropzoneItem>, _cx: &mut App) -> Self {
        let next_file_id = default_items.len() + 1;
        Self {
            seen_external: default_items.clone(),
            items: default_items,
            dragging: false,
            next_file_id,
            notice: None,
        }
    }
}

fn items_from_os_paths(
    paths: &[std::path::PathBuf],
    next_file_id: &mut usize,
    max_size: Option<u64>,
    sim_upload: bool,
) -> Vec<FileDropzoneItem> {
    let mut flat_paths = Vec::new();
    for path in paths {
        if path.is_dir() {
            if let Ok(entries) = std::fs::read_dir(path) {
                for entry in entries.flatten() {
                    let p = entry.path();
                    if p.is_file() {
                        flat_paths.push(p);
                    }
                }
            }
        } else {
            flat_paths.push(path.clone());
        }
    }
    let mut incoming = Vec::with_capacity(flat_paths.len());
    for path in flat_paths {
        let Some(name_os) = path.file_name() else {
            continue;
        };
        let name = name_os.to_string_lossy().into_owned();
        if name.is_empty() {
            continue;
        }
        let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
        let id = SharedString::from(format!("file-{}", *next_file_id));
        *next_file_id += 1;
        let mut item = FileDropzoneItem::new(id, name, bytes);
        if let Some(limit) = max_size
            && bytes > limit
        {
            item = item
                .status(FileDropzoneStatus::Failed)
                .error(SharedString::from(format!(
                    "Exceeds {} limit",
                    format_file_size(limit)
                )))
                .retryable(true);
        } else if sim_upload {
            item = item.status(FileDropzoneStatus::Uploading).progress(6.0);
        } else {
            item = item.status(FileDropzoneStatus::Uploaded);
        }
        incoming.push(item);
    }
    incoming
}

/// Arc `FileDropzone` — a drop target with a staged file list and upload simulation.
#[derive(IntoElement)]
pub struct FileDropzone {
    id: ElementId,
    label: SharedString,
    description: SharedString,
    items: Vec<FileDropzoneItem>,
    /// Uploads each added row: the row's progress advances on a smooth spring to 100 and the
    /// row settles as uploaded (simulated; see deviations).
    simulate_upload: bool,
    max_files: usize,
    max_size: Option<u64>,
    list_placement: FileDropzoneListPlacement,
    compact_at: Option<usize>,
    disabled: bool,
    width: Option<Pixels>,
    #[allow(clippy::type_complexity)]
    on_items_change: Option<Rc<dyn Fn(&[FileDropzoneItem], &mut Window, &mut App)>>,
}

/// Render the file list under the drop target or inside its edge.
impl FileDropzone {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Add files".into(),
            description: "Drop files here or choose from your device".into(),
            items: Vec::new(),
            simulate_upload: true,
            max_files: 5,
            max_size: None,
            list_placement: FileDropzoneListPlacement::Below,
            compact_at: None,
            disabled: false,
            width: None,
            on_items_change: None,
        }
    }

    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = label.into();
        self
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = description.into();
        self
    }

    /// Rows present at mount render in place without an entrance.
    pub fn max_files(mut self, max_files: usize) -> Self {
        self.max_files = max_files.max(1);
        self
    }

    pub fn items(mut self, items: Vec<FileDropzoneItem>) -> Self {
        self.items = items;
        self
    }

    /// Uploads each added row: the row's progress advances on a smooth spring to 100 and the
    /// row settles as uploaded (simulated; see deviations).
    pub fn simulate_upload(mut self, simulate: bool) -> Self {
        self.simulate_upload = simulate;
        self
    }

    /// Files above this many bytes fail with a size reason and never upload.
    pub fn max_size(mut self, max: u64) -> Self {
        self.max_size = Some(max);
        self
    }

    /// Render the file list under the drop target or inside its edge.
    pub fn list_placement(mut self, placement: FileDropzoneListPlacement) -> Self {
        self.list_placement = placement;
        self
    }

    /// Once the list holds this many files, the prompt folds to a slim bar.
    pub fn compact_at(mut self, count: usize) -> Self {
        self.compact_at = Some(count);
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_items_change(
        mut self,
        handler: impl Fn(&[FileDropzoneItem], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_items_change = Some(Rc::new(handler));
        self
    }
}

/// Adds incoming entries to the list, filtering name duplicates and `max_files`. A single-file
/// zone (`multiple == false`) replaces its row.
pub fn file_dropzone_add(
    items: &[FileDropzoneItem],
    incoming: &[FileDropzoneItem],
    max_files: usize,
    multiple: bool,
) -> Result<Vec<FileDropzoneItem>, SharedString> {
    let kept: Vec<FileDropzoneItem> = if multiple { items.to_vec() } else { Vec::new() };
    if kept.len() + incoming.len() > max_files {
        return Err(SharedString::from(format!(
            "You can add up to {max_files} files."
        )));
    }
    let mut next = kept;
    for item in incoming {
        if next.len() >= max_files {
            break;
        }
        if next.iter().any(|existing| existing.name == item.name) {
            continue;
        }
        next.push(item.clone());
    }
    Ok(next)
}

impl RenderOnce for FileDropzone {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-dropzone-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            FileDropzoneInternal::new(self.items.clone(), cx)
        });
        if !self.items.is_empty() && internal.read(cx).seen_external != self.items {
            internal.update(cx, |s, _| {
                s.seen_external = self.items.clone();
                s.items = self.items.clone();
            });
        }

        // Advance active simulated uploads smoothly towards 100%.
        if self.simulate_upload {
            let mut any_uploading = false;
            let mut finished_any = false;
            internal.update(cx, |s, _| {
                for it in &mut s.items {
                    if it.status == Some(FileDropzoneStatus::Uploading) {
                        let p = it.progress.unwrap_or(0.0);
                        let next_p = (p + 1.8).min(100.0);
                        if next_p >= 100.0 {
                            it.progress = Some(100.0);
                            it.status = Some(FileDropzoneStatus::Uploaded);
                            finished_any = true;
                        } else {
                            it.progress = Some(next_p);
                            any_uploading = true;
                        }
                    }
                }
            });
            if any_uploading {
                window.request_animation_frame();
            }
            if finished_any && let Some(cb) = self.on_items_change.clone() {
                let latest = internal.read(cx).items.clone();
                window.defer(cx, move |window, cx| {
                    cb(&latest, window, cx);
                });
            }
        }

        let snap = internal.read(cx).clone();
        let items = snap.items.clone();
        let dragging = snap.dragging;
        let compact = self.compact_at.is_some_and(|at| items.len() >= at);

        let note_copy = snap
            .notice
            .clone()
            .unwrap_or_else(|| SharedString::from(format!("Up to {} files", self.max_files)));
        let drop_copy = SharedString::from("Drop to upload");

        // File rows.
        let on_change_rows = self.on_items_change.clone();
        let row_els: Vec<AnyElement> = items
            .iter()
            .map(|item| {
                let st_remove = internal.clone();
                let st_retry = internal.clone();
                let cb_remove = on_change_rows.clone();
                let cb_retry = on_change_rows.clone();
                let item_id = item.id.clone();
                let item_id_retry = item.id.clone();
                let is_failed = item.status == Some(FileDropzoneStatus::Failed);
                let status_text = match item.status {
                    Some(FileDropzoneStatus::Uploading) => SharedString::from(format!(
                        "Uploading {}%",
                        item.progress.unwrap_or(0.0).round() as i64
                    )),
                    Some(FileDropzoneStatus::Uploaded) => SharedString::from("Uploaded"),
                    Some(FileDropzoneStatus::Failed) => {
                        item.error.clone().unwrap_or_else(|| "Upload failed".into())
                    }
                    None => SharedString::from(""),
                };
                let status_color = match item.status {
                    Some(FileDropzoneStatus::Uploaded) => colors.success,
                    Some(FileDropzoneStatus::Failed) => colors.danger,
                    _ => colors.text_muted,
                };
                let progress_pct = item.progress.unwrap_or(0.0).clamp(0.0, 100.0);
                let progress_bar = match item.status {
                    Some(FileDropzoneStatus::Uploading) => Some(
                        div()
                            .w_full()
                            .mt(px(4.0))
                            .h(px(3.0))
                            .rounded_full()
                            .overflow_hidden()
                            .bg(colors.control_track)
                            .child(
                                gpui_kit::canvas(
                                    |_, _, _| {},
                                    move |bounds, _, window, _| {
                                        let w = f32::from(bounds.size.width)
                                            * (progress_pct / 100.0).clamp(0.0, 1.0);
                                        if w > 0.5 {
                                            window.paint_quad(gpui_kit::fill(
                                                gpui_kit::Bounds::new(
                                                    bounds.origin,
                                                    gpui_kit::size(px(w), bounds.size.height),
                                                ),
                                                colors.control_fill,
                                            ));
                                        }
                                    },
                                )
                                .size_full(),
                            ),
                    ),
                    _ => None,
                };
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("row-{}", item.id)),
                    ))
                    .test_support()
                    .role(Role::ListItem)
                    .aria_label(item.name.clone())
                    .w_full()
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(8.0))
                    .py(px(6.0))
                    .border_b_1()
                    .border_color(colors.border_subtle)
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .min_w_0()
                            .flex_1()
                            .child(
                                div()
                                    .text_size(Typography::TEXT_SM)
                                    .font_medium()
                                    .text_color(colors.foreground)
                                    .truncate()
                                    .child(item.name.clone()),
                            )
                            .child(
                                div()
                                    .flex()
                                    .flex_row()
                                    .items_center()
                                    .gap(px(4.0))
                                    .text_size(Typography::TEXT_XS)
                                    .text_color(colors.text_muted)
                                    .child(SharedString::from(format_file_size(item.size)))
                                    .when(!status_text.is_empty(), |this| {
                                        this.child(SharedString::from("·")).child(
                                            div().text_color(status_color).child(status_text),
                                        )
                                    }),
                            )
                            .when_some(progress_bar, |this, bar| this.child(bar)),
                    )
                    .when(is_failed, |this| {
                        this.child(
                            BaseButton::new(ElementId::NamedChild(
                                self.id.clone().into(),
                                SharedString::from(format!("retry-{}", item.id)),
                            ))
                            .accessibility_label(SharedString::from(format!("Retry {}", item.name)))
                            .on_click(move |_, window, cx| {
                                let mut latest = Vec::new();
                                st_retry.update(cx, |s, _| {
                                    if let Some(target) =
                                        s.items.iter_mut().find(|it| it.id == item_id_retry)
                                    {
                                        target.status = Some(FileDropzoneStatus::Uploading);
                                        target.progress = Some(4.0);
                                        target.error = None;
                                    }
                                    s.seen_external = s.items.clone();
                                    latest = s.items.clone();
                                });
                                if let Some(ref cb) = cb_retry {
                                    cb(&latest, window, cx);
                                }
                                window.refresh();
                            })
                            .h(px(22.0))
                            .px(px(8.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .rounded(px(6.0))
                            .bg(colors.surface_muted)
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.foreground)
                            .cursor_pointer()
                            .child(SharedString::from("Retry")),
                        )
                    })
                    .child(
                        BaseButton::new(ElementId::NamedChild(
                            self.id.clone().into(),
                            SharedString::from(format!("remove-{}", item.id)),
                        ))
                        .accessibility_label(SharedString::from(format!("Remove {}", item.name)))
                        .on_click(move |_, window, cx| {
                            let mut latest = Vec::new();
                            st_remove.update(cx, |s, _| {
                                s.items.retain(|it| it.id != item_id);
                                s.seen_external = s.items.clone();
                                s.notice = None;
                                latest = s.items.clone();
                            });
                            if let Some(ref cb) = cb_remove {
                                cb(&latest, window, cx);
                            }
                            window.refresh();
                        })
                        .w(px(22.0))
                        .h(px(22.0))
                        .flex()
                        .items_center()
                        .justify_center()
                        .rounded(px(6.0))
                        .cursor_pointer()
                        .text_color(colors.text_muted)
                        .hover(move |s| s.bg(colors.surface_muted))
                        .child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .child(SharedString::from("×")),
                        ),
                    )
                    .into_any_element()
            })
            .collect();

        let st_drop_click = internal.clone();
        let st_drop_ext = internal.clone();
        let max_files = self.max_files;
        let max_size = self.max_size;
        let sim_upload = self.simulate_upload;
        let disabled_drop = self.disabled;
        let on_change_drop = self.on_items_change.clone();
        let on_change_ext = self.on_items_change.clone();

        div()
            .id(self.id.clone())
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .child(
                // Drop target.
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "dropzone".into(),
                    ))
                    .test_support()
                    .role(Role::Button)
                    .aria_label(self.label.clone())
                    .w_full()
                    .h(if compact { px(56.0) } else { px(120.0) })
                    .flex()
                    .flex_col()
                    .items_center()
                    .justify_center()
                    .gap(px(6.0))
                    .rounded(Radii::PANEL)
                    .border_1()
                    .border_color(if dragging {
                        colors.control_fill
                    } else {
                        colors.border
                    })
                    .bg(if dragging {
                        oklab_mix(colors.control_fill, colors.surface, 0.06)
                    } else {
                        colors.surface
                    })
                    .when(!self.disabled, |this| {
                        this.cursor_pointer()
                            .hover(move |s| s.bg(colors.surface_muted))
                            .can_drop(|payload, _, _| payload.is::<ExternalPaths>())
                            .drag_over::<ExternalPaths>(move |style, _, _, _| {
                                style.border_color(colors.control_fill).bg(oklab_mix(
                                    colors.control_fill,
                                    colors.surface,
                                    0.06,
                                ))
                            })
                            .on_drop(move |paths: &ExternalPaths, window, cx| {
                                if disabled_drop {
                                    return;
                                }
                                let mut updated: Option<Vec<FileDropzoneItem>> = None;
                                st_drop_ext.update(cx, |s, _| {
                                    s.dragging = false;
                                    let incoming = items_from_os_paths(
                                        paths.paths(),
                                        &mut s.next_file_id,
                                        max_size,
                                        sim_upload,
                                    );
                                    if incoming.is_empty() {
                                        return;
                                    }
                                    match file_dropzone_add(
                                        &s.items,
                                        &incoming,
                                        max_files,
                                        max_files > 1,
                                    ) {
                                        Ok(next) => {
                                            s.items = next.clone();
                                            s.seen_external = next.clone();
                                            s.notice = None;
                                            updated = Some(next);
                                        }
                                        Err(err) => {
                                            s.notice = Some(err);
                                        }
                                    }
                                });
                                if let Some(list) = updated
                                    && let Some(ref cb) = on_change_ext
                                {
                                    cb(&list, window, cx);
                                }
                                window.refresh();
                            })
                            .on_click(move |_, window, cx| {
                                if disabled_drop {
                                    return;
                                }
                                let rx = cx.prompt_for_paths(PathPromptOptions {
                                    files: true,
                                    directories: false,
                                    multiple: max_files > 1,
                                    prompt: None,
                                });
                                let st_picked = st_drop_click.clone();
                                let cb_picked = on_change_drop.clone();
                                window
                                    .spawn(cx, async move |cx| {
                                        let Ok(Ok(Some(paths))) = rx.await else {
                                            return;
                                        };
                                        let _ = cx.update(|window, cx| {
                                            let mut updated: Option<Vec<FileDropzoneItem>> = None;
                                            st_picked.update(cx, |s, _| {
                                                let incoming = items_from_os_paths(
                                                    &paths,
                                                    &mut s.next_file_id,
                                                    max_size,
                                                    sim_upload,
                                                );
                                                if incoming.is_empty() {
                                                    return;
                                                }
                                                match file_dropzone_add(
                                                    &s.items,
                                                    &incoming,
                                                    max_files,
                                                    max_files > 1,
                                                ) {
                                                    Ok(next) => {
                                                        s.items = next.clone();
                                                        s.seen_external = next.clone();
                                                        s.notice = None;
                                                        updated = Some(next);
                                                    }
                                                    Err(err) => {
                                                        s.notice = Some(err);
                                                    }
                                                }
                                            });
                                            if let Some(list) = updated
                                                && let Some(ref cb) = cb_picked
                                            {
                                                cb(&list, window, cx);
                                            }
                                            window.refresh();
                                        });
                                    })
                                    .detach();
                            })
                    })
                    .child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .font_medium()
                            .text_color(colors.foreground)
                            .child(if dragging {
                                drop_copy.clone()
                            } else {
                                self.label.clone()
                            }),
                    )
                    .child(
                        div()
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(self.description.clone()),
                    )
                    .child(
                        div()
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(note_copy),
                    ),
            )
            .child(div().flex().flex_col().children(row_els))
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    struct DropzoneHost {
        events: Rc<RefCell<Vec<String>>>,
    }

    impl Render for DropzoneHost {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            let _ = &self.events;
            div().w(px(480.0)).p(px(16.0)).child(
                FileDropzone::new("dropzone-test")
                    .label("Add files")
                    .max_files(5)
                    .items(vec![
                        FileDropzoneItem::new("f1", "spec.pdf", 1024 * 512)
                            .status(FileDropzoneStatus::Uploaded),
                        FileDropzoneItem::new("f2", "model.bin", 1024 * 1024 * 3)
                            .status(FileDropzoneStatus::Uploading)
                            .progress(45.0),
                        FileDropzoneItem::new("f3", "dump.zip", 1024 * 1024 * 12)
                            .status(FileDropzoneStatus::Failed)
                            .error("Server unreachable"),
                    ]),
            )
        }
    }

    fn dropzone_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("dropzone-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn dropzone_renders_rows_and_statuses(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = DropzoneHost {
            events: Rc::new(RefCell::new(Vec::new())),
        };
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            let zone = window.find(dropzone_element("dropzone"));
            assert_eq!(zone.role(), Some(Role::Button));
            for id in ["f1", "f2", "f3"] {
                let row = window.find(dropzone_element(&format!("row-{id}")));
                assert_eq!(row.role(), Some(Role::ListItem));
            }
        });
    }

    #[gpui_kit::test]
    fn dropzone_rows_expose_file_names(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = DropzoneHost {
            events: Rc::new(RefCell::new(Vec::new())),
        };
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            let row = window.find(dropzone_element("row-f1"));
            assert_eq!(row.role(), Some(Role::ListItem));
            let row2 = window.find(dropzone_element("row-f3"));
            assert_eq!(row2.role(), Some(Role::ListItem));
        });
    }

    #[gpui_kit::test]
    fn dropzone_reduced_motion_renders(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });

        let host = DropzoneHost {
            events: Rc::new(RefCell::new(Vec::new())),
        };
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            assert!(window.try_find(dropzone_element("row-f1")).is_some());
        });
    }

    #[test]
    fn file_dropzone_add_filters_and_caps() {
        let existing = vec![FileDropzoneItem::new("f1", "a.pdf", 100)];
        let incoming = vec![
            FileDropzoneItem::new("f2", "b.pdf", 200),
            FileDropzoneItem::new("f3", "a.pdf", 100), // duplicate name
            FileDropzoneItem::new("f4", "c.pdf", 300),
        ];
        let next = file_dropzone_add(&existing, &incoming, 4, true).unwrap();
        assert_eq!(next.len(), 3);
        assert!(next.iter().all(|i| i.name != "a.pdf" || i.id == "f1"));

        // Single-file mode replaces.
        let next = file_dropzone_add(&existing, &incoming[..1], 5, false).unwrap();
        assert_eq!(next.len(), 1);
        assert_eq!(next[0].name, "b.pdf");

        // Over the cap: an error.
        let err = file_dropzone_add(&existing, &incoming, 2, true).unwrap_err();
        assert_eq!(err, "You can add up to 2 files.");
    }

    #[test]
    fn format_file_size_units() {
        assert_eq!(format_file_size(512), "512 B");
        assert_eq!(format_file_size(1024), "1 KB");
        assert_eq!(format_file_size(1024 * 512), "512 KB");
        assert_eq!(format_file_size(1024 * 1024 * 3), "3.0 MB");
        assert_eq!(format_file_size((1024.0 * 1024.0 * 3.2) as u64), "3.2 MB");
    }
}