1use gpui_base::LogicalStyledExt as _;
2use std::{rc::Rc, time::Duration};
3
4use gpui::{
5 AbsoluteLength, AnyElement, App, Axis, Bounds, ClickEvent, ElementId, Hsla, ImageSource,
6 InteractiveElement as _, IntoElement, MouseButton, ObjectFit, ParentElement, Path, PathBuilder,
7 Pixels, Refineable as _, RenderOnce, ScrollHandle, SharedString,
8 StatefulInteractiveElement as _, StyleRefinement, Styled, StyledImage as _, Window, black,
9 canvas, div, img, linear_color_stop, linear_gradient, point, prelude::FluentBuilder as _, px,
10 relative, rems, white,
11};
12use gpui_base::{
13 is_mobile,
14 motion::{Transition, transition},
15};
16use rust_i18n::t;
17
18use crate::{
19 ActiveTheme as _, Icon, IconName, InteractiveElementExt as _, Sizable, Size, StyledExt as _,
20 button::{Button, ButtonCustomVariant, ButtonVariants as _},
21 h_flex,
22 progress::ProgressCircle,
23 scroll::ScrollableMask,
24 shimmer::{ShimmerStyle, ShimmerText},
25 spinner::Spinner,
26 tooltip::Tooltip,
27 v_flex,
28};
29
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub enum AttachmentStatus {
33 Pending,
35 Uploading,
37 Processing,
39 Failed,
41 #[default]
43 Complete,
44}
45
46impl AttachmentStatus {
47 pub fn is_pending(self) -> bool {
49 matches!(self, Self::Pending)
50 }
51
52 pub fn is_uploading(self) -> bool {
54 matches!(self, Self::Uploading)
55 }
56
57 pub fn is_processing(self) -> bool {
59 matches!(self, Self::Processing)
60 }
61
62 pub fn is_failed(self) -> bool {
64 matches!(self, Self::Failed)
65 }
66
67 pub fn is_complete(self) -> bool {
69 matches!(self, Self::Complete)
70 }
71
72 pub fn is_in_progress(self) -> bool {
74 matches!(self, Self::Uploading | Self::Processing)
75 }
76}
77
78type ControlHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
80
81type Control = (ElementId, ControlHandler);
83
84#[derive(Clone)]
86struct SlotLayout {
87 size: Size,
88 status: AttachmentStatus,
89 axis: Axis,
90 flush: bool,
92 retry: Option<Control>,
94 progress: Option<f32>,
96 id: Option<ElementId>,
98}
99
100const REMOVE_OVERHANG: Pixels = px(6.);
102const REMOVE_BUTTON_SIZE: Pixels = px(20.);
104const RETRY_BUTTON_SIZE: Pixels = px(24.);
106const REMOVE_GROUP: &str = "attachment-remove";
109const PROGRESS_SCRIM: f32 = 0.35;
111const FAILED_SCRIM: f32 = 0.55;
113
114struct CardMetrics {
116 height: AbsoluteLength,
118 chip_width: AbsoluteLength,
120 media: AbsoluteLength,
122 media_glyph: AbsoluteLength,
125 padding_start: AbsoluteLength,
127 padding_end: AbsoluteLength,
129 card_padding: AbsoluteLength,
131 gap: AbsoluteLength,
132 text: AbsoluteLength,
133 description: AbsoluteLength,
134}
135
136fn card_metrics(size: Size) -> CardMetrics {
137 let r = |value: f32| AbsoluteLength::Rems(rems(value));
138 match size {
139 Size::XSmall => CardMetrics {
140 height: r(2.5),
141 chip_width: r(11.),
142 media: r(1.75),
143 media_glyph: r(0.875),
144 padding_start: r(0.25),
145 padding_end: r(0.375),
146 card_padding: r(0.25),
147 gap: r(0.375),
148 text: r(0.6875),
149 description: r(0.625),
150 },
151 Size::Small => CardMetrics {
152 height: r(3.),
153 chip_width: r(12.5),
154 media: r(2.),
155 media_glyph: r(1.),
156 padding_start: r(0.375),
157 padding_end: r(0.5),
158 card_padding: r(0.375),
159 gap: r(0.5),
160 text: r(0.75),
161 description: r(0.6875),
162 },
163 Size::Medium => CardMetrics {
164 height: r(3.5),
165 chip_width: r(14.5),
166 media: r(2.375),
167 media_glyph: r(1.25),
168 padding_start: r(0.5),
169 padding_end: r(0.75),
170 card_padding: r(0.5),
171 gap: r(0.625),
172 text: r(0.8125),
173 description: r(0.75),
174 },
175 Size::Large => CardMetrics {
176 height: r(4.),
177 chip_width: r(17.),
178 media: r(2.75),
179 media_glyph: r(1.5),
180 padding_start: r(0.625),
181 padding_end: r(1.),
182 card_padding: r(0.75),
183 gap: r(0.75),
184 text: r(0.875),
185 description: r(0.8125),
186 },
187 Size::Size(value) => CardMetrics {
189 height: (value * 3.5).into(),
190 chip_width: (value * 14.5).into(),
191 media: (value * 2.375).into(),
192 media_glyph: (value * 1.25).into(),
193 padding_start: (value * 0.5).into(),
194 padding_end: (value * 0.75).into(),
195 card_padding: (value * 0.5).into(),
196 gap: (value * 0.625).into(),
197 text: (value * 0.8125).into(),
198 description: (value * 0.75).into(),
199 },
200 }
201}
202
203fn card_radius(size: Size, cx: &App) -> Pixels {
205 let tokens = cx.theme().semantic_tokens();
206 if size == Size::XSmall {
207 tokens.radius.md
208 } else {
209 tokens.radius.lg
210 }
211}
212
213#[derive(IntoElement)]
215pub struct Attachment {
216 id: Option<ElementId>,
217 style: StyleRefinement,
218 status: AttachmentStatus,
219 size: Size,
220 axis: Axis,
221 media: Option<AttachmentMedia>,
222 content: Option<AttachmentContent>,
223 actions: Option<AttachmentActions>,
224 on_click: Option<ControlHandler>,
225 on_remove: Option<ControlHandler>,
226 on_retry: Option<ControlHandler>,
227 progress: Option<f32>,
228 tooltip: Option<SharedString>,
229}
230
231impl Attachment {
232 pub fn new() -> Self {
234 Self {
235 id: None,
236 style: StyleRefinement::default(),
237 status: AttachmentStatus::Complete,
238 size: Size::Medium,
239 axis: Axis::Horizontal,
240 media: None,
241 content: None,
242 actions: None,
243 on_click: None,
244 on_remove: None,
245 on_retry: None,
246 progress: None,
247 tooltip: None,
248 }
249 }
250
251 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
254 self.id = Some(id.into());
255 self
256 }
257
258 pub fn on_click(
264 mut self,
265 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
266 ) -> Self {
267 self.on_click = Some(Rc::new(handler));
268 self
269 }
270
271 pub fn on_remove(
277 mut self,
278 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
279 ) -> Self {
280 self.on_remove = Some(Rc::new(handler));
281 self
282 }
283
284 pub fn on_retry(
288 mut self,
289 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
290 ) -> Self {
291 self.on_retry = Some(Rc::new(handler));
292 self
293 }
294
295 pub fn progress(mut self, percent: f32) -> Self {
301 self.progress = Some(percent.clamp(0., 100.));
302 self
303 }
304
305 pub fn tooltip(mut self, text: impl Into<SharedString>) -> Self {
308 self.tooltip = Some(text.into());
309 self
310 }
311
312 pub fn status(mut self, status: AttachmentStatus) -> Self {
314 self.status = status;
315 self
316 }
317
318 pub fn axis(mut self, axis: Axis) -> Self {
320 self.axis = axis;
321 self
322 }
323
324 pub fn media(mut self, media: AttachmentMedia) -> Self {
326 self.media = Some(media);
327 self
328 }
329
330 pub fn content(mut self, content: AttachmentContent) -> Self {
332 self.content = Some(content);
333 self
334 }
335
336 pub fn actions(mut self, actions: AttachmentActions) -> Self {
338 self.actions = Some(actions);
339 self
340 }
341}
342
343impl Default for Attachment {
344 fn default() -> Self {
345 Self::new()
346 }
347}
348
349impl Sizable for Attachment {
350 fn with_size(mut self, size: impl Into<Size>) -> Self {
351 self.size = size.into();
352 self
353 }
354}
355
356impl Styled for Attachment {
357 fn style(&mut self) -> &mut StyleRefinement {
358 &mut self.style
359 }
360}
361
362impl Attachment {
363 fn retry_control(&self) -> Option<Control> {
366 if !self.status.is_failed() {
367 return None;
368 }
369 Some((self.id.clone()?, self.on_retry.clone()?))
370 }
371
372 fn layout_slots(&mut self) {
373 let layout = SlotLayout {
374 size: self.size,
375 status: self.status,
376 axis: self.axis,
377 flush: self.axis == Axis::Vertical && self.content.is_none(),
380 retry: self.retry_control(),
381 progress: self.progress.filter(|_| self.status.is_uploading()),
384 id: self.id.clone(),
385 };
386
387 self.media = self.media.take().map(|media| media.layout(layout.clone()));
388 self.content = self
389 .content
390 .take()
391 .map(|content| content.layout(layout.clone()));
392 self.actions = self
393 .actions
394 .take()
395 .map(|actions| actions.layout_for_axis(layout.axis));
396 }
397}
398
399impl RenderOnce for Attachment {
400 fn render(mut self, _: &mut Window, cx: &mut App) -> impl IntoElement {
401 let tokens = cx.theme().semantic_tokens();
402 let size = self.size;
403 let axis = self.axis;
404 let status = self.status;
405 let has_media = self.media.is_some();
406 let has_content = self.content.is_some();
407 let clickable = self.id.is_some() && self.on_click.is_some();
408 let remove = self.id.clone().zip(self.on_remove.take());
409 let tooltip = self.id.clone().zip(self.tooltip.take());
410 let progress_bar = self
411 .progress
412 .filter(|_| status.is_uploading() && axis == Axis::Horizontal);
413 let metrics = card_metrics(size);
414 let radius = card_radius(size, cx);
415 let flush = axis == Axis::Vertical && !has_content;
416
417 self.layout_slots();
418
419 let card = div()
420 .relative()
421 .flex_row_dir(cx)
422 .flex_none()
423 .max_w_full()
424 .min_w_0()
425 .rounded(radius)
426 .border_1()
427 .border_color(if status.is_failed() {
428 tokens.colors.destructive
429 } else {
430 tokens.colors.border
431 })
432 .when(status.is_pending(), |this| this.border_dashed())
433 .bg(tokens.colors.background)
434 .text_color(tokens.colors.foreground)
435 .hover(move |style| {
438 if clickable {
439 style.bg(tokens.colors.muted.opacity(0.5))
440 } else {
441 style
442 }
443 })
444 .line_height(relative(1.25))
445 .text_size(metrics.text)
446 .map(|this| match axis {
447 Axis::Horizontal => this
450 .items_center()
451 .h(metrics.height)
452 .gap(metrics.gap)
453 .ps(metrics.padding_start, cx)
454 .pe(metrics.padding_end, cx)
455 .when(has_content, |this| this.w(metrics.chip_width))
456 .when(!has_content && !has_media, |this| {
457 this.ps(metrics.padding_end, cx)
458 }),
459 Axis::Vertical if flush => this.size(metrics.height),
461 Axis::Vertical => this
463 .w(rems(7.5))
464 .flex_col()
465 .items_start()
466 .gap(metrics.gap)
467 .p(metrics.card_padding),
468 })
469 .when_some(self.media, |this, media| this.child(media))
470 .when_some(self.content, |this, content| this.child(content))
471 .when_some(progress_bar, |this, percent| {
474 this.child(upload_bar(percent, radius, tokens.colors.primary))
475 })
476 .when_some(self.id.zip(self.on_click), |this, (id, on_click)| {
477 this.child(
480 div()
481 .id(id)
482 .absolute()
483 .inset_0()
484 .on_click(move |event, window, cx| on_click(event, window, cx)),
485 )
486 })
487 .when_some(self.actions, |this, actions| this.child(actions))
488 .refine_style(&self.style);
489 let card = match tooltip {
490 Some((id, text)) => card
491 .id((id, "card"))
492 .tooltip(move |window, cx| Tooltip::new(text.clone()).build(window, cx))
493 .into_any_element(),
494 None => card.into_any_element(),
495 };
496
497 let Some((id, on_remove)) = remove else {
498 return card;
499 };
500 div()
503 .relative()
504 .flex_none()
505 .max_w_full()
506 .min_w_0()
507 .group(REMOVE_GROUP)
508 .pt(REMOVE_OVERHANG)
509 .pe(REMOVE_OVERHANG, cx)
510 .child(card)
511 .child(
512 div()
513 .absolute()
514 .top_0()
515 .inset_e(px(0.), cx)
516 .when(!is_mobile(), |this| {
517 this.invisible()
518 .group_hover(REMOVE_GROUP, |this| this.visible())
519 })
520 .child(remove_button(id, on_remove, cx)),
521 )
522 .into_any_element()
523 }
524}
525
526const UPLOAD_BAR_THICKNESS: f32 = 2.;
528const CARD_BORDER: f32 = 1.;
530
531fn upload_bar(percent: f32, radius: Pixels, color: Hsla) -> impl IntoElement {
535 canvas(
536 |_: Bounds<Pixels>, _: &mut Window, _: &mut App| (),
537 move |bounds: Bounds<Pixels>, _: (), window: &mut Window, _: &mut App| {
538 if let Some(path) = upload_bar_path(bounds, percent, radius) {
539 window.paint_path(path, color);
540 }
541 },
542 )
543 .absolute()
544 .inset_0()
545}
546
547fn upload_bar_path(bounds: Bounds<Pixels>, percent: f32, radius: Pixels) -> Option<Path<Pixels>> {
552 const STEPS: usize = 6;
553 let width = bounds.size.width.as_f32();
554 let height = bounds.size.height.as_f32();
555 let radius = (radius.as_f32() - CARD_BORDER).clamp(0., width.min(height) / 2.);
556 let inner_left = 0.;
557 let inner_right = width;
558 let inner_bottom = height;
559 let top = inner_bottom - UPLOAD_BAR_THICKNESS;
560 let end = inner_left + (inner_right - inner_left) * (percent / 100.).clamp(0., 1.);
561 if end <= inner_left || top <= 0. {
562 return None;
563 }
564 let centre_y = inner_bottom - radius;
566 let arc_dx = |y: f32| {
567 if radius > 0. && y > centre_y {
568 (radius * radius - (y - centre_y) * (y - centre_y))
569 .max(0.)
570 .sqrt()
571 } else {
572 radius
573 }
574 };
575 let left_at = |y: f32| inner_left + radius - arc_dx(y);
576 let right_at = |y: f32| (inner_right - radius + arc_dx(y)).min(end);
577 let at = |x: f32, y: f32| point(bounds.origin.x + px(x), bounds.origin.y + px(y));
578 let rows = (0..=STEPS).map(|i| top + UPLOAD_BAR_THICKNESS * i as f32 / STEPS as f32);
579
580 let mut builder = PathBuilder::fill();
581 builder.move_to(at(left_at(top), top));
582 for y in rows.clone() {
584 builder.line_to(at(right_at(y), y));
585 }
586 for y in rows.rev() {
587 builder.line_to(at(left_at(y), y));
588 }
589 builder.build().ok()
590}
591
592fn remove_button(id: ElementId, on_remove: ControlHandler, cx: &App) -> Button {
598 let tokens = cx.theme().semantic_tokens();
599 Button::new((id, "remove"))
600 .custom(
603 ButtonCustomVariant::new(cx)
604 .hover(tokens.colors.muted)
605 .active(tokens.colors.muted)
606 .foreground(tokens.colors.foreground),
607 )
608 .accessibility_label(t!("Attachment.Remove"))
609 .child(
610 Icon::new(IconName::Close)
611 .size(px(10.))
612 .text_color(tokens.colors.foreground),
613 )
614 .size(REMOVE_BUTTON_SIZE)
615 .p_0()
616 .rounded(cx.theme().radius_full())
617 .bg(tokens.colors.background)
618 .border_1()
619 .border_color(tokens.colors.border)
620 .shadow_sm()
621 .on_click(move |event, window, cx| on_remove(event, window, cx))
622}
623
624fn retry_button(id: ElementId, on_retry: ControlHandler, cx: &App) -> Button {
627 let tokens = cx.theme().semantic_tokens();
628 Button::new((id, "retry"))
629 .ghost()
630 .accessibility_label(t!("Attachment.Retry"))
631 .child(
632 Icon::new(IconName::RefreshCw)
633 .size(px(12.))
634 .text_color(tokens.colors.destructive),
635 )
636 .size(RETRY_BUTTON_SIZE)
637 .p_0()
638 .rounded(cx.theme().radius_full())
639 .bg(tokens.colors.background)
640 .shadow_sm()
641 .on_click(move |event, window, cx| on_retry(event, window, cx))
642}
643
644#[derive(IntoElement)]
649pub struct AttachmentMedia {
650 style: StyleRefinement,
651 size: Option<Size>,
652 status: AttachmentStatus,
653 axis: Axis,
654 flush: bool,
656 retry: Option<Control>,
657 progress: Option<f32>,
659 id: Option<ElementId>,
661 source: Option<ImageSource>,
662 children: Vec<AnyElement>,
663 overlays: Vec<AnyElement>,
664}
665
666impl AttachmentMedia {
667 pub fn new() -> Self {
669 Self {
670 style: StyleRefinement::default(),
671 size: None,
672 status: AttachmentStatus::Complete,
673 axis: Axis::Horizontal,
674 flush: false,
675 retry: None,
676 progress: None,
677 id: None,
678 source: None,
679 children: Vec::new(),
680 overlays: Vec::new(),
681 }
682 }
683
684 pub fn src(mut self, source: impl Into<ImageSource>) -> Self {
686 self.source = Some(source.into());
687 self
688 }
689
690 pub fn overlay(mut self, overlay: impl IntoElement) -> Self {
692 self.overlays.push(
693 div()
694 .absolute()
695 .inset_0()
696 .flex()
697 .items_center()
698 .justify_center()
699 .child(overlay)
700 .into_any_element(),
701 );
702 self
703 }
704
705 fn layout(mut self, layout: SlotLayout) -> Self {
706 if self.size.is_none() {
707 self.size = Some(layout.size);
708 }
709 self.status = layout.status;
710 self.axis = layout.axis;
711 self.flush = layout.flush;
712 self.retry = layout.retry;
713 self.progress = layout.progress;
714 self.id = layout.id;
715 self
716 }
717}
718
719impl Default for AttachmentMedia {
720 fn default() -> Self {
721 Self::new()
722 }
723}
724
725impl ParentElement for AttachmentMedia {
726 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
727 self.children.extend(elements);
728 }
729}
730
731impl Sizable for AttachmentMedia {
732 fn with_size(mut self, size: impl Into<Size>) -> Self {
733 self.size = Some(size.into());
734 self
735 }
736}
737
738impl Styled for AttachmentMedia {
739 fn style(&mut self) -> &mut StyleRefinement {
740 &mut self.style
741 }
742}
743
744impl RenderOnce for AttachmentMedia {
745 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
746 let tokens = cx.theme().semantic_tokens();
747 let resolved_size = self.size.unwrap_or_default();
748 let metrics = card_metrics(resolved_size);
749 let radius = if self.flush {
752 (card_radius(resolved_size, cx) - px(1.)).max(px(0.))
753 } else if resolved_size == Size::XSmall {
754 tokens.radius.sm
755 } else {
756 tokens.radius.md
757 };
758 let glyph_size = metrics.media_glyph;
759 let spinner_size = if resolved_size == Size::XSmall {
760 Size::XSmall
761 } else {
762 Size::Small
763 };
764 let ring_size = if resolved_size == Size::XSmall {
765 px(14.)
766 } else {
767 px(20.)
768 };
769 let status = self.status;
770 let source = self.source;
771 let has_source = source.is_some();
772 let failed_media = status.is_failed() && !has_source;
773 let corner_radii = self.style.corner_radii.clone();
774 let image_id: ElementId = match self.id.clone() {
775 Some(id) => (id, "image").into(),
776 None => "attachment-image".into(),
777 };
778 let ring_id: ElementId = match self.id {
779 Some(id) => (id, "progress").into(),
780 None => "attachment-progress".into(),
781 };
782 let busy = |color: Hsla| -> AnyElement {
785 match self.progress {
786 Some(percent) => ProgressCircle::new(ring_id.clone())
787 .value(percent)
788 .color(color)
789 .size(ring_size)
790 .into_any_element(),
791 None => Spinner::new()
792 .with_size(spinner_size)
793 .color(color)
794 .into_any_element(),
795 }
796 };
797 let glyph = if has_source {
800 None
801 } else if status.is_in_progress() {
802 Some(busy(tokens.colors.primary))
803 } else if status.is_failed() {
804 Some(match self.retry.clone() {
805 Some((id, on_retry)) => retry_button(id, on_retry, cx).into_any_element(),
806 None => Icon::new(IconName::Ban).size(glyph_size).into_any_element(),
807 })
808 } else {
809 None
810 };
811 let scrim = if !has_source {
814 None
815 } else if status.is_in_progress() {
816 Some((PROGRESS_SCRIM, busy(white())))
817 } else if status.is_failed() {
818 let control = match self.retry {
819 Some((id, on_retry)) => retry_button(id, on_retry, cx).into_any_element(),
820 None => Icon::new(IconName::Ban)
821 .size(glyph_size)
822 .text_color(white())
823 .into_any_element(),
824 };
825 Some((FAILED_SCRIM, control))
826 } else {
827 None
828 };
829
830 div()
831 .relative()
832 .flex()
833 .flex_shrink_0()
834 .items_center()
835 .justify_center()
836 .overflow_hidden()
837 .when(self.axis == Axis::Horizontal, |this| {
838 this.size(metrics.media)
839 })
840 .text_size(glyph_size)
842 .when(self.axis == Axis::Vertical, |this| {
843 this.w_full().aspect_ratio(1.)
844 })
845 .rounded(radius)
846 .bg(if failed_media {
847 tokens.colors.destructive.opacity(0.1)
848 } else {
849 tokens.colors.muted
850 })
851 .text_color(if failed_media {
852 tokens.colors.destructive
853 } else {
854 tokens.colors.foreground
855 })
856 .when_some(source, |this, source| {
857 let mut image = img(source)
863 .id(image_id)
864 .absolute()
865 .inset_0()
866 .size_full()
867 .rounded(radius)
868 .object_fit(ObjectFit::Cover);
869 image.style().corner_radii.refine(&corner_radii);
870 this.child(image)
871 })
872 .map(|this| match glyph {
873 Some(glyph) => this.child(glyph),
874 None => this.children(self.children),
875 })
876 .when_some(scrim, |this, (opacity, control)| {
877 let mut scrim = div()
880 .absolute()
881 .inset_0()
882 .flex()
883 .items_center()
884 .justify_center()
885 .rounded(radius)
886 .bg(black().opacity(opacity))
887 .child(control);
888 scrim.style().corner_radii.refine(&corner_radii);
889 this.child(scrim)
890 })
891 .children(self.overlays)
892 .refine_style(&self.style)
893 }
894}
895
896#[derive(IntoElement)]
898pub struct AttachmentContent {
899 style: StyleRefinement,
900 vertical_layout: bool,
901 status: AttachmentStatus,
902 retry: Option<Control>,
903 progress: Option<f32>,
904 children: Vec<AttachmentContentChild>,
905}
906
907enum AttachmentContentChild {
908 Title(AttachmentTitle),
909 Description(AttachmentDescription),
910 Element(AnyElement),
911}
912
913impl AttachmentContent {
914 pub fn new() -> Self {
916 Self {
917 style: StyleRefinement::default(),
918 vertical_layout: false,
919 status: AttachmentStatus::Complete,
920 retry: None,
921 progress: None,
922 children: Vec::new(),
923 }
924 }
925
926 pub fn title(mut self, title: AttachmentTitle) -> Self {
928 self.children.push(AttachmentContentChild::Title(title));
929 self
930 }
931
932 pub fn description(mut self, description: AttachmentDescription) -> Self {
934 self.children
935 .push(AttachmentContentChild::Description(description));
936 self
937 }
938
939 fn layout(mut self, layout: SlotLayout) -> Self {
940 let SlotLayout {
941 size,
942 status,
943 axis,
944 retry,
945 progress,
946 ..
947 } = layout;
948 self.vertical_layout = axis == Axis::Vertical;
949 self.status = status;
950 self.retry = retry;
951 self.progress = progress;
952
953 for child in &mut self.children {
954 match child {
955 AttachmentContentChild::Title(title) => {
956 if title.status.is_none() {
957 title.status = Some(status);
958 }
959 }
960 AttachmentContentChild::Description(description) => {
961 if description.status.is_none() {
962 description.status = Some(status);
963 }
964 if description.size.is_none() {
965 description.size = Some(size);
966 }
967 }
968 AttachmentContentChild::Element(_) => {}
969 }
970 }
971
972 self
973 }
974}
975
976impl Default for AttachmentContent {
977 fn default() -> Self {
978 Self::new()
979 }
980}
981
982impl ParentElement for AttachmentContent {
983 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
984 self.children
985 .extend(elements.into_iter().map(AttachmentContentChild::Element));
986 }
987}
988
989impl Styled for AttachmentContent {
990 fn style(&mut self) -> &mut StyleRefinement {
991 &mut self.style
992 }
993}
994
995impl RenderOnce for AttachmentContent {
996 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
997 let tokens = cx.theme().semantic_tokens();
998 let mut retry = self.retry.filter(|_| self.status.is_failed());
1001 let progress = self.progress.filter(|_| self.status.is_uploading());
1002 v_flex()
1003 .max_w_full()
1004 .min_w_0()
1005 .flex_1()
1006 .gap_0p5()
1007 .line_height(relative(1.25))
1008 .when(self.vertical_layout, |this| this.w_full().px_1())
1009 .children(self.children.into_iter().map(|child| {
1010 match child {
1011 AttachmentContentChild::Title(title) => title.into_any_element(),
1012 AttachmentContentChild::Description(mut description) => match retry.take() {
1013 Some((id, on_retry)) => h_flex()
1014 .max_w_full()
1015 .min_w_0()
1016 .gap_1()
1017 .child(description)
1018 .child(
1019 div()
1020 .text_xs()
1021 .text_color(tokens.colors.muted_foreground)
1022 .child("·"),
1023 )
1024 .child(
1025 Button::new((id, "retry"))
1026 .link()
1027 .xsmall()
1028 .label(t!("Attachment.Retry"))
1029 .on_click(move |event, window, cx| on_retry(event, window, cx)),
1030 )
1031 .into_any_element(),
1032 None => {
1033 if let Some(percent) = progress {
1034 description.text =
1035 format!("{} · {}%", description.text, percent.round() as u32)
1036 .into();
1037 }
1038 description.into_any_element()
1039 }
1040 },
1041 AttachmentContentChild::Element(element) => element,
1042 }
1043 }))
1044 .refine_style(&self.style)
1045 }
1046}
1047
1048#[derive(IntoElement)]
1050pub struct AttachmentTitle {
1051 style: StyleRefinement,
1052 text: SharedString,
1053 status: Option<AttachmentStatus>,
1054 shimmer_style: Option<ShimmerStyle>,
1055}
1056
1057impl AttachmentTitle {
1058 pub fn new(text: impl Into<SharedString>) -> Self {
1060 Self {
1061 style: StyleRefinement::default(),
1062 text: text.into(),
1063 status: None,
1064 shimmer_style: None,
1065 }
1066 }
1067
1068 pub fn status(mut self, status: AttachmentStatus) -> Self {
1070 self.status = Some(status);
1071 self
1072 }
1073
1074 pub fn with_shimmer_style(mut self, style: ShimmerStyle) -> Self {
1076 self.shimmer_style = Some(style);
1077 self
1078 }
1079}
1080
1081impl Styled for AttachmentTitle {
1082 fn style(&mut self) -> &mut StyleRefinement {
1083 &mut self.style
1084 }
1085}
1086
1087impl RenderOnce for AttachmentTitle {
1088 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
1089 let loading = self.status.is_some_and(AttachmentStatus::is_in_progress);
1090
1091 div()
1092 .max_w_full()
1093 .min_w_0()
1094 .truncate()
1095 .font_medium()
1096 .map(|this| {
1097 if loading {
1098 this.child(
1099 ShimmerText::new(self.text).when_some(self.shimmer_style, |this, style| {
1100 this.with_shimmer_style(style)
1101 }),
1102 )
1103 } else {
1104 this.child(self.text)
1105 }
1106 })
1107 .refine_style(&self.style)
1108 }
1109}
1110
1111#[derive(IntoElement)]
1113pub struct AttachmentDescription {
1114 style: StyleRefinement,
1115 text: SharedString,
1116 status: Option<AttachmentStatus>,
1117 size: Option<Size>,
1119}
1120
1121impl AttachmentDescription {
1122 pub fn new(text: impl Into<SharedString>) -> Self {
1124 Self {
1125 style: StyleRefinement::default(),
1126 text: text.into(),
1127 status: None,
1128 size: None,
1129 }
1130 }
1131
1132 pub fn status(mut self, status: AttachmentStatus) -> Self {
1134 self.status = Some(status);
1135 self
1136 }
1137}
1138
1139impl Styled for AttachmentDescription {
1140 fn style(&mut self) -> &mut StyleRefinement {
1141 &mut self.style
1142 }
1143}
1144
1145impl RenderOnce for AttachmentDescription {
1146 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1147 let tokens = cx.theme().semantic_tokens();
1148 let color = self
1149 .status
1150 .is_some_and(AttachmentStatus::is_failed)
1151 .then_some(tokens.colors.destructive)
1152 .unwrap_or(tokens.colors.muted_foreground);
1153
1154 div()
1155 .max_w_full()
1156 .min_w_0()
1157 .truncate()
1158 .text_size(card_metrics(self.size.unwrap_or_default()).description)
1159 .line_height(relative(1.25))
1160 .text_color(color)
1161 .child(self.text)
1162 .refine_style(&self.style)
1163 }
1164}
1165
1166#[derive(IntoElement)]
1171pub struct AttachmentActions {
1172 style: StyleRefinement,
1173 vertical_layout: bool,
1174 children: Vec<AnyElement>,
1175}
1176
1177impl AttachmentActions {
1178 pub fn new() -> Self {
1180 Self {
1181 style: StyleRefinement::default(),
1182 vertical_layout: false,
1183 children: Vec::new(),
1184 }
1185 }
1186
1187 fn layout_for_axis(mut self, axis: Axis) -> Self {
1188 self.vertical_layout = axis == Axis::Vertical;
1189 self
1190 }
1191}
1192
1193impl Default for AttachmentActions {
1194 fn default() -> Self {
1195 Self::new()
1196 }
1197}
1198
1199impl ParentElement for AttachmentActions {
1200 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1201 self.children.extend(elements);
1202 }
1203}
1204
1205impl Styled for AttachmentActions {
1206 fn style(&mut self) -> &mut StyleRefinement {
1207 &mut self.style
1208 }
1209}
1210
1211impl RenderOnce for AttachmentActions {
1212 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1213 div()
1214 .relative()
1215 .flex_row_dir(cx)
1216 .flex_shrink_0()
1217 .items_center()
1218 .gap_1()
1219 .when(self.vertical_layout, |this| {
1220 this.absolute().top_3().inset_e(rems(0.75), cx)
1221 })
1222 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1228 .children(self.children)
1229 .refine_style(&self.style)
1230 }
1231}
1232
1233const EDGE_FADE_TRANSITION: Duration = Duration::from_millis(200);
1235
1236struct AttachmentGroupScroll {
1238 handle: ScrollHandle,
1239 primed: bool,
1242}
1243
1244#[derive(IntoElement)]
1246pub struct AttachmentGroup {
1247 id: ElementId,
1248 style: StyleRefinement,
1249 scroll_handle: Option<ScrollHandle>,
1250 edge_fade: Option<Hsla>,
1251 children: Vec<AnyElement>,
1252}
1253
1254impl AttachmentGroup {
1255 pub fn new(id: impl Into<ElementId>) -> Self {
1257 Self {
1258 id: id.into(),
1259 style: StyleRefinement::default(),
1260 scroll_handle: None,
1261 edge_fade: None,
1262 children: Vec::new(),
1263 }
1264 }
1265
1266 pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
1271 self.scroll_handle = Some(handle.clone());
1272 self
1273 }
1274
1275 pub fn with_edge_fade(mut self, color: impl Into<Hsla>) -> Self {
1281 self.edge_fade = Some(color.into());
1282 self
1283 }
1284}
1285
1286impl ParentElement for AttachmentGroup {
1287 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1288 self.children.extend(elements);
1289 }
1290}
1291
1292impl Styled for AttachmentGroup {
1293 fn style(&mut self) -> &mut StyleRefinement {
1294 &mut self.style
1295 }
1296}
1297
1298impl RenderOnce for AttachmentGroup {
1299 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1300 let id = self.id;
1301 let scroll =
1305 window.use_keyed_state((id.clone(), "scroll"), cx, |_, _| AttachmentGroupScroll {
1306 handle: ScrollHandle::new(),
1307 primed: false,
1308 });
1309 let handle = self
1310 .scroll_handle
1311 .unwrap_or_else(|| scroll.read(cx).handle.clone());
1312 let view_id = window.current_view();
1313
1314 let fades = self.edge_fade.map(|color| {
1315 if !scroll.read(cx).primed {
1316 scroll.update(cx, |scroll, _| scroll.primed = true);
1317 window.on_next_frame(move |_, cx| cx.notify(view_id));
1318 }
1319 let max = handle.max_offset().x;
1320 let offset = handle.offset().x;
1322 let scrollable = max > px(1.);
1323 let hides_leading = scrollable && offset < px(-1.);
1324 let hides_trailing = scrollable && offset > px(1.) - max;
1325 let leading = transition(
1326 (id.clone(), "leading-fade"),
1327 if hides_leading { 1. } else { 0. },
1328 Transition::new(EDGE_FADE_TRANSITION),
1329 window,
1330 cx,
1331 );
1332 let trailing = transition(
1333 (id.clone(), "trailing-fade"),
1334 if hides_trailing { 1. } else { 0. },
1335 Transition::new(EDGE_FADE_TRANSITION),
1336 window,
1337 cx,
1338 );
1339 (color, leading, trailing)
1340 });
1341
1342 let row = h_flex()
1343 .id(id)
1344 .w_full()
1345 .min_w_0()
1346 .gap_3()
1347 .py_1()
1348 .overflow_x_scroll()
1349 .lock_scroll_axis()
1350 .track_scroll(&handle)
1351 .when(fades.is_some(), |this| {
1353 this.on_scroll(move |_, _, cx| cx.notify(view_id))
1354 })
1355 .refine_style(&self.style)
1356 .children(self.children);
1357
1358 let fade = |color: Hsla, opacity: f32, leading: bool| {
1361 let (from, to) = if leading {
1362 (color, color.opacity(0.))
1363 } else {
1364 (color.opacity(0.), color)
1365 };
1366 div()
1367 .absolute()
1368 .top_0()
1369 .bottom_0()
1370 .when(leading, |this| this.left_0())
1371 .when(!leading, |this| this.right_0())
1372 .w(rems(1.5))
1373 .opacity(opacity)
1374 .bg(linear_gradient(
1375 90.,
1376 linear_color_stop(from, 0.),
1377 linear_color_stop(to, 1.),
1378 ))
1379 };
1380
1381 div()
1382 .relative()
1383 .w_full()
1384 .min_w_0()
1385 .child(row)
1386 .child(ScrollableMask::vertical_wheel(&handle))
1387 .when_some(fades, |this, (color, leading, trailing)| {
1388 this.when(leading > 0., |this| this.child(fade(color, leading, true)))
1389 .when(trailing > 0., |this| {
1390 this.child(fade(color, trailing, false))
1391 })
1392 })
1393 }
1394}
1395
1396#[cfg(test)]
1397mod tests {
1398 use super::*;
1399
1400 #[test]
1401 fn test_attachment_builder() {
1402 let mut attachment = Attachment::new()
1403 .status(AttachmentStatus::Uploading)
1404 .axis(Axis::Vertical)
1405 .with_size(Size::Small)
1406 .media(AttachmentMedia::new().src("preview.png"))
1407 .content(
1408 AttachmentContent::new()
1409 .title(AttachmentTitle::new("report.pdf"))
1410 .description(AttachmentDescription::new("Uploading")),
1411 )
1412 .actions(AttachmentActions::new().child("Cancel"));
1413
1414 assert_eq!(attachment.status, AttachmentStatus::Uploading);
1415 assert_eq!(attachment.axis, Axis::Vertical);
1416 assert_eq!(attachment.size, Size::Small);
1417 assert!(attachment.media.is_some());
1418 assert!(attachment.content.is_some());
1419 assert!(attachment.actions.is_some());
1420
1421 attachment.layout_slots();
1422 assert_eq!(attachment.media.as_ref().unwrap().size, Some(Size::Small));
1423 assert_eq!(
1424 attachment.media.as_ref().unwrap().status,
1425 AttachmentStatus::Uploading
1426 );
1427 assert!(attachment.content.as_ref().unwrap().vertical_layout);
1428 assert!(attachment.actions.as_ref().unwrap().vertical_layout);
1429
1430 let handle = ScrollHandle::new();
1431 let group = AttachmentGroup::new("group")
1432 .track_scroll(&handle)
1433 .with_edge_fade(gpui::black())
1434 .child("first")
1435 .child("second");
1436 assert!(group.scroll_handle.is_some());
1437 assert_eq!(group.edge_fade, Some(gpui::black()));
1438 assert_eq!(group.children.len(), 2);
1439 assert!(AttachmentGroup::new("plain").scroll_handle.is_none());
1440 assert!(AttachmentGroup::new("plain").edge_fade.is_none());
1441 }
1442
1443 #[test]
1444 fn test_attachment_whole_card_click_builder() {
1445 assert!(Attachment::new().id.is_none());
1446 assert!(Attachment::new().on_click.is_none());
1447
1448 let clickable = Attachment::new()
1449 .id("report-attachment")
1450 .on_click(|_, _, _| {});
1451 assert_eq!(clickable.id, Some("report-attachment".into()));
1452 assert!(clickable.on_click.is_some());
1453 }
1454
1455 #[test]
1456 fn test_attachment_corner_controls_builder() {
1457 assert!(Attachment::new().on_remove.is_none());
1458 assert!(Attachment::new().on_retry.is_none());
1459
1460 let attachment = Attachment::new()
1461 .id("upload")
1462 .on_remove(|_, _, _| {})
1463 .on_retry(|_, _, _| {});
1464 assert!(attachment.on_remove.is_some());
1465 assert!(attachment.on_retry.is_some());
1466 }
1467
1468 #[test]
1469 fn test_attachment_retry_control_reaches_slots_only_while_failed() {
1470 let mut failed = Attachment::new()
1471 .id("upload")
1472 .status(AttachmentStatus::Failed)
1473 .on_retry(|_, _, _| {})
1474 .media(AttachmentMedia::new().src("preview.png"))
1475 .content(AttachmentContent::new().description(AttachmentDescription::new("Failed")));
1476 failed.layout_slots();
1477 assert!(failed.media.as_ref().unwrap().retry.is_some());
1478 assert!(failed.content.as_ref().unwrap().retry.is_some());
1479
1480 let mut complete = Attachment::new()
1483 .id("upload")
1484 .on_retry(|_, _, _| {})
1485 .media(AttachmentMedia::new().src("preview.png"));
1486 complete.layout_slots();
1487 assert!(complete.media.as_ref().unwrap().retry.is_none());
1488
1489 let mut anonymous = Attachment::new()
1490 .status(AttachmentStatus::Failed)
1491 .on_retry(|_, _, _| {})
1492 .media(AttachmentMedia::new().src("preview.png"));
1493 anonymous.layout_slots();
1494 assert!(anonymous.media.as_ref().unwrap().retry.is_none());
1495 }
1496
1497 #[test]
1498 fn test_attachment_progress_and_tooltip_builder() {
1499 assert!(Attachment::new().progress.is_none());
1500 assert!(Attachment::new().tooltip.is_none());
1501 assert_eq!(Attachment::new().progress(130.).progress, Some(100.));
1502 assert_eq!(Attachment::new().progress(-5.).progress, Some(0.));
1503 assert_eq!(
1504 Attachment::new().tooltip("Network error").tooltip,
1505 Some("Network error".into())
1506 );
1507
1508 let mut uploading = Attachment::new()
1510 .id("upload")
1511 .status(AttachmentStatus::Uploading)
1512 .progress(62.)
1513 .media(AttachmentMedia::new().src("preview.png"))
1514 .content(AttachmentContent::new().description(AttachmentDescription::new("Uploading")));
1515 uploading.layout_slots();
1516 assert_eq!(uploading.media.as_ref().unwrap().progress, Some(62.));
1517 assert_eq!(uploading.content.as_ref().unwrap().progress, Some(62.));
1518
1519 let mut processing = Attachment::new()
1520 .status(AttachmentStatus::Processing)
1521 .progress(62.)
1522 .media(AttachmentMedia::new().src("preview.png"));
1523 processing.layout_slots();
1524 assert!(processing.media.as_ref().unwrap().progress.is_none());
1525 }
1526
1527 #[test]
1528 fn test_attachment_image_tile_media_is_flush() {
1529 let mut tile = Attachment::new()
1530 .axis(Axis::Vertical)
1531 .media(AttachmentMedia::new().src("preview.png"));
1532 tile.layout_slots();
1533 assert!(tile.media.as_ref().unwrap().flush);
1534
1535 let mut card = Attachment::new()
1536 .axis(Axis::Vertical)
1537 .media(AttachmentMedia::new().src("preview.png"))
1538 .content(AttachmentContent::new().title(AttachmentTitle::new("preview.png")));
1539 card.layout_slots();
1540 assert!(!card.media.as_ref().unwrap().flush);
1541 }
1542
1543 #[test]
1544 fn test_attachment_defaults_and_status_helpers() {
1545 assert_eq!(Attachment::new().status, AttachmentStatus::Complete);
1546 assert_eq!(AttachmentStatus::default(), AttachmentStatus::Complete);
1547 assert!(AttachmentStatus::Pending.is_pending());
1548 assert!(AttachmentStatus::Uploading.is_in_progress());
1549 assert!(AttachmentStatus::Processing.is_processing());
1550 assert!(AttachmentStatus::Failed.is_failed());
1551 assert!(AttachmentStatus::Complete.is_complete());
1552 assert!(!AttachmentStatus::Complete.is_in_progress());
1553 }
1554
1555 #[test]
1556 fn test_attachment_slots_are_composable() {
1557 let media = AttachmentMedia::new().child("icon");
1558 assert_eq!(media.children.len(), 1);
1559
1560 let content = AttachmentContent::new()
1561 .title(AttachmentTitle::new("name"))
1562 .description(AttachmentDescription::new("Details"))
1563 .child("Custom progress");
1564 assert_eq!(content.children.len(), 3);
1565 assert!(matches!(
1566 content.children[0],
1567 AttachmentContentChild::Title(_)
1568 ));
1569 assert!(matches!(
1570 content.children[1],
1571 AttachmentContentChild::Description(_)
1572 ));
1573 assert!(matches!(
1574 content.children[2],
1575 AttachmentContentChild::Element(_)
1576 ));
1577
1578 let legacy = AttachmentContent::new().child(AttachmentTitle::new("legacy"));
1579 assert!(matches!(
1580 legacy.children[0],
1581 AttachmentContentChild::Element(_)
1582 ));
1583
1584 let actions = AttachmentActions::new().child("remove");
1585 assert_eq!(actions.children.len(), 1);
1586 }
1587
1588 #[test]
1589 fn test_attachment_typed_content_inherits_status() {
1590 let mut attachment = Attachment::new()
1591 .status(AttachmentStatus::Uploading)
1592 .content(
1593 AttachmentContent::new()
1594 .title(AttachmentTitle::new("report.pdf"))
1595 .description(AttachmentDescription::new("Uploading")),
1596 );
1597
1598 attachment.layout_slots();
1599
1600 let content = attachment.content.unwrap();
1601 let AttachmentContentChild::Title(title) = &content.children[0] else {
1602 panic!("expected the typed title slot");
1603 };
1604 assert_eq!(title.status, Some(AttachmentStatus::Uploading));
1605
1606 let AttachmentContentChild::Description(description) = &content.children[1] else {
1607 panic!("expected the typed description slot");
1608 };
1609 assert_eq!(description.status, Some(AttachmentStatus::Uploading));
1610 }
1611
1612 #[test]
1613 fn test_attachment_explicit_child_status_overrides_parent() {
1614 let mut attachment = Attachment::new().status(AttachmentStatus::Failed).content(
1615 AttachmentContent::new()
1616 .title(AttachmentTitle::new("report.pdf").status(AttachmentStatus::Processing))
1617 .description(
1618 AttachmentDescription::new("Previous upload completed")
1619 .status(AttachmentStatus::Complete),
1620 ),
1621 );
1622
1623 attachment.layout_slots();
1624
1625 let content = attachment.content.unwrap();
1626 let AttachmentContentChild::Title(title) = &content.children[0] else {
1627 panic!("expected the typed title slot");
1628 };
1629 assert_eq!(title.status, Some(AttachmentStatus::Processing));
1630
1631 let AttachmentContentChild::Description(description) = &content.children[1] else {
1632 panic!("expected the typed description slot");
1633 };
1634 assert_eq!(description.status, Some(AttachmentStatus::Complete));
1635 }
1636
1637 #[test]
1638 fn test_attachment_title_keeps_custom_shimmer_style() {
1639 let mut attachment = Attachment::new()
1640 .status(AttachmentStatus::Processing)
1641 .content(
1642 AttachmentContent::new().title(
1643 AttachmentTitle::new("report.pdf")
1644 .with_shimmer_style(ShimmerStyle::new().spread(0.45).reverse(true)),
1645 ),
1646 );
1647
1648 attachment.layout_slots();
1649
1650 let content = attachment.content.unwrap();
1651 let AttachmentContentChild::Title(title) = &content.children[0] else {
1652 panic!("expected the typed title slot");
1653 };
1654 assert_eq!(title.status, Some(AttachmentStatus::Processing));
1655 assert!(title.shimmer_style.is_some());
1656 }
1657
1658 #[test]
1659 fn test_attachment_media_preview_keeps_children_and_overlays() {
1660 let media = AttachmentMedia::new()
1661 .src("preview.png")
1662 .child("Existing overlay")
1663 .overlay("Centered overlay");
1664
1665 assert!(media.source.is_some());
1666 assert_eq!(media.children.len(), 1);
1667 assert_eq!(media.overlays.len(), 1);
1668 }
1669
1670 #[test]
1671 fn test_attachment_media_size_inherits_root_unless_explicit() {
1672 let slot = |size, status, axis, flush| SlotLayout {
1673 size,
1674 status,
1675 axis,
1676 flush,
1677 retry: None,
1678 progress: None,
1679 id: None,
1680 };
1681 let inherited = AttachmentMedia::new().layout(slot(
1682 Size::Small,
1683 AttachmentStatus::Complete,
1684 Axis::Vertical,
1685 true,
1686 ));
1687 assert_eq!(inherited.size, Some(Size::Small));
1688 assert_eq!(inherited.axis, Axis::Vertical);
1689 assert!(inherited.flush);
1690
1691 let explicit = AttachmentMedia::new().with_size(Size::XSmall).layout(slot(
1692 Size::Large,
1693 AttachmentStatus::Failed,
1694 Axis::Horizontal,
1695 false,
1696 ));
1697 assert_eq!(explicit.size, Some(Size::XSmall));
1698 assert_eq!(explicit.status, AttachmentStatus::Failed);
1699 }
1700
1701 #[test]
1702 fn test_attachment_group_builder() {
1703 let group = AttachmentGroup::new("attachments")
1704 .child("First")
1705 .child("Second");
1706
1707 assert_eq!(group.children.len(), 2);
1708 }
1709
1710 mod click_dispatch {
1711 use std::{cell::Cell, rc::Rc};
1712
1713 use gpui::{Context, Modifiers, Render, TestAppContext, point, px};
1714
1715 use super::super::*;
1716 use crate::button::Button;
1717
1718 struct AttachmentClickHarness {
1719 card_clicks: Rc<Cell<usize>>,
1720 action_clicks: Rc<Cell<usize>>,
1721 }
1722
1723 impl Render for AttachmentClickHarness {
1724 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1725 let card_clicks = self.card_clicks.clone();
1726 let action_clicks = self.action_clicks.clone();
1727
1728 Attachment::new()
1729 .id("attachment")
1730 .w(px(200.))
1731 .h(px(60.))
1732 .on_click(move |_, _, _| card_clicks.set(card_clicks.get() + 1))
1733 .actions(
1734 AttachmentActions::new().child(
1735 Button::new("open")
1736 .w(px(40.))
1737 .h(px(40.))
1738 .on_click(move |_, _, _| {
1739 action_clicks.set(action_clicks.get() + 1)
1740 }),
1741 ),
1742 )
1743 }
1744 }
1745
1746 #[gpui::test]
1747 fn whole_card_click_stays_below_the_actions(cx: &mut TestAppContext) {
1748 cx.update(crate::init);
1749 let card_clicks = Rc::new(Cell::new(0));
1750 let action_clicks = Rc::new(Cell::new(0));
1751 let (_, cx) = cx.add_window_view({
1752 let card_clicks = card_clicks.clone();
1753 let action_clicks = action_clicks.clone();
1754 move |_, _| AttachmentClickHarness {
1755 card_clicks,
1756 action_clicks,
1757 }
1758 });
1759 cx.update(|window, cx| window.draw(cx).clear(cx));
1760
1761 cx.simulate_click(point(px(20.), px(30.)), Modifiers::default());
1763 assert_eq!(action_clicks.get(), 1);
1764 assert_eq!(card_clicks.get(), 0);
1765
1766 cx.simulate_click(point(px(150.), px(30.)), Modifiers::default());
1768 assert_eq!(action_clicks.get(), 1);
1769 assert_eq!(card_clicks.get(), 1);
1770 }
1771 }
1772
1773 mod retry_dispatch {
1774 use std::{cell::Cell, rc::Rc};
1775
1776 use gpui::{
1777 Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
1778 VisualTestContext, point, px,
1779 };
1780
1781 use super::super::*;
1782
1783 struct FailedMediaHarness {
1784 retry: bool,
1785 retries: Rc<Cell<usize>>,
1786 }
1787
1788 impl Render for FailedMediaHarness {
1789 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1790 let retries = self.retries.clone();
1791 Attachment::new()
1792 .id("failed-attachment")
1793 .status(AttachmentStatus::Failed)
1794 .media(AttachmentMedia::new())
1795 .when(self.retry, |attachment| {
1796 attachment.on_retry(move |_, _, _| retries.set(retries.get() + 1))
1797 })
1798 }
1799 }
1800
1801 fn harness(
1802 cx: &mut TestAppContext,
1803 retry: bool,
1804 ) -> (&mut VisualTestContext, Rc<Cell<usize>>) {
1805 cx.update(crate::init);
1806 let retries = Rc::new(Cell::new(0));
1807 let (_, cx) = cx.add_window_view({
1808 let retries = retries.clone();
1809 move |_, _| FailedMediaHarness { retry, retries }
1810 });
1811 cx.update(|window, cx| window.draw(cx).clear(cx));
1812 (cx, retries)
1813 }
1814
1815 #[gpui::test]
1816 fn failed_media_without_source_retries_by_pointer_and_keyboard(cx: &mut TestAppContext) {
1817 let (cx, retries) = harness(cx, true);
1818 cx.simulate_click(point(px(20.), px(20.)), Modifiers::default());
1819 assert_eq!(retries.get(), 1);
1820
1821 cx.update(|window, cx| window.focus_next(cx));
1822 cx.update(|window, cx| assert!(window.focused(cx).is_some()));
1823 let keystroke = Keystroke::parse("enter").unwrap();
1824 cx.simulate_event(KeyDownEvent {
1825 keystroke: keystroke.clone(),
1826 is_held: false,
1827 prefer_character_input: false,
1828 });
1829 cx.simulate_event(KeyUpEvent { keystroke });
1830 assert_eq!(retries.get(), 2);
1831 }
1832
1833 #[gpui::test]
1834 fn failed_media_without_retry_has_no_action(cx: &mut TestAppContext) {
1835 let (cx, retries) = harness(cx, false);
1836 cx.simulate_click(point(px(20.), px(20.)), Modifiers::default());
1837 assert_eq!(retries.get(), 0);
1838 cx.update(|window, cx| window.focus_next(cx));
1839 cx.update(|window, cx| assert!(window.focused(cx).is_none()));
1840 }
1841 }
1842}