Skip to main content

gpui_base/
dialog.rs

1use crate::TestSupportExt as _;
2use std::{
3    cell::{Cell, RefCell},
4    rc::Rc,
5};
6
7use gpui::{
8    AnyElement, App, ClickEvent, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding,
9    MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString,
10    StatefulInteractiveElement as _, StyleRefinement, Styled, Window, anchored, deferred, div,
11    point, prelude::FluentBuilder as _, px,
12};
13use smallvec::SmallVec;
14
15use crate::actions::{Cancel, Confirm};
16use crate::{FocusTrapElement as _, StyledExt as _};
17
18const CONTEXT: &str = "Dialog";
19type Decision = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool>;
20type Closed = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
21type CloseRequest = Rc<dyn Fn(bool, &mut Window, &mut App)>;
22type OpenRequest = Rc<dyn Fn(&mut Window, &mut App)>;
23type OpenChange = Rc<dyn Fn(bool, DialogChangeReason, &mut Window, &mut App)>;
24
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
26pub enum DialogChangeReason {
27    TriggerPress,
28    BackdropPress,
29    Cancel,
30    Confirm,
31    Imperative,
32}
33
34#[derive(Clone)]
35pub struct DialogHandle {
36    open: Rc<Cell<bool>>,
37    on_open_change: Rc<RefCell<Option<OpenChange>>>,
38}
39
40impl DialogHandle {
41    pub fn new(open: bool) -> Self {
42        Self {
43            open: Rc::new(Cell::new(open)),
44            on_open_change: Rc::new(RefCell::new(None)),
45        }
46    }
47    pub fn is_open(&self) -> bool {
48        self.open.get()
49    }
50    pub fn open(&self, window: &mut Window, cx: &mut App) {
51        self.set_open(true, DialogChangeReason::Imperative, window, cx);
52    }
53    pub fn close(&self, window: &mut Window, cx: &mut App) {
54        self.set_open(false, DialogChangeReason::Imperative, window, cx);
55    }
56    pub(crate) fn set_open(
57        &self,
58        open: bool,
59        reason: DialogChangeReason,
60        window: &mut Window,
61        cx: &mut App,
62    ) {
63        if self.open.replace(open) == open {
64            return;
65        }
66        let callback = self.on_open_change.borrow().clone();
67        if let Some(callback) = callback {
68            callback(open, reason, window, cx);
69        }
70        window.refresh();
71    }
72}
73
74fn request_open_change(
75    handle: &Option<DialogHandle>,
76    callback: &Option<OpenChange>,
77    open: bool,
78    reason: DialogChangeReason,
79    window: &mut Window,
80    cx: &mut App,
81) {
82    if let Some(handle) = handle {
83        handle.set_open(open, reason, window, cx);
84    } else if let Some(callback) = callback {
85        callback(open, reason, window, cx);
86    }
87}
88
89pub fn init(cx: &mut App) {
90    cx.bind_keys([
91        KeyBinding::new("escape", Cancel, Some(CONTEXT)),
92        KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
93    ]);
94}
95
96impl Dialog {
97    pub fn on_ok(
98        mut self,
99        handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
100    ) -> Self {
101        self.on_ok = Rc::new(handler);
102        self
103    }
104
105    pub fn on_cancel(
106        mut self,
107        handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
108    ) -> Self {
109        self.on_cancel = Rc::new(handler);
110        self
111    }
112
113    pub fn on_close(
114        mut self,
115        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
116    ) -> Self {
117        self.on_close = Rc::new(handler);
118        self
119    }
120}
121
122/// Unstyled modal host owning focus, keyboard actions, dismissal, and callback ordering.
123#[derive(IntoElement)]
124pub struct Dialog {
125    style: StyleRefinement,
126    focus: FocusHandle,
127    role: Role,
128    accessibility_label: Option<SharedString>,
129    accessibility_description: Option<SharedString>,
130    layer: usize,
131    keyboard: bool,
132    overlay_closable: bool,
133    topmost: bool,
134    dismiss_below_y: Pixels,
135    backdrop: Option<AnyElement>,
136    popup: Option<AnyElement>,
137    children: SmallVec<[AnyElement; 2]>,
138    on_ok: Decision,
139    on_cancel: Decision,
140    on_close: Closed,
141    request_close: CloseRequest,
142    handle: Option<DialogHandle>,
143    open: bool,
144    on_open_change: Option<OpenChange>,
145}
146
147/// Unstyled trigger that owns pointer activation for opening a dialog.
148#[derive(IntoElement)]
149pub struct DialogTrigger {
150    trigger: AnyElement,
151    open: OpenRequest,
152    handle: Option<DialogHandle>,
153}
154
155impl DialogTrigger {
156    pub fn new(trigger: impl IntoElement) -> Self {
157        Self {
158            trigger: trigger.into_any_element(),
159            open: Rc::new(|_, _| {}),
160            handle: None,
161        }
162    }
163    pub fn handle(mut self, handle: DialogHandle) -> Self {
164        self.handle = Some(handle);
165        self
166    }
167
168    pub fn on_open(mut self, open: impl Fn(&mut Window, &mut App) + 'static) -> Self {
169        self.open = Rc::new(open);
170        self
171    }
172}
173
174impl RenderOnce for DialogTrigger {
175    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
176        div()
177            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
178                if let Some(handle) = self.handle.as_ref() {
179                    handle.set_open(true, DialogChangeReason::TriggerPress, window, cx);
180                }
181                (self.open)(window, cx);
182                cx.stop_propagation();
183            })
184            .child(self.trigger)
185    }
186}
187
188macro_rules! dialog_part {
189    ($(#[$meta:meta])* $name:ident, $id:literal) => {
190        dialog_part!($(#[$meta])* $name, $id, false);
191    };
192    ($(#[$meta:meta])* $name:ident, $id:literal, $occlude:literal) => {
193        $(#[$meta])*
194        #[derive(IntoElement)]
195        pub struct $name {
196            style: StyleRefinement,
197            children: SmallVec<[AnyElement; 2]>,
198        }
199
200        impl $name {
201            pub fn new() -> Self {
202                Self {
203                    style: StyleRefinement::default(),
204                    children: SmallVec::new(),
205                }
206            }
207        }
208
209        impl Default for $name {
210            fn default() -> Self {
211                Self::new()
212            }
213        }
214
215        impl Styled for $name {
216            fn style(&mut self) -> &mut StyleRefinement {
217                &mut self.style
218            }
219        }
220
221        impl ParentElement for $name {
222            fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
223                self.children.extend(elements);
224            }
225        }
226
227        impl RenderOnce for $name {
228            fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
229                div()
230                    .id($id)
231                    // The popup sits over the backdrop, whose press dismisses
232                    // the dialog, so it keeps presses on itself from falling through.
233                    .when($occlude, |this| this.occlude())
234                    .children(self.children)
235                    .refine_style(&self.style)
236            }
237        }
238    };
239}
240
241dialog_part!(
242    /// Unstyled backdrop part rendered behind a dialog popup.
243    DialogBackdrop,
244    "dialog-backdrop"
245);
246
247dialog_part!(
248    /// Unstyled popup part containing dialog content.
249    DialogPopup,
250    "dialog-popup",
251    true
252);
253
254/// Unstyled title slot for a dialog surface.
255#[derive(IntoElement)]
256pub struct DialogTitle {
257    base: gpui::Div,
258    style: StyleRefinement,
259    children: SmallVec<[AnyElement; 2]>,
260}
261
262impl DialogTitle {
263    pub fn new() -> Self {
264        Self {
265            base: div(),
266            style: StyleRefinement::default(),
267            children: SmallVec::new(),
268        }
269    }
270}
271
272impl Default for DialogTitle {
273    fn default() -> Self {
274        Self::new()
275    }
276}
277impl Styled for DialogTitle {
278    fn style(&mut self) -> &mut StyleRefinement {
279        &mut self.style
280    }
281}
282impl ParentElement for DialogTitle {
283    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
284        self.children.extend(elements);
285    }
286}
287impl RenderOnce for DialogTitle {
288    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
289        self.base
290            .id("dialog-title")
291            .children(self.children)
292            .refine_style(&self.style)
293    }
294}
295
296/// Unstyled descriptive-content slot for a dialog surface.
297#[derive(IntoElement)]
298pub struct DialogDescription {
299    base: gpui::Div,
300    style: StyleRefinement,
301    children: SmallVec<[AnyElement; 2]>,
302}
303
304impl DialogDescription {
305    pub fn new() -> Self {
306        Self {
307            base: div(),
308            style: StyleRefinement::default(),
309            children: SmallVec::new(),
310        }
311    }
312}
313
314impl Default for DialogDescription {
315    fn default() -> Self {
316        Self::new()
317    }
318}
319impl Styled for DialogDescription {
320    fn style(&mut self) -> &mut StyleRefinement {
321        &mut self.style
322    }
323}
324impl ParentElement for DialogDescription {
325    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
326        self.children.extend(elements);
327    }
328}
329impl RenderOnce for DialogDescription {
330    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
331        self.base
332            .id("dialog-description")
333            .children(self.children)
334            .refine_style(&self.style)
335    }
336}
337
338/// Wrapper that dispatches the dialog cancel action when activated.
339#[derive(IntoElement)]
340pub struct DialogClose {
341    style: StyleRefinement,
342    children: SmallVec<[AnyElement; 1]>,
343    trigger: Option<AnyElement>,
344    /// The focus node activation dispatches from, filled at render and read
345    /// when clicked, so the trigger built earlier reaches it too.
346    anchor: Rc<RefCell<Option<FocusHandle>>>,
347}
348
349impl DialogClose {
350    pub fn new() -> Self {
351        Self {
352            style: StyleRefinement::default(),
353            children: SmallVec::new(),
354            trigger: None,
355            anchor: Rc::default(),
356        }
357    }
358
359    /// Styles a button with the accessible name "Close" and cancel activation.
360    ///
361    /// The supplied button already supports pointer, keyboard, and accessibility
362    /// activation. The builder only needs to supply presentation.
363    /// The wrapper does not also handle clicks when a trigger is supplied.
364    pub fn trigger<E: IntoElement>(mut self, build: impl FnOnce(crate::Button) -> E) -> Self {
365        let anchor = self.anchor.clone();
366        let button = crate::Button::new("close")
367            .accessibility_label("Close")
368            .on_click(move |_, window, cx| Self::activate(&anchor, window, cx));
369        self.trigger = Some(build(button).into_any_element());
370        self
371    }
372
373    /// Dispatches [`Cancel`] from the control's own focus node, so it reaches
374    /// the dialog the control sits in whatever holds focus at that moment: a
375    /// surface that keeps taking focus back (a native web view, an
376    /// always-on-top window) would otherwise leave the control inert.
377    fn activate(anchor: &RefCell<Option<FocusHandle>>, window: &mut Window, cx: &mut App) {
378        // Clone out before dispatching so the dialog's handlers never run
379        // while the cell is borrowed.
380        let anchor = anchor.borrow().clone();
381        match anchor {
382            Some(anchor) => anchor.dispatch_action(&Cancel, window, cx),
383            None => window.dispatch_action(Box::new(Cancel), cx),
384        }
385    }
386}
387impl Default for DialogClose {
388    fn default() -> Self {
389        Self::new()
390    }
391}
392impl ParentElement for DialogClose {
393    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
394        self.children.extend(elements);
395    }
396}
397impl Styled for DialogClose {
398    fn style(&mut self) -> &mut StyleRefinement {
399        &mut self.style
400    }
401}
402impl RenderOnce for DialogClose {
403    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
404        let anchor = window
405            .use_keyed_state("dialog-close-anchor", cx, |_, cx| cx.focus_handle())
406            .read(cx)
407            .clone();
408        *self.anchor.borrow_mut() = Some(anchor.clone());
409        let cell = self.anchor;
410        div()
411            .id("dialog-close")
412            // A zero-size, out-of-flow node that tracks the anchor: it is never
413            // hovered, so it takes no focus on its own and does not enter the
414            // Tab order, but it sits inside this dialog's dispatch path.
415            .child(div().absolute().size_0().track_focus(&anchor))
416            .when(self.trigger.is_none(), |this| {
417                this.on_click(move |_, window, cx| Self::activate(&cell, window, cx))
418            })
419            .children(self.trigger)
420            .children(self.children)
421            .refine_style(&self.style)
422    }
423}
424
425impl Dialog {
426    pub fn new(cx: &mut App) -> Self {
427        Self {
428            style: StyleRefinement::default(),
429            focus: cx.focus_handle(),
430            role: Role::Dialog,
431            accessibility_label: None,
432            accessibility_description: None,
433            layer: 0,
434            keyboard: true,
435            overlay_closable: true,
436            topmost: true,
437            dismiss_below_y: px(0.),
438            backdrop: None,
439            popup: None,
440            children: SmallVec::new(),
441            on_ok: Rc::new(|_, _, _| true),
442            on_cancel: Rc::new(|_, _, _| true),
443            on_close: Rc::new(|_, _, _| {}),
444            request_close: Rc::new(|_, _, _| {}),
445            handle: None,
446            open: true,
447            on_open_change: None,
448        }
449    }
450    pub fn open(mut self, open: bool) -> Self {
451        self.open = open;
452        self
453    }
454    pub fn handle(mut self, handle: DialogHandle) -> Self {
455        if let Some(callback) = self.on_open_change.as_ref() {
456            *handle.on_open_change.borrow_mut() = Some(callback.clone());
457        }
458        self.handle = Some(handle);
459        self
460    }
461    pub fn on_open_change(
462        mut self,
463        handler: impl Fn(bool, DialogChangeReason, &mut Window, &mut App) + 'static,
464    ) -> Self {
465        let handler: OpenChange = Rc::new(handler);
466        if let Some(handle) = self.handle.as_ref() {
467            *handle.on_open_change.borrow_mut() = Some(handler.clone());
468        }
469        self.on_open_change = Some(handler);
470        self
471    }
472
473    pub fn backdrop(mut self, element: impl IntoElement) -> Self {
474        self.backdrop = Some(element.into_any_element());
475        self
476    }
477    pub fn popup(mut self, element: impl IntoElement) -> Self {
478        self.popup = Some(element.into_any_element());
479        self
480    }
481    pub fn close_on_escape(mut self, value: bool) -> Self {
482        self.keyboard = value;
483        self
484    }
485    pub fn close_on_backdrop_press(mut self, value: bool) -> Self {
486        self.overlay_closable = value;
487        self
488    }
489    pub fn dismiss_below_y(mut self, value: Pixels) -> Self {
490        self.dismiss_below_y = value;
491        self
492    }
493    pub(crate) fn role(mut self, role: Role) -> Self {
494        self.role = role;
495        self
496    }
497    /// Names the dialog for accessibility clients (its title, typically).
498    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
499        self.accessibility_label = Some(label.into());
500        self
501    }
502    /// Describes the dialog for accessibility clients, read after its name.
503    #[doc(hidden)]
504    pub fn accessibility_description(mut self, description: impl Into<SharedString>) -> Self {
505        self.accessibility_description = Some(description.into());
506        self
507    }
508    #[doc(hidden)]
509    pub fn layer(mut self, index: usize, topmost: bool) -> Self {
510        self.layer = index;
511        self.topmost = topmost;
512        self
513    }
514    #[doc(hidden)]
515    pub fn focus_handle(mut self, value: FocusHandle) -> Self {
516        self.focus = value;
517        self
518    }
519    #[doc(hidden)]
520    pub fn request_close(
521        mut self,
522        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
523    ) -> Self {
524        self.request_close = Rc::new(handler);
525        self
526    }
527}
528
529impl Styled for Dialog {
530    fn style(&mut self) -> &mut StyleRefinement {
531        &mut self.style
532    }
533}
534impl ParentElement for Dialog {
535    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
536        self.children.extend(elements);
537    }
538}
539
540impl RenderOnce for Dialog {
541    fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
542        let open = self
543            .handle
544            .as_ref()
545            .map_or(self.open, DialogHandle::is_open);
546        if !open {
547            return div().into_any_element();
548        }
549        let request_close = self.request_close;
550        let cancel = self.on_cancel.clone();
551        let confirm = self.on_ok.clone();
552        let closed = self.on_close.clone();
553        let overlay_closable = self.overlay_closable && self.topmost;
554        let dismiss_below_y = self.dismiss_below_y;
555        let escape_handle = self.handle.clone();
556        let confirm_handle = self.handle.clone();
557        let backdrop_handle = self.handle.clone();
558        let escape_change = self.on_open_change.clone();
559        let confirm_change = self.on_open_change.clone();
560        let backdrop_change = self.on_open_change.clone();
561        let viewport = window.viewport_size();
562
563        deferred(
564            anchored().position(point(px(0.), px(0.))).child(
565                div()
566                    .id(("dialog-host", self.layer))
567                    .test_support()
568                    .absolute()
569                    .top_0()
570                    .left_0()
571                    .w(viewport.width)
572                    .h(viewport.height)
573                    // A popup in normal flow lands centered; `refine_style`
574                    // below lets the caller lay the host out differently.
575                    .flex()
576                    .items_center()
577                    .justify_center()
578                    .role(self.role)
579                    .when_some(self.accessibility_label.clone(), |this, label| {
580                        this.aria_label(label)
581                    })
582                    .when_some(self.accessibility_description.clone(), |this, text| {
583                        this.aria_description(text)
584                    })
585                    // GPUI has no `aria_modal` setter. Modal tells assistive
586                    // technology that content outside the dialog is inert; only
587                    // the topmost dialog is, so a stacked alert also leaves the
588                    // dialog below it out of reach.
589                    .when(self.topmost, |this| {
590                        this.a11y_synthetic_children(|builder| builder.parent_node().set_modal())
591                    })
592                    .track_focus(&self.focus)
593                    .focus_trap(format!("dialog-{}", self.layer), &self.focus)
594                    .when(self.keyboard, |this| this.key_context(CONTEXT))
595                    .map(|this| {
596                        let request_cancel = request_close.clone();
597                        let request_confirm = request_close.clone();
598                        let closed_cancel = closed.clone();
599                        this.on_action(move |_: &Cancel, window, cx| {
600                            let event = ClickEvent::default();
601                            if cancel(&event, window, cx) {
602                                request_open_change(
603                                    &escape_handle,
604                                    &escape_change,
605                                    false,
606                                    DialogChangeReason::Cancel,
607                                    window,
608                                    cx,
609                                );
610                                request_cancel(false, window, cx);
611                                closed_cancel(&event, window, cx);
612                            }
613                        })
614                        .on_action(move |_: &Confirm, window, cx| {
615                            let event = ClickEvent::default();
616                            if confirm(&event, window, cx) {
617                                request_open_change(
618                                    &confirm_handle,
619                                    &confirm_change,
620                                    false,
621                                    DialogChangeReason::Confirm,
622                                    window,
623                                    cx,
624                                );
625                                request_confirm(true, window, cx);
626                                closed(&event, window, cx);
627                            }
628                        })
629                    })
630                    .when_some(self.backdrop, |this, backdrop| {
631                        let cancel = self.on_cancel.clone();
632                        let closed = self.on_close.clone();
633                        let request_close = request_close.clone();
634                        this.child(
635                            div()
636                                // The backdrop covers the host, so a caller's
637                                // `absolute()` surface has a box to fill.
638                                .absolute()
639                                .inset_0()
640                                .on_any_mouse_down(move |event, window, cx| {
641                                    if event.position.y < dismiss_below_y {
642                                        return;
643                                    }
644                                    let button = event.button;
645                                    cx.stop_propagation();
646                                    let event = ClickEvent::default();
647                                    if button == MouseButton::Left
648                                        && overlay_closable
649                                        && cancel(&event, window, cx)
650                                    {
651                                        request_open_change(
652                                            &backdrop_handle,
653                                            &backdrop_change,
654                                            false,
655                                            DialogChangeReason::BackdropPress,
656                                            window,
657                                            cx,
658                                        );
659                                        request_close(false, window, cx);
660                                        closed(&event, window, cx);
661                                    }
662                                })
663                                .child(backdrop),
664                        )
665                    })
666                    .children(self.popup)
667                    .children(self.children)
668                    .refine_style(&self.style),
669            ),
670        )
671        .with_priority(10 + self.layer)
672        .into_any_element()
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679    use gpui::{Context, Render, point};
680    use std::{cell::RefCell, rc::Rc};
681
682    #[gpui::test]
683    fn a_dialog_takes_an_accessible_name(cx: &mut gpui::TestAppContext) {
684        struct Named;
685        impl Render for Named {
686            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
687                div().child(
688                    Dialog::new(cx)
689                        .accessibility_label("Discard draft?")
690                        .popup(div().size(px(10.))),
691                )
692            }
693        }
694        cx.update(crate::init);
695        let (_, cx) = cx.add_window_view(|_, _| Named);
696        cx.update(|window, cx| window.draw(cx).clear(cx));
697        let dialog = cx.update(|window, _| {
698            crate::test_support::snapshots(window)
699                .into_iter()
700                .find(|node| node.role() == Some(Role::Dialog))
701                .expect("a dialog node")
702        });
703        assert_eq!(dialog.label(), Some("Discard draft?"));
704    }
705
706    #[gpui::test]
707    fn close_trigger_supplies_accessible_button(cx: &mut gpui::TestAppContext) {
708        use gpui::{Element as _, accesskit, canvas};
709        use std::sync::{Arc, Mutex};
710
711        struct Probe(Arc<Mutex<Option<accesskit::Node>>>);
712        impl Render for Probe {
713            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
714                let captured = self.0.clone();
715                canvas(
716                    move |_, window, cx| {
717                        DialogClose::new().trigger(|button| {
718                            let element = button.render(window, cx).into_element();
719                            let mut node = accesskit::Node::new(element.a11y_role().unwrap());
720                            element.write_a11y_info(&mut node);
721                            *captured.lock().unwrap() = Some(node);
722                            element
723                        });
724                    },
725                    |_, _, _, _| {},
726                )
727            }
728        }
729
730        let captured = Arc::new(Mutex::new(None));
731        let result = captured.clone();
732        let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
733        cx.update(|window, cx| window.draw(cx).clear(cx));
734        let node = result.lock().unwrap().take().unwrap();
735        assert_eq!(node.role(), Role::Button);
736        assert_eq!(node.label(), Some("Close"));
737        assert!(node.supports_action(accesskit::Action::Click));
738    }
739
740    #[gpui::test]
741    fn close_trigger_activates_once_and_respects_cancel_veto(cx: &mut gpui::TestAppContext) {
742        use gpui::{KeyDownEvent, KeyUpEvent, Keystroke};
743
744        struct Harness {
745            focus: FocusHandle,
746            button_focus: FocusHandle,
747            handle: DialogHandle,
748            attempts: Rc<Cell<usize>>,
749        }
750        impl Render for Harness {
751            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
752                let attempts = self.attempts.clone();
753                let button_focus = self.button_focus.clone();
754                Dialog::new(cx)
755                    .handle(self.handle.clone())
756                    .focus_handle(self.focus.clone())
757                    .on_cancel(move |_, _, _| {
758                        attempts.set(attempts.get() + 1);
759                        attempts.get() > 1
760                    })
761                    .popup(
762                        DialogClose::new().trigger(move |button| {
763                            button.size(px(100.)).track_focus(&button_focus)
764                        }),
765                    )
766            }
767        }
768
769        cx.update(crate::init);
770        let handle = DialogHandle::new(true);
771        let attempts = Rc::new(Cell::new(0));
772        let (view, cx) = cx.add_window_view({
773            let handle = handle.clone();
774            let attempts = attempts.clone();
775            move |_, cx| Harness {
776                focus: cx.focus_handle(),
777                button_focus: cx.focus_handle(),
778                handle,
779                attempts,
780            }
781        });
782        let viewport = cx.update(|window, cx| {
783            view.read(cx).focus.clone().focus(window, cx);
784            window.draw(cx).clear(cx);
785            window.viewport_size()
786        });
787        let popup_center = point(viewport.width / 2., viewport.height / 2.);
788        cx.simulate_click(popup_center, Default::default());
789        cx.run_until_parked();
790        assert_eq!(attempts.get(), 1);
791        assert!(handle.is_open(), "on_cancel can veto pointer dismissal");
792
793        cx.update(|window, cx| {
794            view.read(cx).button_focus.clone().focus(window, cx);
795            window.draw(cx).clear(cx);
796        });
797        let keystroke = Keystroke::parse("space").unwrap();
798        cx.simulate_event(KeyDownEvent {
799            keystroke: keystroke.clone(),
800            is_held: false,
801            prefer_character_input: false,
802        });
803        cx.simulate_event(KeyUpEvent { keystroke });
804        cx.run_until_parked();
805        assert_eq!(attempts.get(), 2);
806        assert!(!handle.is_open(), "Space uses the same cancel decision");
807    }
808
809    struct TriggerHarness {
810        handle: DialogHandle,
811    }
812    impl Render for TriggerHarness {
813        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
814            DialogTrigger::new(div().size(px(100.))).handle(self.handle.clone())
815        }
816    }
817
818    #[gpui::test]
819    fn trigger_opens_shared_handle_and_reports_reason(cx: &mut gpui::TestAppContext) {
820        let handle = DialogHandle::new(false);
821        let changes = Rc::new(RefCell::new(Vec::new()));
822        *handle.on_open_change.borrow_mut() = Some({
823            let changes = changes.clone();
824            Rc::new(move |open, reason, _, _| changes.borrow_mut().push((open, reason)))
825        });
826        let (_, cx) = cx.add_window_view({
827            let handle = handle.clone();
828            move |_, _| TriggerHarness { handle }
829        });
830        cx.update(|window, cx| window.draw(cx).clear(cx));
831        cx.simulate_click(point(px(20.), px(20.)), Default::default());
832
833        assert!(handle.is_open());
834        assert_eq!(
835            &*changes.borrow(),
836            &[(true, DialogChangeReason::TriggerPress)]
837        );
838    }
839
840    /// The backdrop is the dimming surface every caller hands over as an
841    /// `absolute()` element, so it has to have the host's box to resolve
842    /// against — a collapsed wrapper leaves it zero-sized and invisible.
843    #[gpui::test]
844    fn the_backdrop_fills_the_host(cx: &mut gpui::TestAppContext) {
845        use gpui::{Bounds, canvas};
846        use std::cell::Cell;
847
848        struct Harness {
849            focus: FocusHandle,
850            bounds: Rc<Cell<Bounds<Pixels>>>,
851        }
852        impl Render for Harness {
853            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
854                let bounds = self.bounds.clone();
855                Dialog::new(cx)
856                    .open(true)
857                    .focus_handle(self.focus.clone())
858                    .backdrop(
859                        canvas(
860                            move |bounds_of_backdrop, _, _| bounds.set(bounds_of_backdrop),
861                            |_, _, _, _| {},
862                        )
863                        .absolute()
864                        .size_full(),
865                    )
866                    .popup(div().size(px(100.)))
867            }
868        }
869
870        cx.update(crate::init);
871        let bounds = Rc::new(Cell::new(Bounds::default()));
872        let (_, cx) = cx.add_window_view({
873            let bounds = bounds.clone();
874            move |_, cx| Harness {
875                focus: cx.focus_handle(),
876                bounds,
877            }
878        });
879        let viewport = cx.update(|window, cx| {
880            let viewport = window.viewport_size();
881            window.draw(cx).clear(cx);
882            viewport
883        });
884
885        assert_eq!(
886            bounds.get().size,
887            viewport,
888            "a zero-sized backdrop paints no overlay behind the dialog"
889        );
890    }
891
892    /// The backdrop sits under the popup, so a press on the popup must not
893    /// reach it and dismiss the dialog.
894    #[gpui::test]
895    fn pressing_the_popup_does_not_dismiss(cx: &mut gpui::TestAppContext) {
896        struct Harness(DialogHandle);
897        impl Render for Harness {
898            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
899                Dialog::new(cx)
900                    .handle(self.0.clone())
901                    .backdrop(div().absolute().size_full())
902                    .popup(DialogPopup::new().size(px(100.)))
903            }
904        }
905
906        cx.update(crate::init);
907        let handle = DialogHandle::new(true);
908        let (_, cx) = cx.add_window_view({
909            let handle = handle.clone();
910            move |_, _| Harness(handle)
911        });
912        let viewport = cx.update(|window, cx| {
913            window.draw(cx).clear(cx);
914            window.viewport_size()
915        });
916
917        cx.simulate_click(
918            point(viewport.width / 2., viewport.height / 2.),
919            Default::default(),
920        );
921        assert!(
922            handle.is_open(),
923            "a press on the popup keeps the dialog open"
924        );
925
926        cx.simulate_click(point(px(5.), px(5.)), Default::default());
927        assert!(!handle.is_open(), "a press on the backdrop still dismisses");
928    }
929
930    #[gpui::test]
931    fn the_popup_is_centered_by_default(cx: &mut gpui::TestAppContext) {
932        use gpui::{Bounds, canvas};
933        use std::cell::Cell;
934
935        struct Harness(Rc<Cell<Bounds<Pixels>>>);
936        impl Render for Harness {
937            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
938                let bounds = self.0.clone();
939                Dialog::new(cx).popup(
940                    canvas(move |popup, _, _| bounds.set(popup), |_, _, _, _| {}).size(px(100.)),
941                )
942            }
943        }
944
945        cx.update(crate::init);
946        let bounds = Rc::new(Cell::new(Bounds::default()));
947        let (_, cx) = cx.add_window_view({
948            let bounds = bounds.clone();
949            move |_, _| Harness(bounds)
950        });
951        let viewport = cx.update(|window, cx| {
952            let viewport = window.viewport_size();
953            window.draw(cx).clear(cx);
954            viewport
955        });
956
957        assert_eq!(
958            bounds.get().center(),
959            point(viewport.width / 2., viewport.height / 2.)
960        );
961    }
962}