Skip to main content

gpui_base/
alert_dialog.rs

1use gpui::prelude::FluentBuilder as _;
2use gpui::{
3    App, ClickEvent, FocusHandle, InteractiveElement as _, IntoElement, MouseButton, ParentElement,
4    Pixels, RenderOnce, Role, StatefulInteractiveElement as _, StyleRefinement, Styled, Window,
5    div,
6};
7use smallvec::SmallVec;
8
9use crate::{Dialog, DialogChangeReason, DialogHandle};
10
11macro_rules! alert_part {
12    ($name:ident, $id:literal) => {
13        alert_part!($name, $id, false);
14    };
15    ($name:ident, $id:literal, $occlude:literal) => {
16        #[derive(IntoElement)]
17        pub struct $name {
18            style: StyleRefinement,
19            children: SmallVec<[gpui::AnyElement; 2]>,
20        }
21        impl $name {
22            pub fn new() -> Self {
23                Self {
24                    style: StyleRefinement::default(),
25                    children: SmallVec::new(),
26                }
27            }
28        }
29        impl Default for $name {
30            fn default() -> Self {
31                Self::new()
32            }
33        }
34        impl ParentElement for $name {
35            fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
36                self.children.extend(elements);
37            }
38        }
39        impl Styled for $name {
40            fn style(&mut self) -> &mut StyleRefinement {
41                &mut self.style
42            }
43        }
44        impl RenderOnce for $name {
45            fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
46                div()
47                    .id($id)
48                    // Presses on the popup stay off the backdrop behind it.
49                    .when($occlude, |this| this.occlude())
50                    .children(self.children)
51                    .refine_style(&self.style)
52            }
53        }
54    };
55}
56
57alert_part!(AlertDialogBackdrop, "alert-dialog-backdrop");
58alert_part!(AlertDialogPopup, "alert-dialog-popup", true);
59alert_part!(AlertDialogTitle, "alert-dialog-title");
60alert_part!(AlertDialogDescription, "alert-dialog-description");
61
62#[derive(IntoElement)]
63pub struct AlertDialogTrigger {
64    trigger: gpui::AnyElement,
65    open: std::rc::Rc<dyn Fn(&mut Window, &mut App)>,
66    handle: Option<DialogHandle>,
67}
68impl AlertDialogTrigger {
69    pub fn new(trigger: impl IntoElement) -> Self {
70        Self {
71            trigger: trigger.into_any_element(),
72            open: std::rc::Rc::new(|_, _| {}),
73            handle: None,
74        }
75    }
76    pub fn on_open(mut self, open: impl Fn(&mut Window, &mut App) + 'static) -> Self {
77        self.open = std::rc::Rc::new(open);
78        self
79    }
80    pub fn handle(mut self, handle: DialogHandle) -> Self {
81        self.handle = Some(handle);
82        self
83    }
84}
85impl RenderOnce for AlertDialogTrigger {
86    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
87        div()
88            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
89                if let Some(handle) = self.handle.as_ref() {
90                    handle.set_open(true, DialogChangeReason::TriggerPress, window, cx);
91                }
92                (self.open)(window, cx);
93                cx.stop_propagation();
94            })
95            .child(self.trigger)
96    }
97}
98
99macro_rules! alert_close_part {
100    ($name:ident, $id:literal) => {
101        #[derive(IntoElement)]
102        pub struct $name {
103            style: StyleRefinement,
104            children: SmallVec<[gpui::AnyElement; 1]>,
105        }
106        impl $name {
107            pub fn new() -> Self {
108                Self {
109                    style: StyleRefinement::default(),
110                    children: SmallVec::new(),
111                }
112            }
113        }
114        impl Default for $name {
115            fn default() -> Self {
116                Self::new()
117            }
118        }
119        impl ParentElement for $name {
120            fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
121                self.children.extend(elements);
122            }
123        }
124        impl Styled for $name {
125            fn style(&mut self) -> &mut StyleRefinement {
126                &mut self.style
127            }
128        }
129        impl RenderOnce for $name {
130            fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
131                div()
132                    .id($id)
133                    .on_click(|_, window, cx| {
134                        window.dispatch_action(Box::new(crate::actions::Cancel), cx)
135                    })
136                    .children(self.children)
137                    .refine_style(&self.style)
138            }
139        }
140    };
141}
142alert_close_part!(AlertDialogClose, "alert-dialog-close");
143alert_close_part!(AlertDialogCancel, "alert-dialog-cancel");
144
145/// Wrapper that dispatches the alert dialog's confirm action.
146#[derive(IntoElement)]
147pub struct AlertDialogAction {
148    style: StyleRefinement,
149    children: SmallVec<[gpui::AnyElement; 1]>,
150}
151
152impl AlertDialogAction {
153    pub fn new() -> Self {
154        Self {
155            style: StyleRefinement::default(),
156            children: SmallVec::new(),
157        }
158    }
159}
160
161impl Default for AlertDialogAction {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl ParentElement for AlertDialogAction {
168    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
169        self.children.extend(elements);
170    }
171}
172
173impl Styled for AlertDialogAction {
174    fn style(&mut self) -> &mut StyleRefinement {
175        &mut self.style
176    }
177}
178
179impl RenderOnce for AlertDialogAction {
180    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
181        div()
182            .id("alert-dialog-action")
183            .on_click(|_, window, cx| {
184                window.dispatch_action(Box::new(crate::actions::Confirm { secondary: false }), cx)
185            })
186            .children(self.children)
187            .refine_style(&self.style)
188    }
189}
190
191/// Alert-dialog specialization of the Base modal host.
192pub struct AlertDialog(Dialog);
193
194impl AlertDialog {
195    pub fn new(cx: &mut App) -> Self {
196        Self(
197            Dialog::new(cx)
198                .role(Role::AlertDialog)
199                .close_on_backdrop_press(false),
200        )
201    }
202    pub fn open(mut self, open: bool) -> Self {
203        self.0 = self.0.open(open);
204        self
205    }
206    pub fn handle(mut self, handle: DialogHandle) -> Self {
207        self.0 = self.0.handle(handle);
208        self
209    }
210    pub fn on_open_change(
211        mut self,
212        handler: impl Fn(bool, DialogChangeReason, &mut Window, &mut App) + 'static,
213    ) -> Self {
214        self.0 = self.0.on_open_change(handler);
215        self
216    }
217    pub fn backdrop(mut self, element: impl IntoElement) -> Self {
218        self.0 = self.0.backdrop(element);
219        self
220    }
221    pub fn popup(mut self, element: impl IntoElement) -> Self {
222        self.0 = self.0.popup(element);
223        self
224    }
225    pub fn close_on_escape(mut self, value: bool) -> Self {
226        self.0 = self.0.close_on_escape(value);
227        self
228    }
229    pub fn dismiss_below_y(mut self, value: Pixels) -> Self {
230        self.0 = self.0.dismiss_below_y(value);
231        self
232    }
233    pub fn on_ok(
234        mut self,
235        handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
236    ) -> Self {
237        self.0 = self.0.on_ok(handler);
238        self
239    }
240    pub fn on_cancel(
241        mut self,
242        handler: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
243    ) -> Self {
244        self.0 = self.0.on_cancel(handler);
245        self
246    }
247    pub fn on_close(
248        mut self,
249        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
250    ) -> Self {
251        self.0 = self.0.on_close(handler);
252        self
253    }
254    #[doc(hidden)]
255    pub fn layer(mut self, index: usize, topmost: bool) -> Self {
256        self.0 = self.0.layer(index, topmost);
257        self
258    }
259    #[doc(hidden)]
260    pub fn focus_handle(mut self, value: FocusHandle) -> Self {
261        self.0 = self.0.focus_handle(value);
262        self
263    }
264    #[doc(hidden)]
265    pub fn request_close(
266        mut self,
267        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
268    ) -> Self {
269        self.0 = self.0.request_close(handler);
270        self
271    }
272}
273
274impl Styled for AlertDialog {
275    fn style(&mut self) -> &mut StyleRefinement {
276        self.0.style()
277    }
278}
279impl ParentElement for AlertDialog {
280    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
281        self.0.extend(elements);
282    }
283}
284impl IntoElement for AlertDialog {
285    type Element = <Dialog as IntoElement>::Element;
286    fn into_element(self) -> Self::Element {
287        self.0.into_element()
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use gpui::{Context, Render, div, point, px};
295    use std::{cell::Cell, rc::Rc};
296
297    struct Harness {
298        close_requested: Rc<Cell<bool>>,
299    }
300
301    impl Render for Harness {
302        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
303            let close_requested = self.close_requested.clone();
304            AlertDialog::new(cx)
305                .request_close(move |_, _, _| close_requested.set(true))
306                .backdrop(div().size(px(200.)))
307        }
308    }
309
310    #[gpui::test]
311    fn backdrop_is_not_closable_by_default(cx: &mut gpui::TestAppContext) {
312        cx.update(crate::init);
313        let close_requested = Rc::new(Cell::new(false));
314        let (_, cx) = cx.add_window_view({
315            let close_requested = close_requested.clone();
316            move |_, _| Harness { close_requested }
317        });
318        cx.update(|window, cx| window.draw(cx).clear(cx));
319
320        cx.simulate_click(point(px(20.), px(20.)), Default::default());
321
322        assert!(!close_requested.get());
323    }
324
325    /// The host centers its popup by default; styling the alert dialog
326    /// replaces that layout just as it does for a plain dialog.
327    #[gpui::test]
328    fn host_style_positions_the_popup(cx: &mut gpui::TestAppContext) {
329        use gpui::{Bounds, canvas};
330
331        struct TopLeft(Rc<Cell<Bounds<Pixels>>>);
332        impl Render for TopLeft {
333            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
334                let bounds = self.0.clone();
335                AlertDialog::new(cx).items_start().justify_start().popup(
336                    canvas(move |popup, _, _| bounds.set(popup), |_, _, _, _| {}).size(px(100.)),
337                )
338            }
339        }
340
341        cx.update(crate::init);
342        let bounds = Rc::new(Cell::new(Bounds::default()));
343        let (_, cx) = cx.add_window_view({
344            let bounds = bounds.clone();
345            move |_, _| TopLeft(bounds)
346        });
347        cx.update(|window, cx| window.draw(cx).clear(cx));
348
349        assert_eq!(bounds.get().origin, point(px(0.), px(0.)));
350    }
351}