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 IntoElement for BaseDialogRoot {
294 type Element = <gpui_base::Dialog as IntoElement>::Element;
295 fn into_element(self) -> Self::Element {
296 match self {
297 Self::Dialog(root) => root.into_element(),
298 Self::AlertDialog(root) => root.into_element(),
299 }
300 }
301}
302
303#[derive(Clone, Copy, Debug)]
307pub(crate) struct DialogMotion {
308 pub(crate) visibility: f32,
309 pub(crate) closing: bool,
310}
311
312#[derive(IntoElement)]
314pub struct Dialog {
315 base: Option<BaseDialogRoot>,
316 pub(crate) style: StyleRefinement,
317 children: Vec<AnyElement>,
318 trigger: Option<AnyElement>,
319 title: Option<AnyElement>,
320 pub(crate) header: Option<AnyElement>,
321 pub(crate) footer: Option<AnyElement>,
322 pub(crate) content_builder: Option<ContentBuilderFn>,
323 pub(crate) props: DialogProps,
324
325 pub(super) button_props: DialogButtonProps,
326
327 pub(crate) focus_handle: FocusHandle,
329 pub(crate) layer_ix: usize,
330 pub(crate) stack_depth: usize,
332 pub(crate) selection_scope: TextSelectionScopeId,
333 pub(crate) motion: Option<DialogMotion>,
334 pub(crate) id: usize,
335}
336
337pub(crate) fn overlay_color(overlay: bool, cx: &App) -> Hsla {
338 if !overlay {
339 return hsla(0., 0., 0., 0.);
340 }
341
342 cx.theme().overlay
343}
344
345fn dialog_shadow(delta: f32) -> Vec<BoxShadow> {
346 vec![
347 BoxShadow {
348 color: hsla(0., 0., 0., 0.1 * delta),
349 offset: point(px(0.), px(20.)),
350 blur_radius: px(25.),
351 spread_radius: px(-5.),
352 inset: false,
353 },
354 BoxShadow {
355 color: hsla(0., 0., 0., 0.1 * delta),
356 offset: point(px(0.), px(8.)),
357 blur_radius: px(10.),
358 spread_radius: px(-6.),
359 inset: false,
360 },
361 ]
362}
363
364impl Dialog {
365 pub fn new(cx: &mut App) -> Self {
367 Self {
368 base: Some(BaseDialogRoot::Dialog(gpui_base::Dialog::new(cx))),
369 focus_handle: cx.focus_handle(),
370 style: StyleRefinement::default(),
371 trigger: None,
372 title: None,
373 header: None,
374 footer: None,
375 content_builder: None,
376 props: DialogProps::default(),
377 children: Vec::new(),
378 layer_ix: 0,
379 stack_depth: 0,
380 selection_scope: TextSelectionScopeId::default(),
381 button_props: DialogButtonProps::default(),
382 motion: None,
383 id: 0,
384 }
385 }
386
387 pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
391 self.trigger = Some(trigger.into_any_element());
392 self
393 }
394
395 pub fn content<F>(mut self, builder: F) -> Self
397 where
398 F: Fn(DialogContent, &mut Window, &mut App) -> DialogContent + 'static,
399 {
400 self.content_builder = Some(Rc::new(builder));
401 self
402 }
403
404 pub fn title(mut self, title: impl IntoElement) -> Self {
406 self.title = Some(title.into_any_element());
407 self
408 }
409
410 pub(crate) fn header(mut self, header: impl IntoElement) -> Self {
412 self.header = Some(header.into_any_element());
413 self
414 }
415
416 pub fn footer(mut self, footer: impl IntoElement) -> Self {
425 self.footer = Some(footer.into_any_element());
426 self
427 }
428
429 pub fn button_props(mut self, button_props: DialogButtonProps) -> Self {
441 self.button_props.merge(button_props);
442 self
443 }
444
445 pub(crate) fn with_base_alert_dialog(mut self, base: gpui_base::AlertDialog) -> Self {
446 self.base = Some(BaseDialogRoot::AlertDialog(base));
447 self.props.overlay_closable = false;
448 self
449 }
450
451 pub fn on_close(
455 mut self,
456 on_close: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
457 ) -> Self {
458 self.button_props.on_close = Some(Rc::new(on_close));
459 self
460 }
461
462 pub fn on_ok(
466 mut self,
467 on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
468 ) -> Self {
469 self.button_props = self.button_props.on_ok(on_ok);
470 self
471 }
472
473 pub fn on_cancel(
477 mut self,
478 on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
479 ) -> Self {
480 self.button_props = self.button_props.on_cancel(on_cancel);
481 self
482 }
483
484 pub fn close_button(mut self, close_button: bool) -> Self {
486 self.props.close_button = close_button;
487 self
488 }
489
490 pub fn margin_top(mut self, margin_top: impl Into<Pixels>) -> Self {
492 self.props.margin_top = Some(margin_top.into());
493 self
494 }
495
496 pub fn centered(mut self) -> Self {
499 self.props.centered = true;
500 self
501 }
502
503 pub fn w(mut self, width: impl Into<Pixels>) -> Self {
509 self.props.width = width.into();
510 self
511 }
512
513 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
517 self.props.width = width.into();
518 self
519 }
520
521 pub fn max_w(mut self, max_width: impl Into<Pixels>) -> Self {
523 self.props.max_width = Some(max_width.into());
524 self
525 }
526
527 pub fn overlay(mut self, overlay: bool) -> Self {
529 self.props.overlay = overlay;
530 self
531 }
532
533 pub fn overlay_closable(mut self, overlay_closable: bool) -> Self {
537 self.props.overlay_closable = overlay_closable;
538 self
539 }
540
541 pub fn keyboard(mut self, keyboard: bool) -> Self {
543 self.props.keyboard = keyboard;
544 self
545 }
546
547 pub fn entrance(mut self, entrance: DialogEntrance) -> Self {
553 self.props.entrance = entrance;
554 self
555 }
556
557 pub(crate) fn exit_duration(&self, cx: &App) -> Duration {
562 if cx.reduce_motion() {
563 return Duration::ZERO;
564 }
565
566 match self.props.entrance {
567 DialogEntrance::None => Duration::ZERO,
568 DialogEntrance::SlideDown => *ANIMATION_DURATION,
569 _ => cx.theme().motion_tokens().duration_normal,
570 }
571 }
572
573 pub(crate) fn motion_transition(&self, cx: &App) -> Transition {
574 let transition = Transition::new(self.exit_duration(cx));
575 if self.props.entrance == DialogEntrance::SlideDown {
578 transition.ease(cubic_bezier(1. / 3., 0.72, 2. / 3., 1.))
579 } else {
580 let easing = cx.theme().motion_tokens().easing_enter.clone();
581 transition.ease(move |delta| easing.sample(delta).clamp(0., 1.))
582 }
583 }
584
585 pub(crate) fn has_overlay(&self) -> bool {
586 self.props.overlay
587 }
588
589 pub(crate) fn with_props(mut self, props: DialogProps) -> Self {
590 self.props = props;
591 self
592 }
593
594 fn defer_close_dialog(window: &mut Window, cx: &mut App) {
595 WindowState::update(window, cx, |root, window, cx| {
596 root.defer_close_dialog(window, cx);
597 });
598 }
599}
600
601impl ParentElement for Dialog {
602 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
603 self.children.extend(elements);
604 }
605}
606
607impl Styled for Dialog {
608 fn style(&mut self) -> &mut gpui::StyleRefinement {
609 &mut self.style
610 }
611}
612
613impl Dialog {
614 fn render_trigger(self, trigger: AnyElement, _: &mut Window, _: &mut App) -> AnyElement {
615 let content_builder = self.content_builder.clone();
616 let style = self.style.clone();
617 let props = self.props.clone();
618 let button_props = self.button_props.clone();
619
620 gpui_base::DialogTrigger::new(trigger)
621 .on_open(move |window, cx| {
622 let content_builder = content_builder.clone();
623 let style = style.clone();
624 let props = props.clone();
625 let button_props = button_props.clone();
626 window.open_dialog(cx, move |dialog, _, _| {
627 dialog
628 .refine_style(&style)
629 .button_props(button_props.clone())
630 .with_props(props.clone())
631 .content({
632 let content_builder = content_builder.clone();
633 move |content, window, cx| {
634 if let Some(builder) = content_builder.clone() {
635 builder(content, window, cx)
636 } else {
637 content
638 }
639 }
640 })
641 });
642 })
643 .into_any_element()
644 }
645}
646
647impl RenderOnce for Dialog {
648 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
649 if let Some(trigger) = self.trigger.take() {
650 return self.render_trigger(trigger, window, cx);
651 }
652
653 let layer_ix = self.layer_ix;
654 let selection_scope = self.selection_scope;
655 let on_close = self.button_props.close_handler();
656 let on_ok = self.button_props.ok_handler();
657 let on_cancel = self.button_props.cancel_handler();
658
659 let window_paddings = crate::window_border::window_paddings(window);
660 let view_size = window.viewport_size()
661 - gpui::size(
662 window_paddings.left + window_paddings.right,
663 window_paddings.top + window_paddings.bottom,
664 );
665 let margin = cx.theme().spacing_tokens().lg;
671 let layer_offset = px(self.stack_depth as f32 * 16.);
672 let (anchor, y) = if self.props.centered {
673 (Anchor::LeftCenter, view_size.height / 2.)
674 } else {
675 let y = self.props.margin_top.unwrap_or(view_size.height / 10.);
676 (Anchor::TopLeft, y)
677 };
678 let y = y + layer_offset;
679 let entrance = self.props.entrance;
680 let motion = cx.theme().motion_tokens();
681 let closing = self.motion.is_some_and(|motion| motion.closing);
682 let visibility = self
683 .motion
684 .map_or(1.0, |motion| motion.visibility.clamp(0., 1.));
685 let fade_overlay = closing && self.props.overlay_visible;
686 let travel = motion.distance_short.to_pixels(window.rem_size());
687 let width = self
688 .props
689 .width
690 .min((view_size.width - margin * 2.).max(px(0.)));
691 let x = (view_size.width - width) / 2.;
692 let max_height = (view_size.height - margin * 2. - layer_offset).max(px(0.));
693
694 let base_size = window.text_style().font_size;
695 let rem_size = window.rem_size();
696
697 let mut paddings = Edges::all(px(16.));
698 if let Some(pl) = self.style.padding.left {
699 paddings.left = pl.to_pixels(base_size, rem_size);
700 }
701 if let Some(pr) = self.style.padding.right {
702 paddings.right = pr.to_pixels(base_size, rem_size);
703 }
704 if let Some(pt) = self.style.padding.top {
705 paddings.top = pt.to_pixels(base_size, rem_size);
706 }
707 if let Some(pb) = self.style.padding.bottom {
708 paddings.bottom = pb.to_pixels(base_size, rem_size);
709 }
710
711 let topmost = WindowState::read(window, cx)
714 .active_dialogs
715 .iter()
716 .rposition(|dialog| !dialog.closing);
717 let is_topmost = !closing && topmost == Some(layer_ix);
718
719 anchored()
720 .position(point(window_paddings.left, window_paddings.top))
721 .snap_to_window()
722 .child(
723 div()
724 .id("dialog")
725 .test_support()
726 .when(!closing, |this| this.occlude())
729 .w(view_size.width)
730 .h(view_size.height)
731 .when(fade_overlay, |this| {
732 this.child(div().absolute().inset_0().bg(overlay_color(true, cx)))
733 })
734 .child(
735 self.base
736 .take()
737 .expect("Dialog base host is always present")
738 .layer(self.id, is_topmost)
739 .focus_handle(self.focus_handle.clone())
740 .close_on_escape(self.props.keyboard && !closing)
741 .close_on_backdrop_press(self.props.overlay_closable && !closing)
742 .dismiss_below_y(TITLE_BAR_HEIGHT)
743 .when(self.props.overlay && !closing, |this| {
744 this.backdrop(
745 div()
746 .absolute()
747 .size_full()
748 .window_control_area(WindowControlArea::Drag)
749 .when(self.props.overlay_visible, |overlay| {
750 overlay.bg(overlay_color(true, cx))
751 }),
752 )
753 })
754 .on_ok(move |event, window, cx| !closing && on_ok(event, window, cx))
755 .on_cancel(move |event, window, cx| {
756 !closing && on_cancel(event, window, cx)
757 })
758 .on_close(move |event, window, cx| on_close(event, window, cx))
759 .request_close(move |deferred, window, cx| {
760 if closing {
763 return;
764 }
765 if deferred {
766 Self::defer_close_dialog(window, cx);
767 } else {
768 window.close_dialog(cx);
769 }
770 })
771 .popup(
772 gpui_base::Positioner::corner(
773 anchor,
774 point(window_paddings.left + x, window_paddings.top + y),
775 )
776 .margin(margin)
777 .child(
778 v_flex()
779 .id("surface")
780 .test_support()
781 .debug_selector(move || format!("dialog-{layer_ix}"))
782 .bg(cx.theme().tokens.background)
783 .border_1()
784 .border_color(cx.theme().border)
785 .rounded(cx.theme().radius_lg)
786 .min_h_24()
787 .pt(paddings.top)
788 .pb(paddings.bottom)
789 .gap(paddings.top.max(px(8.)))
790 .refine_style(&self.style)
791 .px_0()
792 .occlude()
793 .w(width)
794 .when_some(self.props.max_width, |this, w| this.max_w(w))
795 .max_h(max_height)
796 .child(
797 v_flex()
798 .flex_1()
799 .overflow_hidden()
800 .gap_y_2()
801 .when_some(self.header, |this, header| {
802 this.child(
803 div()
804 .pl(paddings.left)
805 .pr(paddings.right)
806 .child(header),
807 )
808 })
809 .when_some(self.title, |this, title| {
810 this.child(
811 DialogTitle::new()
812 .pl(paddings.left)
813 .pr(paddings.right)
814 .child(title),
815 )
816 })
817 .when_some(self.content_builder, |this, builder| {
818 this.child(builder(
819 DialogContent::new()
820 .gap(paddings.bottom)
821 .pl(paddings.left)
822 .pr(paddings.right),
823 window,
824 cx,
825 ))
826 })
827 .when(!self.children.is_empty(), |this| {
828 this.child(
829 div().flex_1().overflow_hidden().child(
830 v_flex()
832 .size_full()
833 .overflow_y_scrollbar()
834 .pl(paddings.left)
835 .pr(paddings.right)
836 .children(self.children),
837 ),
838 )
839 }),
840 )
841 .when_some(self.footer, |this, footer| {
842 this.child(
843 div()
844 .pl(paddings.left)
845 .pr(paddings.right)
846 .child(footer),
847 )
848 })
849 .children(self.props.close_button.then(|| {
850 let top = (paddings.top - px(10.)).max(px(8.));
851 let right = (paddings.right - px(10.)).max(px(8.));
852
853 gpui_base::DialogClose::new()
854 .absolute()
855 .top(top)
856 .inset_e(right, cx)
857 .trigger(|button| {
858 Button::new("close")
859 .with_base(button)
860 .small()
861 .ghost()
862 .icon(IconName::Close)
863 .accessibility_label("Close")
864 })
865 }))
866 .when(closing, |surface| {
867 surface
870 .capture_any_mouse_down(|_, _, cx| {
871 cx.stop_propagation()
872 })
873 .capture_any_mouse_up(|_, _, cx| {
874 cx.stop_propagation()
875 })
876 .capture_key_down(|_, window, cx| {
877 window.prevent_default();
878 cx.stop_propagation();
879 })
880 .capture_key_up(|_, _, cx| cx.stop_propagation())
881 .child(
882 div()
883 .absolute()
884 .inset_0()
885 .occlude()
886 .on_any_mouse_down(|_, _, cx| {
887 cx.stop_propagation()
888 })
889 .on_scroll(|_, _, cx| {
890 cx.stop_propagation()
891 }),
892 )
893 })
894 .opacity(visibility)
897 .shadow(dialog_shadow(visibility))
898 .text_selection_scope(selection_scope)
899 .map(|surface| {
900 if entrance == DialogEntrance::FadeSlide {
901 let mut surface = EntranceSurface::new(
902 surface.into_any_element(),
903 travel,
904 window_paddings.top + margin,
905 );
906 surface.progress = visibility;
907 surface.into_any_element()
908 } else {
909 surface.into_any_element()
910 }
911 }),
912 )
913 .when(
914 entrance == DialogEntrance::SlideDown,
915 |positioner| {
916 positioner.position(point(
917 window_paddings.left + x,
918 window_paddings.top + y * visibility,
919 ))
920 },
921 ),
922 ),
923 )
924 .opacity(visibility),
925 )
926 .into_any_element()
927 }
928}
929
930#[cfg(test)]
931pub(crate) mod tests {
932 use super::*;
933 use gpui::{
934 AppContext as _, Bounds, Context, Render, StatefulInteractiveElement as _, TestAppContext,
935 VisualTestContext, size,
936 };
937 use std::{cell::Cell, rc::Rc};
938
939 struct DialogHost {
940 clicks: Rc<Cell<usize>>,
941 }
942
943 impl Render for DialogHost {
944 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
945 let clicks = self.clicks.clone();
946 div().size_full().child(
947 div()
950 .id("background-target")
951 .absolute()
952 .top_0()
953 .left_0()
954 .w_full()
955 .h(px(200.))
956 .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
957 )
958 }
959 }
960
961 pub(crate) fn window(
964 cx: &mut TestAppContext,
965 window_size: gpui::Size<Pixels>,
966 ) -> &mut VisualTestContext {
967 let (cx, _) = window_with_click_count(cx, window_size);
968 cx
969 }
970
971 fn window_with_click_count(
974 cx: &mut TestAppContext,
975 window_size: gpui::Size<Pixels>,
976 ) -> (&mut VisualTestContext, Rc<Cell<usize>>) {
977 cx.update(|cx| {
978 crate::init(cx);
979 cx.set_reduce_motion(true);
980 });
981 let clicks = Rc::new(Cell::new(0));
982 let counter = clicks.clone();
983 let (_, cx) = cx.add_window_view(|window, cx| {
984 let view = cx.new(|_| DialogHost { clicks: counter });
985 crate::Root::new(view, window, cx)
986 });
987 cx.simulate_resize(window_size);
988 cx.update(|window, cx| window.draw(cx).clear(cx));
989 (cx, clicks)
990 }
991
992 fn open(
993 cx: &mut VisualTestContext,
994 build: impl Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
995 ) {
996 cx.update(|window, cx| window.open_dialog(cx, build));
997 cx.run_until_parked();
998 cx.update(|window, cx| window.draw(cx).clear(cx));
1000 cx.update(|window, cx| window.draw(cx).clear(cx));
1001 }
1002
1003 fn frame(cx: &mut VisualTestContext) {
1006 cx.update(|window, _| window.refresh());
1007 cx.run_until_parked();
1008 }
1009
1010 fn surface(cx: &mut VisualTestContext, layer_ix: usize) -> Bounds<Pixels> {
1011 let selector = ["dialog-0", "dialog-1"][layer_ix];
1012 cx.debug_bounds(selector)
1013 .unwrap_or_else(|| panic!("dialog layer {layer_ix} was not painted"))
1014 }
1015
1016 #[gpui::test]
1019 fn a_dialog_that_fits_keeps_its_default_width_and_top_offset(cx: &mut TestAppContext) {
1020 let cx = window(cx, size(px(1000.), px(800.)));
1021 open(cx, |dialog, _, _| dialog.title("Fits").child("body"));
1022
1023 let bounds = surface(cx, 0);
1024 assert_eq!(bounds.size.width, px(448.));
1025 assert_eq!(bounds.origin.x, px(276.));
1026 assert_eq!(bounds.origin.y, px(80.));
1027 }
1028
1029 #[gpui::test]
1034 fn a_dialog_larger_than_the_window_stays_inside_it(cx: &mut TestAppContext) {
1035 let viewport = size(px(400.), px(300.));
1036 let cx = window(cx, viewport);
1037 open(cx, |dialog, _, _| {
1038 dialog
1039 .w(px(800.))
1040 .title("Too big")
1041 .child(div().h(px(1000.)).child("tall body"))
1042 .footer(div().h(px(32.)).debug_selector(|| "footer-probe".into()))
1043 });
1044
1045 let bounds = surface(cx, 0);
1046 let footer = cx.debug_bounds("footer-probe").unwrap();
1047 let margin = px(16.);
1048 assert!(
1049 bounds.origin.x >= margin && bounds.right() <= viewport.width - margin,
1050 "the dialog ran off the sides: {bounds:?}"
1051 );
1052 assert!(
1053 bounds.bottom() <= viewport.height - margin,
1054 "the dialog ran off the bottom: {bounds:?}"
1055 );
1056 assert_eq!(bounds.origin.y, margin);
1057 assert!(
1058 footer.bottom() <= bounds.bottom(),
1059 "the footer was clipped below the dialog: footer {footer:?}, dialog {bounds:?}"
1060 );
1061 }
1062
1063 #[gpui::test]
1065 fn dialog_button_props_merge_with_what_the_dialog_already_carries(cx: &mut TestAppContext) {
1066 let cx = window(cx, size(px(400.), px(300.)));
1067 cx.update(|_, cx| {
1068 let dialog = Dialog::new(cx)
1069 .button_props(DialogButtonProps::default().cancel_text("Keep"))
1070 .button_props(DialogButtonProps::default().ok_text("Delete"))
1071 .button_props(DialogButtonProps::default().ok_variant(ButtonVariant::Danger));
1072
1073 assert_eq!(dialog.button_props.ok_text.as_deref(), Some("Delete"));
1074 assert_eq!(dialog.button_props.cancel_text.as_deref(), Some("Keep"));
1075 assert_eq!(dialog.button_props.ok_variant, Some(ButtonVariant::Danger));
1076 });
1077 }
1078
1079 #[gpui::test]
1082 fn stacked_dialogs_each_fit_the_window(cx: &mut TestAppContext) {
1083 let viewport = size(px(400.), px(300.));
1084 let cx = window(cx, viewport);
1085 open(cx, |dialog, _, _| {
1086 dialog.title("First").child(div().h(px(1000.)))
1087 });
1088 open(cx, |dialog, _, _| {
1089 dialog.title("Second").child(div().h(px(1000.)))
1090 });
1091
1092 let first = surface(cx, 0);
1093 let second = surface(cx, 1);
1094 assert_eq!(second.origin.y, first.origin.y + px(16.));
1095 assert!(first.bottom() <= viewport.height - px(16.), "{first:?}");
1096 assert!(second.bottom() <= viewport.height - px(16.), "{second:?}");
1097 assert!(second.size.height < first.size.height);
1098 }
1099
1100 #[gpui::test]
1101 fn test_dialog_entrance_builder(cx: &mut TestAppContext) {
1102 cx.update(crate::init);
1103 cx.update(|cx| {
1104 assert_eq!(Dialog::new(cx).props.entrance, DialogEntrance::SlideDown);
1105 for entrance in [
1106 DialogEntrance::SlideDown,
1107 DialogEntrance::Fade,
1108 DialogEntrance::FadeSlide,
1109 DialogEntrance::None,
1110 ] {
1111 assert_eq!(Dialog::new(cx).entrance(entrance).props.entrance, entrance);
1112 }
1113 });
1114 }
1115
1116 #[gpui::test]
1117 fn reduced_motion_displays_every_entrance_at_rest(cx: &mut TestAppContext) {
1118 for entrance in [
1119 DialogEntrance::SlideDown,
1120 DialogEntrance::Fade,
1121 DialogEntrance::FadeSlide,
1122 DialogEntrance::None,
1123 ] {
1124 let cx = window(cx, size(px(1000.), px(800.)));
1125 open(cx, move |dialog, _, _| {
1126 dialog
1127 .title("Entrance")
1128 .child("body")
1129 .entrance(entrance)
1130 .margin_top(px(300.))
1131 });
1132 assert_eq!(surface(cx, 0).top(), px(300.));
1133 }
1134 }
1135
1136 #[gpui::test]
1137 fn no_entrance_displays_immediately_and_keeps_keyboard_dismissal(cx: &mut TestAppContext) {
1138 let cx = window(cx, size(px(1000.), px(800.)));
1139 cx.update(|_, cx| cx.set_reduce_motion(false));
1140 open(cx, |dialog, _, _| {
1141 dialog
1142 .title("Immediate")
1143 .child("body")
1144 .entrance(DialogEntrance::None)
1145 .margin_top(px(300.))
1146 });
1147 assert_eq!(surface(cx, 0).top(), px(300.));
1148 cx.simulate_keystrokes("escape");
1149 cx.update(|window, cx| assert!(WindowState::read(window, cx).active_dialogs.is_empty()));
1150 }
1151
1152 #[gpui::test]
1155 fn closing_plays_the_entrance_backwards_before_the_dialog_unmounts(cx: &mut TestAppContext) {
1156 let cx = window(cx, size(px(1000.), px(800.)));
1157 cx.update(|_, cx| cx.set_reduce_motion(false));
1158 open(cx, |dialog, _, _| {
1159 dialog.title("Closing").child("body").margin_top(px(300.))
1160 });
1161
1162 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1163 frame(cx);
1164 cx.update(|window, cx| window.close_dialog(cx));
1165 frame(cx);
1166 cx.update(|window, cx| {
1169 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1);
1170 assert!(!window.has_active_dialog(cx));
1171 });
1172 assert_eq!(surface(cx, 0).top(), px(300.));
1173
1174 cx.background_executor
1176 .advance_clock(*ANIMATION_DURATION / 2);
1177 frame(cx);
1178 cx.update(|window, cx| assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1));
1179 let halfway = surface(cx, 0).top();
1180 assert!(
1181 halfway > px(0.) && halfway < px(300.),
1182 "the closing dialog should slide back up: {halfway:?}"
1183 );
1184
1185 cx.background_executor
1187 .advance_clock(*ANIMATION_DURATION / 2 + Duration::from_millis(1));
1188 frame(cx);
1189 cx.update(|window, cx| {
1190 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1191 assert!(!window.has_active_dialog(cx));
1192 });
1193 assert!(cx.debug_bounds("dialog-0").is_none());
1194 }
1195
1196 #[gpui::test]
1197 fn reduced_motion_closes_in_a_single_frame(cx: &mut TestAppContext) {
1198 let cx = window(cx, size(px(1000.), px(800.)));
1199 open(cx, |dialog, _, _| dialog.title("Reduced").child("body"));
1200 cx.update(|window, cx| window.close_dialog(cx));
1201 cx.update(|window, cx| {
1202 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1203 assert!(!window.has_active_dialog(cx));
1204 });
1205 }
1206
1207 #[gpui::test]
1208 fn zero_theme_duration_closes_fade_entrances_immediately(cx: &mut TestAppContext) {
1209 for entrance in [DialogEntrance::Fade, DialogEntrance::FadeSlide] {
1210 let cx = window(cx, size(px(1000.), px(800.)));
1211 cx.update(|_, cx| {
1212 cx.set_reduce_motion(false);
1213 crate::Theme::update(cx, |theme| theme.motion.duration_normal = Duration::ZERO);
1214 });
1215 open(cx, move |dialog, _, _| {
1216 dialog.title("Immediate").child("body").entrance(entrance)
1217 });
1218 cx.update(|window, cx| window.close_dialog(cx));
1219 cx.update(|window, cx| {
1220 assert!(WindowState::read(window, cx).active_dialogs.is_empty());
1221 assert!(!window.has_active_dialog(cx));
1222 });
1223 }
1224 }
1225
1226 #[gpui::test]
1229 fn reopening_during_the_exit_keeps_the_new_dialog(cx: &mut TestAppContext) {
1230 let cx = window(cx, size(px(1000.), px(800.)));
1231 cx.update(|_, cx| cx.set_reduce_motion(false));
1232 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1233 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1234 frame(cx);
1235 cx.update(|window, cx| window.close_dialog(cx));
1236 frame(cx);
1237
1238 open(cx, |dialog, _, _| dialog.title("Second").child("body"));
1239 cx.update(|window, cx| {
1240 let state = WindowState::read(window, cx);
1241 assert_eq!(state.active_dialogs.len(), 2);
1242 assert!(state.active_dialogs[0].closing);
1243 assert!(!state.active_dialogs[1].closing);
1244 assert!(
1245 state.active_dialogs[1].focus_handle().is_focused(window),
1246 "the reopened dialog owns focus while the old one leaves"
1247 );
1248 });
1249
1250 cx.background_executor
1251 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1252 frame(cx);
1253 frame(cx);
1255 cx.update(|window, cx| {
1256 let state = WindowState::read(window, cx);
1257 assert_eq!(state.active_dialogs.len(), 1);
1258 assert!(!state.active_dialogs[0].closing);
1259 assert!(state.active_dialogs[0].focus_handle().is_focused(window));
1260 assert!(window.has_active_dialog(cx));
1261 });
1262 assert_eq!(surface(cx, 0).top(), px(80.));
1263 assert!(cx.debug_bounds("dialog-1").is_none());
1264 }
1265
1266 #[gpui::test]
1270 fn a_closing_dialog_does_not_offset_the_next_one(cx: &mut TestAppContext) {
1271 for body_height in [px(40.), px(1000.)] {
1272 let cx = window(cx, size(px(1000.), px(800.)));
1273 cx.update(|_, cx| cx.set_reduce_motion(false));
1274 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1275 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1276 frame(cx);
1277 cx.update(|window, cx| window.close_dialog(cx));
1278 frame(cx);
1279
1280 open(cx, move |dialog, _, _| {
1281 dialog
1282 .title("Second")
1283 .child(div().h(body_height))
1284 .entrance(DialogEntrance::None)
1285 });
1286 let during_exit = surface(cx, 1);
1287
1288 cx.background_executor
1289 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1290 frame(cx);
1291 frame(cx);
1292 assert!(cx.debug_bounds("dialog-1").is_none());
1293 assert_eq!(during_exit, surface(cx, 0));
1294 }
1295 }
1296
1297 #[gpui::test]
1300 fn closing_the_top_dialog_leaves_the_one_below_mounted(cx: &mut TestAppContext) {
1301 let cx = window(cx, size(px(1000.), px(800.)));
1302 cx.update(|_, cx| cx.set_reduce_motion(false));
1303 open(cx, |dialog, _, _| dialog.title("First").child("body"));
1304 open(cx, |dialog, _, _| dialog.title("Second").child("body"));
1305
1306 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1307 frame(cx);
1308 cx.update(|window, cx| window.close_dialog(cx));
1309 frame(cx);
1310 cx.update(|window, cx| {
1311 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 2);
1312 assert!(window.has_active_dialog(cx));
1313 });
1314 assert!(
1315 cx.debug_bounds("dialog-0").is_some(),
1316 "the lower dialog stays"
1317 );
1318 assert!(
1319 cx.debug_bounds("dialog-1").is_some(),
1320 "the closing dialog still paints its exit"
1321 );
1322
1323 cx.background_executor
1324 .advance_clock(*ANIMATION_DURATION + Duration::from_millis(1));
1325 frame(cx);
1326 cx.update(|window, cx| {
1327 assert_eq!(WindowState::read(window, cx).active_dialogs.len(), 1);
1328 assert!(window.has_active_dialog(cx));
1329 });
1330 assert!(cx.debug_bounds("dialog-0").is_some());
1331 assert!(cx.debug_bounds("dialog-1").is_none());
1332 }
1333
1334 #[gpui::test]
1337 fn closing_dialog_does_not_block_input_beneath_it(cx: &mut TestAppContext) {
1338 let (cx, clicks) = window_with_click_count(cx, size(px(1000.), px(800.)));
1339 cx.update(|_, cx| cx.set_reduce_motion(false));
1340 open(cx, |dialog, _, _| {
1341 dialog
1342 .title("Closing")
1343 .child("body")
1344 .margin_top(px(300.))
1345 .overlay_closable(false)
1346 });
1347
1348 let backdrop_point = point(px(100.), px(60.));
1351 cx.simulate_click(backdrop_point, gpui::Modifiers::default());
1352 assert_eq!(clicks.get(), 0, "an open dialog blocked the application");
1353
1354 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1355 frame(cx);
1356 cx.update(|window, cx| window.close_dialog(cx));
1357 frame(cx);
1358 cx.simulate_click(backdrop_point, gpui::Modifiers::default());
1359 assert_eq!(
1360 clicks.get(),
1361 1,
1362 "the closing dialog swallowed a press meant for the application"
1363 );
1364 }
1365
1366 #[gpui::test]
1367 fn zero_theme_duration_displays_fade_entrances_immediately(cx: &mut TestAppContext) {
1368 for entrance in [DialogEntrance::Fade, DialogEntrance::FadeSlide] {
1369 let cx = window(cx, size(px(1000.), px(800.)));
1370 cx.update(|_, cx| {
1371 cx.set_reduce_motion(false);
1372 crate::Theme::update(cx, |theme| theme.motion.duration_normal = Duration::ZERO);
1373 });
1374 open(cx, move |dialog, _, _| {
1375 dialog
1376 .title("Immediate")
1377 .child("body")
1378 .entrance(entrance)
1379 .margin_top(px(300.))
1380 });
1381 assert_eq!(surface(cx, 0).top(), px(300.));
1382 }
1383 }
1384
1385 #[gpui::test]
1386 fn alert_dialog_uses_the_same_entrance(cx: &mut TestAppContext) {
1387 for entrance in [
1388 DialogEntrance::SlideDown,
1389 DialogEntrance::Fade,
1390 DialogEntrance::FadeSlide,
1391 DialogEntrance::None,
1392 ] {
1393 let cx = window(cx, size(px(1000.), px(800.)));
1394 cx.update(|window, cx| {
1395 let alert = crate::dialog::AlertDialog::new(cx)
1396 .title("Alert")
1397 .entrance(entrance);
1398 assert_eq!(alert.build_surface(window, cx).props.entrance, entrance);
1399 window.open_alert_dialog(cx, move |alert, _, _| {
1400 alert.title("Alert").entrance(entrance)
1401 });
1402 });
1403 cx.run_until_parked();
1404 cx.update(|window, cx| window.draw(cx).clear(cx));
1405 cx.update(|window, cx| window.draw(cx).clear(cx));
1406 assert_eq!(surface(cx, 0).top(), px(80.));
1407 }
1408 }
1409
1410 #[gpui::test]
1413 fn closing_fades_the_dialog_surface(cx: &mut TestAppContext) {
1414 let cx = window(cx, size(px(1000.), px(800.)));
1415 cx.update(|_, cx| cx.set_reduce_motion(false));
1416 open(cx, |dialog, _, _| {
1417 dialog
1418 .title("Fading")
1419 .child("body")
1420 .margin_top(px(300.))
1421 .entrance(DialogEntrance::Fade)
1422 });
1423 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1424 frame(cx);
1425 cx.update(|window, cx| window.close_dialog(cx));
1426 frame(cx);
1427 assert_eq!(
1428 surface_alpha(cx),
1429 1.0,
1430 "the exit should start fully visible"
1431 );
1432
1433 cx.background_executor
1434 .advance_clock(Duration::from_millis(90));
1435 frame(cx);
1436 let alpha = surface_alpha(cx);
1437 assert!(
1438 alpha > 0.0 && alpha < 1.0,
1439 "the closing surface should fade, but its background is {alpha}"
1440 );
1441 }
1442
1443 #[gpui::test]
1444 fn closing_during_entrance_reverses_from_the_current_sample(cx: &mut TestAppContext) {
1445 for entrance in [
1446 DialogEntrance::SlideDown,
1447 DialogEntrance::Fade,
1448 DialogEntrance::FadeSlide,
1449 ] {
1450 let cx = window(cx, size(px(1000.), px(800.)));
1451 cx.update(|_, cx| cx.set_reduce_motion(false));
1452 open(cx, move |dialog, _, _| {
1453 dialog
1454 .title("Interrupted")
1455 .child("body")
1456 .margin_top(px(300.))
1457 .entrance(entrance)
1458 });
1459 cx.background_executor
1460 .advance_clock(Duration::from_millis(40));
1461 frame(cx);
1462 let before = surface(cx, 0);
1463 let alpha = surface_alpha(cx);
1464 assert!(alpha > 0. && alpha < 1.);
1465 cx.update(|window, cx| window.close_dialog(cx));
1466 frame(cx);
1467 assert_eq!(surface(cx, 0), before, "{entrance:?} jumped on close");
1468 assert!((surface_alpha(cx) - alpha).abs() < 0.001);
1469 cx.background_executor
1470 .advance_clock(Duration::from_millis(20));
1471 frame(cx);
1472 assert!(surface_alpha(cx) < alpha);
1473 assert!(surface(cx, 0).top() <= before.top());
1474 }
1475 }
1476
1477 #[gpui::test]
1478 fn exiting_content_rejects_clicks_focus_and_text_input(cx: &mut TestAppContext) {
1479 use crate::input::{Input, InputState};
1480 use gpui::Focusable as _;
1481
1482 for deferred in [false, true] {
1483 let cx = window(cx, size(px(1000.), px(800.)));
1484 let input = cx.update(|window, cx| cx.new(|cx| InputState::new(window, cx)));
1485 let clicks = Rc::new(Cell::new(0));
1486 let counter = clicks.clone();
1487 let field = input.clone();
1488 cx.update(|_, cx| cx.set_reduce_motion(false));
1489 open(cx, move |dialog, _, _| {
1490 let counter = counter.clone();
1491 dialog
1492 .title("Form")
1493 .child(
1494 div()
1495 .debug_selector(|| "exit-input".into())
1496 .child(Input::new(&field)),
1497 )
1498 .footer(
1499 div().debug_selector(|| "exit-button".into()).child(
1500 Button::new("custom")
1501 .label("Custom action")
1502 .w_full()
1503 .on_click(move |_, _, _| counter.set(counter.get() + 1)),
1504 ),
1505 )
1506 });
1507 cx.background_executor.advance_clock(*ANIMATION_DURATION);
1508 frame(cx);
1509 let button = cx.debug_bounds("exit-button").unwrap().center();
1510 cx.simulate_click(button, gpui::Modifiers::default());
1511 assert_eq!(clicks.get(), 1);
1512 cx.update(|window, cx| input.focus_handle(cx).focus(window, cx));
1513 cx.simulate_input("before");
1514 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1515 cx.update(|window, cx| {
1516 if deferred {
1517 Dialog::defer_close_dialog(window, cx);
1518 } else {
1519 window.close_dialog(cx);
1520 }
1521 });
1522 frame(cx);
1523 let button = cx.debug_bounds("exit-button").unwrap().center();
1524 cx.simulate_click(button, gpui::Modifiers::default());
1525 assert_eq!(clicks.get(), 1, "a closing footer button ran its callback");
1526 let field = cx.debug_bounds("exit-input").unwrap().center();
1527 cx.simulate_click(field, gpui::Modifiers::default());
1528 cx.simulate_input("after");
1529 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1530 for key in ["tab", "shift-tab"] {
1531 cx.simulate_keystrokes(key);
1532 frame(cx);
1533 cx.update(|window, cx| assert!(!input.focus_handle(cx).is_focused(window)));
1534 }
1535 cx.update(|window, cx| input.focus_handle(cx).focus(window, cx));
1537 frame(cx);
1538 cx.update(|window, cx| assert!(!input.focus_handle(cx).is_focused(window)));
1539 cx.simulate_input("after");
1540 assert_eq!(input.read_with(cx, |input, _| input.value()), "before");
1541 }
1542 }
1543
1544 fn surface_alpha(cx: &mut VisualTestContext) -> f32 {
1546 let bounds = cx.debug_bounds("dialog-0").unwrap();
1547 let scale = cx.update(|window, _| window.scale_factor());
1548 let left = f32::from(bounds.origin.x) * scale;
1549 let top = f32::from(bounds.origin.y) * scale;
1550 let width = f32::from(bounds.size.width) * scale;
1551 let height = f32::from(bounds.size.height) * scale;
1552 cx.update(|window, _| {
1553 window
1554 .painted_quads()
1555 .into_iter()
1556 .filter(|quad| {
1557 (quad.bounds.origin.x.0 - left).abs() < 1.0
1558 && (quad.bounds.origin.y.0 - top).abs() < 1.0
1559 && (quad.bounds.size.width.0 - width).abs() < 1.0
1560 && (quad.bounds.size.height.0 - height).abs() < 1.0
1561 })
1562 .filter_map(|quad| quad.background.as_solid().map(|color| color.a))
1563 .fold(0.0_f32, f32::max)
1564 })
1565 }
1566}