1use super::entrance::{DialogEntrance, EntranceSurface};
2use crate::root::WindowState;
3use gpui_base::TestSupportExt as _;
4use std::{rc::Rc, sync::LazyLock, time::Duration};
5
6use gpui::{
7 Action, Anchor, AnyElement, App, BoxShadow, ClickEvent, Edges, FocusHandle, Hsla,
8 InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString,
9 StyleRefinement, Styled, Window, WindowControlArea, anchored, div, hsla, point,
10 prelude::FluentBuilder, px,
11};
12use gpui_base::{ElementExt as _, LogicalStyledExt as _, TextSelectionScopeId, motion::Transition};
13use rust_i18n::t;
14
15use crate::{
16 ActiveTheme as _, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT, WindowExt as _,
17 animation::cubic_bezier,
18 button::{Button, ButtonVariant, ButtonVariants as _},
19 dialog::{DialogContent, DialogDispatchAnchor, DialogTitle},
20 scroll::ScrollableElement as _,
21 v_flex,
22};
23
24pub static ANIMATION_DURATION: LazyLock<Duration> = LazyLock::new(|| Duration::from_secs_f64(0.25));
25pub use gpui_base::actions::{Cancel, Confirm};
26
27type OkHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static>;
28type CancelHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static>;
29type CloseHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
30
31fn merge_field<T>(slot: &mut Option<T>, value: Option<T>) {
33 if value.is_some() {
34 *slot = value;
35 }
36}
37
38#[derive(Clone, Default)]
47pub struct DialogButtonProps {
48 pub(crate) ok_text: Option<SharedString>,
49 pub(crate) ok_variant: Option<ButtonVariant>,
50 pub(crate) cancel_text: Option<SharedString>,
51 pub(crate) cancel_variant: Option<ButtonVariant>,
52 pub(crate) show_cancel: Option<bool>,
53 pub(crate) on_ok: Option<OkHandler>,
54 pub(crate) on_cancel: Option<CancelHandler>,
55 pub(crate) on_close: Option<CloseHandler>,
56}
57
58impl DialogButtonProps {
59 pub fn ok_text(mut self, ok_text: impl Into<SharedString>) -> Self {
61 self.ok_text = Some(ok_text.into());
62 self
63 }
64
65 pub fn ok_variant(mut self, ok_variant: ButtonVariant) -> Self {
67 self.ok_variant = Some(ok_variant);
68 self
69 }
70
71 pub fn cancel_text(mut self, cancel_text: impl Into<SharedString>) -> Self {
73 self.cancel_text = Some(cancel_text.into());
74 self
75 }
76
77 pub fn cancel_variant(mut self, cancel_variant: ButtonVariant) -> Self {
79 self.cancel_variant = Some(cancel_variant);
80 self
81 }
82
83 pub fn show_cancel(mut self, show_cancel: bool) -> Self {
85 self.show_cancel = Some(show_cancel);
86 self
87 }
88
89 pub fn on_ok(
93 mut self,
94 on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
95 ) -> Self {
96 self.on_ok = Some(Rc::new(on_ok));
97 self
98 }
99
100 pub fn on_cancel(
104 mut self,
105 on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
106 ) -> Self {
107 self.on_cancel = Some(Rc::new(on_cancel));
108 self
109 }
110
111 pub(crate) fn merge(&mut self, other: Self) {
113 merge_field(&mut self.ok_text, other.ok_text);
114 merge_field(&mut self.ok_variant, other.ok_variant);
115 merge_field(&mut self.cancel_text, other.cancel_text);
116 merge_field(&mut self.cancel_variant, other.cancel_variant);
117 merge_field(&mut self.show_cancel, other.show_cancel);
118 merge_field(&mut self.on_ok, other.on_ok);
119 merge_field(&mut self.on_cancel, other.on_cancel);
120 merge_field(&mut self.on_close, other.on_close);
121 }
122
123 pub(crate) fn is_cancel_shown(&self) -> bool {
125 self.show_cancel.unwrap_or(false)
126 }
127
128 pub(crate) fn ok_handler(&self) -> OkHandler {
130 self.on_ok
131 .clone()
132 .unwrap_or_else(|| Rc::new(|_, _, _| true))
133 }
134
135 pub(crate) fn cancel_handler(&self) -> CancelHandler {
137 self.on_cancel
138 .clone()
139 .unwrap_or_else(|| Rc::new(|_, _, _| true))
140 }
141
142 pub(crate) fn close_handler(&self) -> CloseHandler {
144 self.on_close
145 .clone()
146 .unwrap_or_else(|| Rc::new(|_, _, _| {}))
147 }
148
149 pub(crate) fn render_ok(&self, _: &mut Window, _: &mut App) -> AnyElement {
150 let ok_text = self
151 .ok_text
152 .clone()
153 .unwrap_or_else(|| t!("Dialog.ok").into());
154
155 DialogButton {
156 anchor_key: "dialog-ok-anchor",
157 button: Button::new("ok")
158 .label(ok_text)
159 .with_variant(self.ok_variant.unwrap_or(ButtonVariant::Primary)),
160 action: Rc::new(Confirm { secondary: false }),
161 }
162 .into_any_element()
163 }
164
165 pub(crate) fn render_cancel(&self, _: &mut Window, _: &mut App) -> AnyElement {
166 let cancel_text = self
167 .cancel_text
168 .clone()
169 .unwrap_or_else(|| t!("Dialog.cancel").into());
170
171 DialogButton {
172 anchor_key: "dialog-cancel-anchor",
173 button: Button::new("cancel")
174 .label(cancel_text)
175 .with_variant(self.cancel_variant.unwrap_or_default()),
176 action: Rc::new(Cancel),
177 }
178 .into_any_element()
179 }
180}
181
182#[derive(IntoElement)]
185struct DialogButton {
186 anchor_key: &'static str,
188 button: Button,
189 action: Rc<dyn Action>,
190}
191
192impl RenderOnce for DialogButton {
193 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
194 let anchor = DialogDispatchAnchor::new(self.anchor_key, window, cx);
195 self.button
196 .child(anchor.element())
197 .on_click(move |_, window, cx| anchor.dispatch(&*self.action, window, cx))
198 }
199}
200
201type ContentBuilderFn = Rc<dyn Fn(DialogContent, &mut Window, &mut App) -> DialogContent + 'static>;
202
203#[derive(Clone)]
204pub(crate) struct DialogProps {
205 width: Pixels,
206 max_width: Option<Pixels>,
207 margin_top: Option<Pixels>,
208 centered: bool,
209 close_button: bool,
210
211 overlay: bool,
212 overlay_closable: bool,
213 pub(crate) overlay_visible: bool,
214 keyboard: bool,
215 entrance: DialogEntrance,
216}
217
218impl Default for DialogProps {
219 fn default() -> Self {
220 Self {
221 margin_top: None,
222 centered: false,
223 width: px(448.),
224 max_width: None,
225 overlay: true,
226 keyboard: true,
227 overlay_visible: false,
228 close_button: true,
229 overlay_closable: true,
230 entrance: DialogEntrance::default(),
231 }
232 }
233}
234
235enum BaseDialogRoot {
236 Dialog(gpui_base::Dialog),
237 AlertDialog(gpui_base::AlertDialog),
238}
239
240macro_rules! map_base_root {
241 ($self:expr, $method:ident($($arg:expr),* $(,)?)) => {
242 match $self {
243 BaseDialogRoot::Dialog(root) => BaseDialogRoot::Dialog(root.$method($($arg),*)),
244 BaseDialogRoot::AlertDialog(root) => {
245 BaseDialogRoot::AlertDialog(root.$method($($arg),*))
246 }
247 }
248 };
249}
250
251impl BaseDialogRoot {
252 fn layer(self, index: usize, topmost: bool) -> Self {
253 map_base_root!(self, layer(index, topmost))
254 }
255 fn focus_handle(self, focus: FocusHandle) -> Self {
256 map_base_root!(self, focus_handle(focus))
257 }
258 fn close_on_escape(self, value: bool) -> Self {
259 map_base_root!(self, close_on_escape(value))
260 }
261 fn close_on_backdrop_press(self, value: bool) -> Self {
262 match self {
263 Self::Dialog(root) => Self::Dialog(root.close_on_backdrop_press(value)),
264 Self::AlertDialog(root) => Self::AlertDialog(root),
265 }
266 }
267 fn dismiss_below_y(self, value: Pixels) -> Self {
268 map_base_root!(self, dismiss_below_y(value))
269 }
270 fn backdrop(self, element: impl IntoElement) -> Self {
271 map_base_root!(self, backdrop(element))
272 }
273 fn popup(self, element: impl IntoElement) -> Self {
274 map_base_root!(self, popup(element))
275 }
276 fn on_ok(self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static) -> Self {
277 map_base_root!(self, on_ok(handler))
278 }
279 fn on_cancel(
280 self,
281 handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
282 ) -> Self {
283 map_base_root!(self, on_cancel(handler))
284 }
285 fn on_close(self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
286 map_base_root!(self, on_close(handler))
287 }
288 fn request_close(self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
289 map_base_root!(self, request_close(handler))
290 }
291}
292
293impl Styled for BaseDialogRoot {
294 fn style(&mut self) -> &mut StyleRefinement {
295 match self {
296 Self::Dialog(root) => root.style(),
297 Self::AlertDialog(root) => root.style(),
298 }
299 }
300}
301
302impl IntoElement for BaseDialogRoot {
303 type Element = <gpui_base::Dialog as IntoElement>::Element;
304 fn into_element(self) -> Self::Element {
305 match self {
306 Self::Dialog(root) => root.into_element(),
307 Self::AlertDialog(root) => root.into_element(),
308 }
309 }
310}
311
312#[derive(Clone, Copy, Debug)]
316pub(crate) struct DialogMotion {
317 pub(crate) visibility: f32,
318 pub(crate) closing: bool,
319}
320
321#[derive(IntoElement)]
323pub struct Dialog {
324 base: Option<BaseDialogRoot>,
325 pub(crate) style: StyleRefinement,
326 children: Vec<AnyElement>,
327 trigger: Option<AnyElement>,
328 title: Option<AnyElement>,
329 pub(crate) header: Option<AnyElement>,
330 pub(crate) footer: Option<AnyElement>,
331 pub(crate) content_builder: Option<ContentBuilderFn>,
332 pub(crate) props: DialogProps,
333
334 pub(super) button_props: DialogButtonProps,
335
336 pub(crate) focus_handle: FocusHandle,
338 pub(crate) layer_ix: usize,
339 pub(crate) stack_depth: usize,
341 pub(crate) selection_scope: TextSelectionScopeId,
342 pub(crate) motion: Option<DialogMotion>,
343 pub(crate) id: usize,
344}
345
346pub(crate) fn overlay_color(overlay: bool, cx: &App) -> Hsla {
347 if !overlay {
348 return hsla(0., 0., 0., 0.);
349 }
350
351 cx.theme().overlay
352}
353
354fn dialog_shadow(delta: f32) -> Vec<BoxShadow> {
355 vec![
356 BoxShadow {
357 color: hsla(0., 0., 0., 0.1 * delta),
358 offset: point(px(0.), px(20.)),
359 blur_radius: px(25.),
360 spread_radius: px(-5.),
361 inset: false,
362 },
363 BoxShadow {
364 color: hsla(0., 0., 0., 0.1 * delta),
365 offset: point(px(0.), px(8.)),
366 blur_radius: px(10.),
367 spread_radius: px(-6.),
368 inset: false,
369 },
370 ]
371}
372
373impl Dialog {
374 pub fn new(cx: &mut App) -> Self {
376 Self {
377 base: Some(BaseDialogRoot::Dialog(gpui_base::Dialog::new(cx))),
378 focus_handle: cx.focus_handle(),
379 style: StyleRefinement::default(),
380 trigger: None,
381 title: None,
382 header: None,
383 footer: None,
384 content_builder: None,
385 props: DialogProps::default(),
386 children: Vec::new(),
387 layer_ix: 0,
388 stack_depth: 0,
389 selection_scope: TextSelectionScopeId::default(),
390 button_props: DialogButtonProps::default(),
391 motion: None,
392 id: 0,
393 }
394 }
395
396 pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
400 self.trigger = Some(trigger.into_any_element());
401 self
402 }
403
404 pub fn content<F>(mut self, builder: F) -> Self
406 where
407 F: Fn(DialogContent, &mut Window, &mut App) -> DialogContent + 'static,
408 {
409 self.content_builder = Some(Rc::new(builder));
410 self
411 }
412
413 pub fn title(mut self, title: impl IntoElement) -> Self {
415 self.title = Some(title.into_any_element());
416 self
417 }
418
419 pub(crate) fn header(mut self, header: impl IntoElement) -> Self {
421 self.header = Some(header.into_any_element());
422 self
423 }
424
425 pub fn footer(mut self, footer: impl IntoElement) -> Self {
434 self.footer = Some(footer.into_any_element());
435 self
436 }
437
438 pub fn button_props(mut self, button_props: DialogButtonProps) -> Self {
450 self.button_props.merge(button_props);
451 self
452 }
453
454 pub(crate) fn with_base_alert_dialog(mut self, base: gpui_base::AlertDialog) -> Self {
455 self.base = Some(BaseDialogRoot::AlertDialog(base));
456 self.props.overlay_closable = false;
457 self
458 }
459
460 pub fn on_close(
464 mut self,
465 on_close: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
466 ) -> Self {
467 self.button_props.on_close = Some(Rc::new(on_close));
468 self
469 }
470
471 pub fn on_ok(
475 mut self,
476 on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
477 ) -> Self {
478 self.button_props = self.button_props.on_ok(on_ok);
479 self
480 }
481
482 pub fn on_cancel(
486 mut self,
487 on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
488 ) -> Self {
489 self.button_props = self.button_props.on_cancel(on_cancel);
490 self
491 }
492
493 pub fn close_button(mut self, close_button: bool) -> Self {
495 self.props.close_button = close_button;
496 self
497 }
498
499 pub fn margin_top(mut self, margin_top: impl Into<Pixels>) -> Self {
501 self.props.margin_top = Some(margin_top.into());
502 self
503 }
504
505 pub fn centered(mut self) -> Self {
508 self.props.centered = true;
509 self
510 }
511
512 pub fn w(mut self, width: impl Into<Pixels>) -> Self {
518 self.props.width = width.into();
519 self
520 }
521
522 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
526 self.props.width = width.into();
527 self
528 }
529
530 pub fn max_w(mut self, max_width: impl Into<Pixels>) -> Self {
532 self.props.max_width = Some(max_width.into());
533 self
534 }
535
536 pub fn overlay(mut self, overlay: bool) -> Self {
538 self.props.overlay = overlay;
539 self
540 }
541
542 pub fn overlay_closable(mut self, overlay_closable: bool) -> Self {
546 self.props.overlay_closable = overlay_closable;
547 self
548 }
549
550 pub fn keyboard(mut self, keyboard: bool) -> Self {
552 self.props.keyboard = keyboard;
553 self
554 }
555
556 pub fn entrance(mut self, entrance: DialogEntrance) -> Self {
562 self.props.entrance = entrance;
563 self
564 }
565
566 pub(crate) fn exit_duration(&self, cx: &App) -> Duration {
571 if cx.reduce_motion() {
572 return Duration::ZERO;
573 }
574
575 match self.props.entrance {
576 DialogEntrance::None => Duration::ZERO,
577 DialogEntrance::SlideDown => *ANIMATION_DURATION,
578 _ => cx.theme().motion_tokens().duration_normal,
579 }
580 }
581
582 pub(crate) fn motion_transition(&self, cx: &App) -> Transition {
583 let transition = Transition::new(self.exit_duration(cx));
584 if self.props.entrance == DialogEntrance::SlideDown {
587 transition.ease(cubic_bezier(1. / 3., 0.72, 2. / 3., 1.))
588 } else {
589 let easing = cx.theme().motion_tokens().easing_enter.clone();
590 transition.ease(move |delta| easing.sample(delta).clamp(0., 1.))
591 }
592 }
593
594 pub(crate) fn has_overlay(&self) -> bool {
595 self.props.overlay
596 }
597
598 pub(crate) fn with_props(mut self, props: DialogProps) -> Self {
599 self.props = props;
600 self
601 }
602
603 fn defer_close_dialog(window: &mut Window, cx: &mut App) {
604 WindowState::update(window, cx, |root, window, cx| {
605 root.defer_close_dialog(window, cx);
606 });
607 }
608}
609
610impl ParentElement for Dialog {
611 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
612 self.children.extend(elements);
613 }
614}
615
616impl Styled for Dialog {
617 fn style(&mut self) -> &mut gpui::StyleRefinement {
618 &mut self.style
619 }
620}
621
622impl Dialog {
623 fn render_trigger(self, trigger: AnyElement, _: &mut Window, _: &mut App) -> AnyElement {
624 let content_builder = self.content_builder.clone();
625 let style = self.style.clone();
626 let props = self.props.clone();
627 let button_props = self.button_props.clone();
628
629 gpui_base::DialogTrigger::new(trigger)
630 .on_open(move |window, cx| {
631 let content_builder = content_builder.clone();
632 let style = style.clone();
633 let props = props.clone();
634 let button_props = button_props.clone();
635 window.open_dialog(cx, move |dialog, _, _| {
636 dialog
637 .refine_style(&style)
638 .button_props(button_props.clone())
639 .with_props(props.clone())
640 .content({
641 let content_builder = content_builder.clone();
642 move |content, window, cx| {
643 if let Some(builder) = content_builder.clone() {
644 builder(content, window, cx)
645 } else {
646 content
647 }
648 }
649 })
650 });
651 })
652 .into_any_element()
653 }
654}
655
656impl RenderOnce for Dialog {
657 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
658 if let Some(trigger) = self.trigger.take() {
659 return self.render_trigger(trigger, window, cx);
660 }
661
662 let layer_ix = self.layer_ix;
663 let selection_scope = self.selection_scope;
664 let on_close = self.button_props.close_handler();
665 let on_ok = self.button_props.ok_handler();
666 let on_cancel = self.button_props.cancel_handler();
667
668 let window_paddings = crate::window_border::window_paddings(window);
669 let view_size = window.viewport_size()
670 - gpui::size(
671 window_paddings.left + window_paddings.right,
672 window_paddings.top + window_paddings.bottom,
673 );
674 let margin = cx.theme().spacing_tokens().lg;
680 let layer_offset = px(self.stack_depth as f32 * 16.);
681 let (anchor, y) = if self.props.centered {
682 (Anchor::LeftCenter, view_size.height / 2.)
683 } else {
684 let y = self.props.margin_top.unwrap_or(view_size.height / 10.);
685 (Anchor::TopLeft, y)
686 };
687 let y = y + layer_offset;
688 let entrance = self.props.entrance;
689 let motion = cx.theme().motion_tokens();
690 let closing = self.motion.is_some_and(|motion| motion.closing);
691 let visibility = self
692 .motion
693 .map_or(1.0, |motion| motion.visibility.clamp(0., 1.));
694 let fade_overlay = closing && self.props.overlay_visible;
695 let travel = motion.distance_short.to_pixels(window.rem_size());
696 let width = self
697 .props
698 .width
699 .min((view_size.width - margin * 2.).max(px(0.)));
700 let x = (view_size.width - width) / 2.;
701 let max_height = (view_size.height - margin * 2. - layer_offset).max(px(0.));
702
703 let base_size = window.text_style().font_size;
704 let rem_size = window.rem_size();
705
706 let mut paddings = Edges::all(px(16.));
707 if let Some(pl) = self.style.padding.left {
708 paddings.left = pl.to_pixels(base_size, rem_size);
709 }
710 if let Some(pr) = self.style.padding.right {
711 paddings.right = pr.to_pixels(base_size, rem_size);
712 }
713 if let Some(pt) = self.style.padding.top {
714 paddings.top = pt.to_pixels(base_size, rem_size);
715 }
716 if let Some(pb) = self.style.padding.bottom {
717 paddings.bottom = pb.to_pixels(base_size, rem_size);
718 }
719
720 let topmost = WindowState::read(window, cx)
723 .active_dialogs
724 .iter()
725 .rposition(|dialog| !dialog.closing);
726 let is_topmost = !closing && topmost == Some(layer_ix);
727
728 anchored()
729 .position(point(window_paddings.left, window_paddings.top))
730 .snap_to_window()
731 .child(
732 div()
733 .id("dialog")
734 .test_support()
735 .when(!closing, |this| this.occlude())
738 .w(view_size.width)
739 .h(view_size.height)
740 .when(fade_overlay, |this| {
741 this.child(div().absolute().inset_0().bg(overlay_color(true, cx)))
742 })
743 .child(
744 self.base
745 .take()
746 .expect("Dialog base host is always present")
747 .layer(self.id, is_topmost)
748 .top(window_paddings.top)
752 .left(window_paddings.left)
753 .w(view_size.width)
754 .h(view_size.height)
755 .focus_handle(self.focus_handle.clone())
756 .close_on_escape(self.props.keyboard && !closing)
757 .close_on_backdrop_press(self.props.overlay_closable && !closing)
758 .dismiss_below_y(TITLE_BAR_HEIGHT)
759 .when(self.props.overlay && !closing, |this| {
760 this.backdrop(
761 div()
762 .absolute()
763 .size_full()
764 .window_control_area(WindowControlArea::Drag)
765 .when(self.props.overlay_visible, |overlay| {
766 overlay.bg(overlay_color(true, cx))
767 }),
768 )
769 })
770 .on_ok(move |event, window, cx| !closing && on_ok(event, window, cx))
771 .on_cancel(move |event, window, cx| {
772 !closing && on_cancel(event, window, cx)
773 })
774 .on_close(move |event, window, cx| on_close(event, window, cx))
775 .request_close(move |deferred, window, cx| {
776 if closing {
779 return;
780 }
781 if deferred {
782 Self::defer_close_dialog(window, cx);
783 } else {
784 window.close_dialog(cx);
785 }
786 })
787 .popup(
788 gpui_base::Positioner::corner(
789 anchor,
790 point(window_paddings.left + x, window_paddings.top + y),
791 )
792 .margin(margin)
793 .child(
794 v_flex()
795 .id("surface")
796 .test_support()
797 .debug_selector(move || format!("dialog-{layer_ix}"))
798 .bg(cx.theme().tokens.background)
799 .border_1()
800 .border_color(cx.theme().border)
801 .rounded(cx.theme().radius_lg)
802 .min_h_24()
803 .pt(paddings.top)
804 .pb(paddings.bottom)
805 .gap(paddings.top.max(px(8.)))
806 .refine_style(&self.style)
807 .px_0()
808 .occlude()
809 .w(width)
810 .when_some(self.props.max_width, |this, w| this.max_w(w))
811 .max_h(max_height)
812 .child(
813 v_flex()
814 .flex_1()
815 .overflow_hidden()
816 .gap_y_2()
817 .when_some(self.header, |this, header| {
818 this.child(
819 div()
820 .pl(paddings.left)
821 .pr(paddings.right)
822 .child(header),
823 )
824 })
825 .when_some(self.title, |this, title| {
826 this.child(
827 DialogTitle::new()
828 .pl(paddings.left)
829 .pr(paddings.right)
830 .child(title),
831 )
832 })
833 .when_some(self.content_builder, |this, builder| {
834 this.child(builder(
835 DialogContent::new()
836 .gap(paddings.bottom)
837 .pl(paddings.left)
838 .pr(paddings.right),
839 window,
840 cx,
841 ))
842 })
843 .when(!self.children.is_empty(), |this| {
844 this.child(
845 div().flex_1().overflow_hidden().child(
846 v_flex()
848 .size_full()
849 .overflow_y_scrollbar()
850 .pl(paddings.left)
851 .pr(paddings.right)
852 .children(self.children),
853 ),
854 )
855 }),
856 )
857 .when_some(self.footer, |this, footer| {
858 this.child(
859 div()
860 .pl(paddings.left)
861 .pr(paddings.right)
862 .child(footer),
863 )
864 })
865 .children(self.props.close_button.then(|| {
866 let top = (paddings.top - px(10.)).max(px(8.));
867 let right = (paddings.right - px(10.)).max(px(8.));
868
869 gpui_base::DialogClose::new()
870 .absolute()
871 .top(top)
872 .inset_e(right, cx)
873 .trigger(|button| {
874 Button::new("close")
875 .with_base(button)
876 .small()
877 .ghost()
878 .icon(IconName::Close)
879 .accessibility_label("Close")
880 })
881 }))
882 .when(closing, |surface| {
883 surface
886 .capture_any_mouse_down(|_, _, cx| {
887 cx.stop_propagation()
888 })
889 .capture_any_mouse_up(|_, _, cx| {
890 cx.stop_propagation()
891 })
892 .capture_key_down(|_, window, cx| {
893 window.prevent_default();
894 cx.stop_propagation();
895 })
896 .capture_key_up(|_, _, cx| cx.stop_propagation())
897 .child(
898 div()
899 .absolute()
900 .inset_0()
901 .occlude()
902 .on_any_mouse_down(|_, _, cx| {
903 cx.stop_propagation()
904 })
905 .on_scroll(|_, _, cx| {
906 cx.stop_propagation()
907 }),
908 )
909 })
910 .opacity(visibility)
913 .shadow(dialog_shadow(visibility))
914 .text_selection_scope(selection_scope)
915 .map(|surface| {
916 if entrance == DialogEntrance::FadeSlide {
917 let mut surface = EntranceSurface::new(
918 surface.into_any_element(),
919 travel,
920 window_paddings.top + margin,
921 );
922 surface.progress = visibility;
923 surface.into_any_element()
924 } else {
925 surface.into_any_element()
926 }
927 }),
928 )
929 .when(
930 entrance == DialogEntrance::SlideDown,
931 |positioner| {
932 positioner.position(point(
933 window_paddings.left + x,
934 window_paddings.top + y * visibility,
935 ))
936 },
937 ),
938 ),
939 )
940 .opacity(visibility),
941 )
942 .into_any_element()
943 }
944}
945
946#[cfg(test)]
947pub(crate) mod tests {
948 use super::*;
949 use gpui::{
950 AppContext as _, Bounds, Context, Render, StatefulInteractiveElement as _, TestAppContext,
951 VisualTestContext, size,
952 };
953 use std::{cell::Cell, rc::Rc};
954
955 struct DialogHost {
956 clicks: Rc<Cell<usize>>,
957 }
958
959 impl Render for DialogHost {
960 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
961 let clicks = self.clicks.clone();
962 div().size_full().child(
963 div()
966 .id("background-target")
967 .absolute()
968 .top_0()
969 .left_0()
970 .w_full()
971 .h(px(200.))
972 .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
973 )
974 }
975 }
976
977 pub(crate) fn window(
980 cx: &mut TestAppContext,
981 window_size: gpui::Size<Pixels>,
982 ) -> &mut VisualTestContext {
983 let (cx, _) = window_with_click_count(cx, window_size);
984 cx
985 }
986
987 fn window_with_click_count(
990 cx: &mut TestAppContext,
991 window_size: gpui::Size<Pixels>,
992 ) -> (&mut VisualTestContext, Rc<Cell<usize>>) {
993 cx.update(|cx| {
994 crate::init(cx);
995 cx.set_reduce_motion(true);
996 });
997 let clicks = Rc::new(Cell::new(0));
998 let counter = clicks.clone();
999 let (_, cx) = cx.add_window_view(|window, cx| {
1000 let view = cx.new(|_| DialogHost { clicks: counter });
1001 crate::Root::new(view, window, cx)
1002 });
1003 cx.simulate_resize(window_size);
1004 cx.update(|window, cx| window.draw(cx).clear(cx));
1005 (cx, clicks)
1006 }
1007
1008 fn open(
1009 cx: &mut VisualTestContext,
1010 build: impl Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
1011 ) {
1012 cx.update(|window, cx| window.open_dialog(cx, build));
1013 cx.run_until_parked();
1014 cx.update(|window, cx| window.draw(cx).clear(cx));
1016 cx.update(|window, cx| window.draw(cx).clear(cx));
1017 }
1018
1019 fn frame(cx: &mut VisualTestContext) {
1022 cx.update(|window, _| window.refresh());
1023 cx.run_until_parked();
1024 }
1025
1026 fn surface(cx: &mut VisualTestContext, layer_ix: usize) -> Bounds<Pixels> {
1027 let selector = ["dialog-0", "dialog-1"][layer_ix];
1028 cx.debug_bounds(selector)
1029 .unwrap_or_else(|| panic!("dialog layer {layer_ix} was not painted"))
1030 }
1031
1032 #[gpui::test]
1035 fn a_dialog_that_fits_keeps_its_default_width_and_top_offset(cx: &mut TestAppContext) {
1036 let cx = window(cx, size(px(1000.), px(800.)));
1037 open(cx, |dialog, _, _| dialog.title("Fits").child("body"));
1038
1039 let bounds = surface(cx, 0);
1040 assert_eq!(bounds.size.width, px(448.));
1041 assert_eq!(bounds.origin.x, px(276.));
1042 assert_eq!(bounds.origin.y, px(80.));
1043 }
1044
1045 #[gpui::test]
1050 fn a_dialog_larger_than_the_window_stays_inside_it(cx: &mut TestAppContext) {
1051 let viewport = size(px(400.), px(300.));
1052 let cx = window(cx, viewport);
1053 open(cx, |dialog, _, _| {
1054 dialog
1055 .w(px(800.))
1056 .title("Too big")
1057 .child(div().h(px(1000.)).child("tall body"))
1058 .footer(div().h(px(32.)).debug_selector(|| "footer-probe".into()))
1059 });
1060
1061 let bounds = surface(cx, 0);
1062 let footer = cx.debug_bounds("footer-probe").unwrap();
1063 let margin = px(16.);
1064 assert!(
1065 bounds.origin.x >= margin && bounds.right() <= viewport.width - margin,
1066 "the dialog ran off the sides: {bounds:?}"
1067 );
1068 assert!(
1069 bounds.bottom() <= viewport.height - margin,
1070 "the dialog ran off the bottom: {bounds:?}"
1071 );
1072 assert_eq!(bounds.origin.y, margin);
1073 assert!(
1074 footer.bottom() <= bounds.bottom(),
1075 "the footer was clipped below the dialog: footer {footer:?}, dialog {bounds:?}"
1076 );
1077 }
1078
1079 #[gpui::test]
1081 fn dialog_button_props_merge_with_what_the_dialog_already_carries(cx: &mut TestAppContext) {
1082 let cx = window(cx, size(px(400.), px(300.)));
1083 cx.update(|_, cx| {
1084 let dialog = Dialog::new(cx)
1085 .button_props(DialogButtonProps::default().cancel_text("Keep"))
1086 .button_props(DialogButtonProps::default().ok_text("Delete"))
1087 .button_props(DialogButtonProps::default().ok_variant(ButtonVariant::Danger));
1088
1089 assert_eq!(dialog.button_props.ok_text.as_deref(), Some("Delete"));
1090 assert_eq!(dialog.button_props.cancel_text.as_deref(), Some("Keep"));
1091 assert_eq!(dialog.button_props.ok_variant, Some(ButtonVariant::Danger));
1092 });
1093 }
1094
1095 #[gpui::test]
1098 fn stacked_dialogs_each_fit_the_window(cx: &mut TestAppContext) {
1099 let viewport = size(px(400.), px(300.));
1100 let cx = window(cx, viewport);
1101 open(cx, |dialog, _, _| {
1102 dialog.title("First").child(div().h(px(1000.)))
1103 });
1104 open(cx, |dialog, _, _| {
1105 dialog.title("Second").child(div().h(px(1000.)))
1106 });
1107
1108 let first = surface(cx, 0);
1109 let second = surface(cx, 1);
1110 assert_eq!(second.origin.y, first.origin.y + px(16.));
1111 assert!(first.bottom() <= viewport.height - px(16.), "{first:?}");
1112 assert!(second.bottom() <= viewport.height - px(16.), "{second:?}");
1113 assert!(second.size.height < first.size.height);
1114 }
1115
1116 #[gpui::test]
1117 fn test_dialog_entrance_builder(cx: &mut TestAppContext) {
1118 cx.update(crate::init);
1119 cx.update(|cx| {
1120 assert_eq!(Dialog::new(cx).props.entrance, DialogEntrance::SlideDown);
1121 for entrance in [
1122 DialogEntrance::SlideDown,
1123 DialogEntrance::Fade,
1124 DialogEntrance::FadeSlide,
1125 DialogEntrance::None,
1126 ] {
1127 assert_eq!(Dialog::new(cx).entrance(entrance).props.entrance, entrance);
1128 }
1129 });
1130 }
1131
1132 #[gpui::test]
1133 fn reduced_motion_displays_every_entrance_at_rest(cx: &mut TestAppContext) {
1134 for entrance in [
1135 DialogEntrance::SlideDown,
1136 DialogEntrance::Fade,
1137 DialogEntrance::FadeSlide,
1138 DialogEntrance::None,
1139 ] {
1140 let cx = window(cx, size(px(1000.), px(800.)));
1141 open(cx, move |dialog, _, _| {
1142 dialog
1143 .title("Entrance")
1144 .child("body")
1145 .entrance(entrance)
1146 .margin_top(px(300.))
1147 });
1148 assert_eq!(surface(cx, 0).top(), px(300.));
1149 }
1150 }
1151
1152 #[gpui::test]
1153 fn no_entrance_displays_immediately_and_keeps_keyboard_dismissal(cx: &mut TestAppContext) {
1154 let cx = window(cx, size(px(1000.), px(800.)));
1155 cx.update(|_, cx| cx.set_reduce_motion(false));
1156 open(cx, |dialog, _, _| {
1157 dialog
1158 .title("Immediate")
1159 .child("body")
1160 .entrance(DialogEntrance::None)
1161 .margin_top(px(300.))
1162 });
1163 assert_eq!(surface(cx, 0).top(), px(300.));
1164 cx.simulate_keystrokes("escape");
1165 cx.update(|window, cx| assert!(WindowState::read(window, cx).active_dialogs.is_empty()));
1166 }
1167
1168 #[gpui::test]
1171 fn closing_plays_the_entrance_backwards_before_the_dialog_unmounts(cx: &mut TestAppContext) {
1172 let cx = window(cx, size(px(1000.), px(800.)));
1173 cx.update(|_, cx| cx.set_reduce_motion(false));
1174 open(cx, |dialog, _, _| {
1175 dialog.title("Closing").child("body").margin_top(px(300.))
1176 });
1177
1178 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1179 frame(cx);
1180 cx.update(|window, cx| window.close_dialog(cx));
1181 frame(cx);
1182 cx.update(|window, cx| {
1185 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1);
1186 assert!(!window.has_active_dialog(cx));
1187 });
1188 assert_eq!(surface(cx, 0).top(), px(300.));
1189
1190 cx.background_executor
1192 .advance_clock(*ANIMATION_DURATION / 2);
1193 frame(cx);
1194 cx.update(|window, cx| assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1));
1195 let halfway = surface(cx, 0).top();
1196 assert!(
1197 halfway > px(0.) && halfway < px(300.),
1198 "the closing dialog should slide back up: {halfway:?}"
1199 );
1200
1201 cx.background_executor
1203 .advance_clock(*ANIMATION_DURATION / 2 + Duration::from_millis(1));
1204 frame(cx);
1205 cx.update(|window, cx| {
1206 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1207 assert!(!window.has_active_dialog(cx));
1208 });
1209 assert!(cx.debug_bounds("dialog-0").is_none());
1210 }
1211
1212 #[gpui::test]
1213 fn reduced_motion_closes_in_a_single_frame(cx: &mut TestAppContext) {
1214 let cx = window(cx, size(px(1000.), px(800.)));
1215 open(cx, |dialog, _, _| dialog.title("Reduced").child("body"));
1216 cx.update(|window, cx| window.close_dialog(cx));
1217 cx.update(|window, cx| {
1218 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1219 assert!(!window.has_active_dialog(cx));
1220 });
1221 }
1222
1223 #[gpui::test]
1224 fn zero_theme_duration_closes_fade_entrances_immediately(cx: &mut TestAppContext) {
1225 for entrance in [DialogEntrance::Fade, DialogEntrance::FadeSlide] {
1226 let cx = window(cx, size(px(1000.), px(800.)));
1227 cx.update(|_, cx| {
1228 cx.set_reduce_motion(false);
1229 crate::Theme::update(cx, |theme| theme.motion.duration_normal = Duration::ZERO);
1230 });
1231 open(cx, move |dialog, _, _| {
1232 dialog.title("Immediate").child("body").entrance(entrance)
1233 });
1234 cx.update(|window, cx| window.close_dialog(cx));
1235 cx.update(|window, cx| {
1236 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1237 assert!(!window.has_active_dialog(cx));
1238 });
1239 }
1240 }
1241
1242 #[gpui::test]
1245 fn reopening_during_the_exit_keeps_the_new_dialog(cx: &mut TestAppContext) {
1246 let cx = window(cx, size(px(1000.), px(800.)));
1247 cx.update(|_, cx| cx.set_reduce_motion(false));
1248 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1249 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1250 frame(cx);
1251 cx.update(|window, cx| window.close_dialog(cx));
1252 frame(cx);
1253
1254 open(cx, |dialog, _, _| dialog.title("Second").child("body"));
1255 cx.update(|window, cx| {
1256 let state = WindowState::read(window, cx);
1257 assert_eq!(state.active_dialogs.len(), 2);
1258 assert!(state.active_dialogs[0].closing);
1259 assert!(!state.active_dialogs[1].closing);
1260 assert!(
1261 state.active_dialogs[1].focus_handle().is_focused(window),
1262 "the reopened dialog owns focus while the old one leaves"
1263 );
1264 });
1265
1266 cx.background_executor
1267 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1268 frame(cx);
1269 frame(cx);
1271 cx.update(|window, cx| {
1272 let state = WindowState::read(window, cx);
1273 assert_eq!(state.active_dialogs.len(), 1);
1274 assert!(!state.active_dialogs[0].closing);
1275 assert!(state.active_dialogs[0].focus_handle().is_focused(window));
1276 assert!(window.has_active_dialog(cx));
1277 });
1278 assert_eq!(surface(cx, 0).top(), px(80.));
1279 assert!(cx.debug_bounds("dialog-1").is_none());
1280 }
1281
1282 #[gpui::test]
1286 fn a_closing_dialog_does_not_offset_the_next_one(cx: &mut TestAppContext) {
1287 for body_height in [px(40.), px(1000.)] {
1288 let cx = window(cx, size(px(1000.), px(800.)));
1289 cx.update(|_, cx| cx.set_reduce_motion(false));
1290 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1291 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1292 frame(cx);
1293 cx.update(|window, cx| window.close_dialog(cx));
1294 frame(cx);
1295
1296 open(cx, move |dialog, _, _| {
1297 dialog
1298 .title("Second")
1299 .child(div().h(body_height))
1300 .entrance(DialogEntrance::None)
1301 });
1302 let during_exit = surface(cx, 1);
1303
1304 cx.background_executor
1305 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1306 frame(cx);
1307 frame(cx);
1308 assert!(cx.debug_bounds("dialog-1").is_none());
1309 assert_eq!(during_exit, surface(cx, 0));
1310 }
1311 }
1312
1313 #[gpui::test]
1316 fn closing_the_top_dialog_leaves_the_one_below_mounted(cx: &mut TestAppContext) {
1317 let cx = window(cx, size(px(1000.), px(800.)));
1318 cx.update(|_, cx| cx.set_reduce_motion(false));
1319 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1320 open(cx, |dialog, _, _| dialog.title("Second").child("body"));
1321
1322 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1323 frame(cx);
1324 cx.update(|window, cx| window.close_dialog(cx));
1325 frame(cx);
1326 cx.update(|window, cx| {
1327 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 2);
1328 assert!(window.has_active_dialog(cx));
1329 });
1330 assert!(
1331 cx.debug_bounds("dialog-0").is_some(),
1332 "the lower dialog stays"
1333 );
1334 assert!(
1335 cx.debug_bounds("dialog-1").is_some(),
1336 "the closing dialog still paints its exit"
1337 );
1338
1339 cx.background_executor
1340 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1341 frame(cx);
1342 cx.update(|window, cx| {
1343 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1);
1344 assert!(window.has_active_dialog(cx));
1345 });
1346 assert!(cx.debug_bounds("dialog-0").is_some());
1347 assert!(cx.debug_bounds("dialog-1").is_none());
1348 }
1349
1350 #[gpui::test]
1353 fn closing_dialog_does_not_block_input_beneath_it(cx: &mut TestAppContext) {
1354 let (cx, clicks) = window_with_click_count(cx, size(px(1000.), px(800.)));
1355 cx.update(|_, cx| cx.set_reduce_motion(false));
1356 open(cx, |dialog, _, _| {
1357 dialog
1358 .title("Closing")
1359 .child("body")
1360 .margin_top(px(300.))
1361 .overlay_closable(false)
1362 });
1363
1364 let backdrop_point = point(px(100.), px(60.));
1367 cx.simulate_click(backdrop_point, gpui::Modifiers::default());
1368 assert_eq!(clicks.get(), 0, "an open dialog blocked the application");
1369
1370 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1371 frame(cx);
1372 cx.update(|window, cx| window.close_dialog(cx));
1373 frame(cx);
1374 cx.simulate_click(backdrop_point, gpui::Modifiers::default());
1375 assert_eq!(
1376 clicks.get(),
1377 1,
1378 "the closing dialog swallowed a press meant for the application"
1379 );
1380 }
1381
1382 #[gpui::test]
1383 fn zero_theme_duration_displays_fade_entrances_immediately(cx: &mut TestAppContext) {
1384 for entrance in [DialogEntrance::Fade, DialogEntrance::FadeSlide] {
1385 let cx = window(cx, size(px(1000.), px(800.)));
1386 cx.update(|_, cx| {
1387 cx.set_reduce_motion(false);
1388 crate::Theme::update(cx, |theme| theme.motion.duration_normal = Duration::ZERO);
1389 });
1390 open(cx, move |dialog, _, _| {
1391 dialog
1392 .title("Immediate")
1393 .child("body")
1394 .entrance(entrance)
1395 .margin_top(px(300.))
1396 });
1397 assert_eq!(surface(cx, 0).top(), px(300.));
1398 }
1399 }
1400
1401 #[gpui::test]
1402 fn alert_dialog_uses_the_same_entrance(cx: &mut TestAppContext) {
1403 for entrance in [
1404 DialogEntrance::SlideDown,
1405 DialogEntrance::Fade,
1406 DialogEntrance::FadeSlide,
1407 DialogEntrance::None,
1408 ] {
1409 let cx = window(cx, size(px(1000.), px(800.)));
1410 cx.update(|window, cx| {
1411 let alert = crate::dialog::AlertDialog::new(cx)
1412 .title("Alert")
1413 .entrance(entrance);
1414 assert_eq!(alert.build_surface(window, cx).props.entrance, entrance);
1415 window.open_alert_dialog(cx, move |alert, _, _| {
1416 alert.title("Alert").entrance(entrance)
1417 });
1418 });
1419 cx.run_until_parked();
1420 cx.update(|window, cx| window.draw(cx).clear(cx));
1421 cx.update(|window, cx| window.draw(cx).clear(cx));
1422 assert_eq!(surface(cx, 0).top(), px(80.));
1423 }
1424 }
1425
1426 #[gpui::test]
1429 fn closing_fades_the_dialog_surface(cx: &mut TestAppContext) {
1430 let cx = window(cx, size(px(1000.), px(800.)));
1431 cx.update(|_, cx| cx.set_reduce_motion(false));
1432 open(cx, |dialog, _, _| {
1433 dialog
1434 .title("Fading")
1435 .child("body")
1436 .margin_top(px(300.))
1437 .entrance(DialogEntrance::Fade)
1438 });
1439 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1440 frame(cx);
1441 cx.update(|window, cx| window.close_dialog(cx));
1442 frame(cx);
1443 assert_eq!(
1444 surface_alpha(cx),
1445 1.0,
1446 "the exit should start fully visible"
1447 );
1448
1449 cx.background_executor
1450 .advance_clock(Duration::from_millis(90));
1451 frame(cx);
1452 let alpha = surface_alpha(cx);
1453 assert!(
1454 alpha > 0.0 && alpha < 1.0,
1455 "the closing surface should fade, but its background is {alpha}"
1456 );
1457 }
1458
1459 #[gpui::test]
1460 fn closing_during_entrance_reverses_from_the_current_sample(cx: &mut TestAppContext) {
1461 for entrance in [
1462 DialogEntrance::SlideDown,
1463 DialogEntrance::Fade,
1464 DialogEntrance::FadeSlide,
1465 ] {
1466 let cx = window(cx, size(px(1000.), px(800.)));
1467 cx.update(|_, cx| cx.set_reduce_motion(false));
1468 open(cx, move |dialog, _, _| {
1469 dialog
1470 .title("Interrupted")
1471 .child("body")
1472 .margin_top(px(300.))
1473 .entrance(entrance)
1474 });
1475 cx.background_executor
1476 .advance_clock(Duration::from_millis(40));
1477 frame(cx);
1478 let before = surface(cx, 0);
1479 let alpha = surface_alpha(cx);
1480 assert!(alpha > 0. && alpha < 1.);
1481 cx.update(|window, cx| window.close_dialog(cx));
1482 frame(cx);
1483 assert_eq!(surface(cx, 0), before, "{entrance:?} jumped on close");
1484 assert!((surface_alpha(cx) - alpha).abs() < 0.001);
1485 cx.background_executor
1486 .advance_clock(Duration::from_millis(20));
1487 frame(cx);
1488 assert!(surface_alpha(cx) < alpha);
1489 assert!(surface(cx, 0).top() <= before.top());
1490 }
1491 }
1492
1493 #[gpui::test]
1494 fn exiting_content_rejects_clicks_focus_and_text_input(cx: &mut TestAppContext) {
1495 use crate::input::{Input, InputState};
1496 use gpui::Focusable as _;
1497
1498 for deferred in [false, true] {
1499 let cx = window(cx, size(px(1000.), px(800.)));
1500 let input = cx.update(|window, cx| cx.new(|cx| InputState::new(window, cx)));
1501 let clicks = Rc::new(Cell::new(0));
1502 let counter = clicks.clone();
1503 let field = input.clone();
1504 cx.update(|_, cx| cx.set_reduce_motion(false));
1505 open(cx, move |dialog, _, _| {
1506 let counter = counter.clone();
1507 dialog
1508 .title("Form")
1509 .child(
1510 div()
1511 .debug_selector(|| "exit-input".into())
1512 .child(Input::new(&field)),
1513 )
1514 .footer(
1515 div().debug_selector(|| "exit-button".into()).child(
1516 Button::new("custom")
1517 .label("Custom action")
1518 .w_full()
1519 .on_click(move |_, _, _| counter.set(counter.get() + 1)),
1520 ),
1521 )
1522 });
1523 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1524 frame(cx);
1525 let button = cx.debug_bounds("exit-button").unwrap().center();
1526 cx.simulate_click(button, gpui::Modifiers::default());
1527 assert_eq!(clicks.get(), 1);
1528 cx.update(|window, cx| input.focus_handle(cx).focus(window, cx));
1529 cx.simulate_input("before");
1530 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1531 cx.update(|window, cx| {
1532 if deferred {
1533 Dialog::defer_close_dialog(window, cx);
1534 } else {
1535 window.close_dialog(cx);
1536 }
1537 });
1538 frame(cx);
1539 let button = cx.debug_bounds("exit-button").unwrap().center();
1540 cx.simulate_click(button, gpui::Modifiers::default());
1541 assert_eq!(clicks.get(), 1, "a closing footer button ran its callback");
1542 let field = cx.debug_bounds("exit-input").unwrap().center();
1543 cx.simulate_click(field, gpui::Modifiers::default());
1544 cx.simulate_input("after");
1545 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1546 for key in ["tab", "shift-tab"] {
1547 cx.simulate_keystrokes(key);
1548 frame(cx);
1549 cx.update(|window, cx| assert!(!input.focus_handle(cx).is_focused(window)));
1550 }
1551 cx.update(|window, cx| input.focus_handle(cx).focus(window, cx));
1553 frame(cx);
1554 cx.update(|window, cx| assert!(!input.focus_handle(cx).is_focused(window)));
1555 cx.simulate_input("after");
1556 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1557 }
1558 }
1559
1560 fn surface_alpha(cx: &mut VisualTestContext) -> f32 {
1562 let bounds = cx.debug_bounds("dialog-0").unwrap();
1563 let scale = cx.update(|window, _| window.scale_factor());
1564 let left = f32::from(bounds.origin.x) * scale;
1565 let top = f32::from(bounds.origin.y) * scale;
1566 let width = f32::from(bounds.size.width) * scale;
1567 let height = f32::from(bounds.size.height) * scale;
1568 cx.update(|window, _| {
1569 window
1570 .painted_quads()
1571 .into_iter()
1572 .filter(|quad| {
1573 (quad.bounds.origin.x.0 - left).abs() < 1.0
1574 && (quad.bounds.origin.y.0 - top).abs() < 1.0
1575 && (quad.bounds.size.width.0 - width).abs() < 1.0
1576 && (quad.bounds.size.height.0 - height).abs() < 1.0
1577 })
1578 .filter_map(|quad| quad.background.as_solid().map(|color| color.a))
1579 .fold(0.0_f32, f32::max)
1580 })
1581 }
1582}