Skip to main content

gpui_component/dialog/
alert_dialog.rs

1use gpui::{
2    AnyElement, App, ClickEvent, IntoElement, ParentElement, Pixels, RenderOnce, SharedString,
3    StyleRefinement, Styled, Window, prelude::FluentBuilder as _,
4};
5use gpui_base::LogicalStyledExt as _;
6
7use crate::{
8    StyledExt as _, WindowExt as _,
9    button::ButtonVariant,
10    dialog::{
11        Dialog, DialogButtonProps, DialogDescription, DialogEntrance, DialogFooter, DialogHeader,
12        DialogTitle,
13    },
14    h_flex, v_flex,
15};
16
17/// AlertDialog is a modal dialog that interrupts the user with important content
18/// and expects a response.
19///
20/// It is built on top of the Dialog component with opinionated defaults:
21/// - Footer buttons are center-aligned (vs right-aligned in Dialog)
22/// - Icon is optional (disabled by default, enable with `.show_icon(true)`)
23/// - Simplified API for common alert scenarios
24/// - Uses declarative DialogHeader, DialogTitle, DialogDescription, and DialogFooter components
25/// - Supports both imperative and declarative API styles
26///
27/// # Examples
28///
29/// ## Imperative API (using WindowExt)
30///
31/// ```ignore
32/// use gpui_kit::component::{AlertDialog, alert::AlertVariant};
33///
34/// // Using WindowExt trait
35/// window.open_alert_dialog(cx, |alert, _, _| {
36///     alert
37///         .title("Unsaved Changes")
38///         .description("You have unsaved changes. Are you sure you want to leave?")
39///         .show_cancel(true)
40/// });
41/// ```
42///
43/// ## Declarative API (using trigger and content)
44///
45/// ```ignore
46/// use gpui_kit::component::{AlertDialog, DialogHeader, DialogTitle, DialogDescription, DialogFooter};
47///
48/// AlertDialog::new(cx)
49///     .trigger(Button::new("delete").label("Delete"))
50///     .content(|content, _, cx| {
51///         content
52///             .child(
53///                 DialogHeader::new()
54///                     .items_center()
55///                     .child(DialogTitle::new().child("Delete File"))
56///                     .child(DialogDescription::new().child("Are you sure?"))
57///             )
58///             .child(
59///                 DialogFooter::new()
60///                     .justify_center()
61///                     .child(Button::new("cancel").label("Cancel"))
62///                     .child(Button::new("confirm").label("Delete"))
63///             )
64///     })
65/// ```
66#[derive(IntoElement)]
67pub struct AlertDialog {
68    base: Dialog,
69    trigger: Option<AnyElement>,
70    icon: Option<AnyElement>,
71    title: Option<AnyElement>,
72    description: Option<AnyElement>,
73    children: Vec<AnyElement>,
74}
75
76impl AlertDialog {
77    /// Create a new AlertDialog.
78    ///
79    /// By default, the dialog is not overlay closable with a OK button.
80    ///
81    pub fn new(cx: &mut App) -> Self {
82        Self {
83            base: Dialog::new(cx)
84                .with_base_alert_dialog(gpui_base::AlertDialog::new(cx))
85                .close_button(false),
86            trigger: None,
87            icon: None,
88            title: None,
89            description: None,
90            children: Vec::new(),
91        }
92    }
93
94    /// Set to use confirm dialog, with OK and Cancel buttons.
95    ///
96    /// The default of [`AlertDialog`] has OK button.
97    pub fn confirm(mut self) -> Self {
98        self.base.button_props.show_cancel = Some(true);
99        self
100    }
101
102    /// Sets the trigger element for the alert dialog.
103    ///
104    /// When a trigger is set, the dialog will render as a trigger element that opens the dialog when clicked.
105    ///
106    /// **Note**: When using `.trigger()`, you should also use `.content()` to define the dialog content
107    /// declaratively instead of using `.title()`, `.description()`, etc.
108    ///
109    /// The `title`, `description`, `icon`, and `button_props` will be ignored when used together with `.trigger()`.
110    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
111        self.trigger = Some(trigger.into_any_element());
112        self
113    }
114
115    /// Sets the content builder for declarative API.
116    ///
117    /// When using this method, you define the dialog content using declarative components like
118    /// `DialogHeader`, `DialogTitle`, `DialogDescription`, and `DialogFooter`.
119    ///
120    /// This method is typically used together with `.trigger()` for a fully declarative API.
121    ///
122    /// # Examples
123    ///
124    /// ```ignore
125    /// AlertDialog::new(cx)
126    ///     .trigger(Button::new("delete").label("Delete"))
127    ///     .content(|content, _, cx| {
128    ///         content
129    ///             .child(DialogHeader::new().child(DialogTitle::new().child("Confirm")))
130    ///             .child(DialogFooter::new().child(Button::new("ok").label("OK")))
131    ///     })
132    /// ```
133    pub fn content<F>(mut self, builder: F) -> Self
134    where
135        F: Fn(crate::dialog::DialogContent, &mut Window, &mut App) -> crate::dialog::DialogContent
136            + 'static,
137    {
138        self.base = self.base.content(builder);
139        self
140    }
141
142    /// Sets the footer builder for declarative API.
143    ///
144    /// This is used to define the footer content using declarative components like `DialogFooter`.
145    ///
146    /// If not set, a default footer with OK and optional Cancel button will be used.
147    pub fn footer(mut self, footer: impl IntoElement) -> Self {
148        self.base = self.base.footer(footer);
149        self
150    }
151
152    #[track_caller]
153    fn debug_assert_no_trigger(&self) {
154        debug_assert!(
155            self.trigger.is_none() && self.base.content_builder.is_none(),
156            "Cannot set this property when trigger is used. Use content() to define dialog content instead."
157        );
158    }
159
160    /// Sets the icon of the alert dialog, default is None.
161    #[track_caller]
162    pub fn icon(mut self, icon: impl IntoElement) -> Self {
163        self.debug_assert_no_trigger();
164        self.icon = Some(icon.into_any_element());
165        self
166    }
167
168    /// Sets the title of the alert dialog.
169    #[track_caller]
170    pub fn title(mut self, title: impl IntoElement) -> Self {
171        self.debug_assert_no_trigger();
172        self.title = Some(title.into_any_element());
173        self
174    }
175
176    /// Sets the description of the alert dialog.
177    #[track_caller]
178    pub fn description(mut self, description: impl IntoElement) -> Self {
179        self.debug_assert_no_trigger();
180        self.description = Some(description.into_any_element());
181        self
182    }
183
184    /// Set the button props of the alert dialog.
185    ///
186    /// Use this to configure button text, variants, and visibility in one
187    /// value. It overrides only the fields `button_props` sets, so the Cancel
188    /// button [`Self::confirm`] asked for and callbacks set earlier survive,
189    /// whatever the call order. For a single property, prefer the direct
190    /// builders — [`Self::ok_text`], [`Self::ok_variant`],
191    /// [`Self::cancel_text`], [`Self::cancel_variant`].
192    ///
193    /// # Examples
194    ///
195    /// ```ignore
196    /// alert.confirm().button_props(
197    ///     DialogButtonProps::default()
198    ///         .ok_text("Delete")
199    ///         .ok_variant(ButtonVariant::Danger)
200    ///         .cancel_text("Keep")
201    /// )
202    /// ```
203    #[track_caller]
204    pub fn button_props(mut self, button_props: DialogButtonProps) -> Self {
205        self.debug_assert_no_trigger();
206        self.base = self.base.button_props(button_props);
207        self
208    }
209
210    /// Sets the text of the OK button. Default is `OK`.
211    pub fn ok_text(mut self, ok_text: impl Into<SharedString>) -> Self {
212        self.base.button_props.ok_text = Some(ok_text.into());
213        self
214    }
215
216    /// Sets the variant of the OK button. Default is `ButtonVariant::Primary`.
217    pub fn ok_variant(mut self, ok_variant: ButtonVariant) -> Self {
218        self.base.button_props.ok_variant = Some(ok_variant);
219        self
220    }
221
222    /// Sets the text of the Cancel button. Default is `Cancel`.
223    pub fn cancel_text(mut self, cancel_text: impl Into<SharedString>) -> Self {
224        self.base.button_props.cancel_text = Some(cancel_text.into());
225        self
226    }
227
228    /// Sets the variant of the Cancel button. Default is `ButtonVariant::default()`.
229    pub fn cancel_variant(mut self, cancel_variant: ButtonVariant) -> Self {
230        self.base.button_props.cancel_variant = Some(cancel_variant);
231        self
232    }
233
234    /// Sets the width of the alert dialog, defaults to 420px.
235    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
236        self.base = self.base.width(width);
237        self
238    }
239
240    /// Show cancel button. Default is false.
241    pub fn show_cancel(mut self, show_cancel: bool) -> Self {
242        self.base.button_props.show_cancel = Some(show_cancel);
243        self
244    }
245
246    /// Alert dialogs never close from a backdrop press.
247    #[deprecated(note = "AlertDialog backdrop dismissal is disabled by design")]
248    pub fn overlay_closable(self, _: bool) -> Self {
249        self
250    }
251
252    /// Set the close button of the alert dialog, defaults to `false`.
253    pub fn close_button(mut self, close_button: bool) -> Self {
254        self.base = self.base.close_button(close_button);
255        self
256    }
257
258    /// Set whether to support keyboard esc to close the dialog, defaults to `true`.
259    pub fn keyboard(mut self, keyboard: bool) -> Self {
260        self.base = self.base.keyboard(keyboard);
261        self
262    }
263
264    /// Sets the top offset of the alert dialog.
265    ///
266    /// Without this, the surface keeps the [`Dialog`] default: a tenth of the
267    /// viewport height below the top edge, which pins short alerts near the
268    /// top of a tall window. Pass a larger offset to seat an alert further
269    /// down, e.g. in the vertical middle of the window.
270    pub fn margin_top(mut self, margin_top: impl Into<Pixels>) -> Self {
271        self.base = self.base.margin_top(margin_top);
272        self
273    }
274
275    /// Centers the alert dialog vertically in the window, whatever its
276    /// height, in place of the [`Self::margin_top`] offset.
277    pub fn centered(mut self) -> Self {
278        self.base = self.base.centered();
279        self
280    }
281
282    /// Sets how the alert dialog enters, defaulting to [`DialogEntrance::SlideDown`].
283    ///
284    /// Shares the surface, backdrop, and reduced-motion policy of [`Dialog::entrance`].
285    pub fn entrance(mut self, entrance: DialogEntrance) -> Self {
286        self.base = self.base.entrance(entrance);
287        self
288    }
289
290    /// Sets the callback for when the alert dialog is closed.
291    ///
292    /// Called after [`Self::on_action`] or [`Self::on_cancel`] callback.
293    pub fn on_close(
294        mut self,
295        on_close: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
296    ) -> Self {
297        self.base = self.base.on_close(on_close);
298        self
299    }
300
301    /// Sets the callback for when the OK/action button is clicked.
302    ///
303    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
304    pub fn on_ok(
305        mut self,
306        on_ok: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
307    ) -> Self {
308        self.base = self.base.on_ok(on_ok);
309        self
310    }
311
312    /// Sets the callback for when the alert dialog has been canceled.
313    ///
314    /// The callback should return `true` to close the dialog, if return `false` the dialog will not be closed.
315    pub fn on_cancel(
316        mut self,
317        on_cancel: impl Fn(&ClickEvent, &mut Window, &mut App) -> bool + 'static,
318    ) -> Self {
319        self.base = self.base.on_cancel(on_cancel);
320        self
321    }
322
323    /// Build the styled dialog surface around the Base alert-dialog host.
324    pub(crate) fn build_surface(self, window: &mut Window, cx: &mut App) -> Dialog {
325        let button_props = self.base.button_props.clone();
326        let has_title = self.icon.is_some() || self.title.is_some();
327        let has_header = has_title || self.description.is_some();
328        let has_footer = self.base.footer.is_some();
329
330        self.base
331            .when(has_header, |this| {
332                this.header(
333                    DialogHeader::new().child(
334                        h_flex()
335                            .flex_row_dir(cx)
336                            .gap_2()
337                            .items_start()
338                            .when_some(self.icon, |row, icon| row.child(icon))
339                            .child(
340                                v_flex()
341                                    .flex_1()
342                                    .min_w_0()
343                                    .gap_1()
344                                    .when_some(self.title, |this, title| {
345                                        this.child(DialogTitle::new().child(title))
346                                    })
347                                    .when_some(self.description, |this, desc| {
348                                        this.child(DialogDescription::new().child(desc))
349                                    }),
350                            ),
351                    ),
352                )
353            })
354            .children(self.children)
355            .when(!has_footer, |this| {
356                // Default footer for AlertDialog if user doesn't provide one, with OK and optional Cancel button
357                this.footer(
358                    DialogFooter::new()
359                        .when(button_props.is_cancel_shown(), |this| {
360                            this.child(button_props.render_cancel(window, cx))
361                        })
362                        .child(button_props.render_ok(window, cx)),
363                )
364            })
365    }
366}
367
368impl Styled for AlertDialog {
369    fn style(&mut self) -> &mut StyleRefinement {
370        &mut self.base.style
371    }
372}
373
374impl ParentElement for AlertDialog {
375    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
376        self.children.extend(elements);
377    }
378}
379
380impl AlertDialog {
381    fn render_trigger(self, trigger: AnyElement, _: &mut Window, _: &mut App) -> AnyElement {
382        let content_builder = self.base.content_builder.clone();
383        let style = self.base.style.clone();
384        let props = self.base.props.clone();
385        let button_props = self.base.button_props.clone();
386
387        gpui_base::AlertDialogTrigger::new(trigger)
388            .on_open(move |window, cx| {
389                let content_builder = content_builder.clone();
390                let style = style.clone();
391                let props = props.clone();
392                let button_props = button_props.clone();
393                window.open_dialog(cx, move |dialog, _, cx| {
394                    dialog
395                        .with_base_alert_dialog(gpui_base::AlertDialog::new(cx))
396                        .refine_style(&style)
397                        .button_props(button_props.clone())
398                        .with_props(props.clone())
399                        .when_some(content_builder.clone(), |this, content_builder| {
400                            this.content(move |content, window, cx| {
401                                content_builder(content, window, cx)
402                            })
403                        })
404                });
405            })
406            .into_any_element()
407    }
408}
409
410impl RenderOnce for AlertDialog {
411    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
412        if let Some(trigger) = self.trigger.take() {
413            // If a trigger is provided, render the trigger element that opens the dialog
414            self.render_trigger(trigger, window, cx)
415        } else {
416            // Otherwise, render the dialog content directly
417            self.build_surface(window, cx).into_any_element()
418        }
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use std::{cell::Cell, rc::Rc};
425
426    use gpui::{ClickEvent, TestAppContext, px, size};
427
428    use super::*;
429    use crate::dialog::dialog::tests::window;
430
431    /// `button_props` overrides only the fields it sets, so the Cancel button
432    /// `confirm` asked for survives a later props value that never mentions it.
433    #[gpui::test]
434    fn button_props_after_confirm_keeps_the_cancel_button(cx: &mut TestAppContext) {
435        let cx = window(cx, size(px(800.), px(600.)));
436        cx.update(|_, cx| {
437            let alert = AlertDialog::new(cx)
438                .confirm()
439                .button_props(DialogButtonProps::default().ok_text("Delete"));
440
441            assert!(alert.base.button_props.is_cancel_shown());
442            assert_eq!(alert.base.button_props.ok_text.as_deref(), Some("Delete"));
443        });
444    }
445
446    /// The call order does not matter either way round.
447    #[gpui::test]
448    fn confirm_after_button_props_keeps_the_ok_text(cx: &mut TestAppContext) {
449        let cx = window(cx, size(px(800.), px(600.)));
450        cx.update(|_, cx| {
451            let alert = AlertDialog::new(cx)
452                .button_props(DialogButtonProps::default().ok_text("Delete"))
453                .confirm();
454
455            assert!(alert.base.button_props.is_cancel_shown());
456            assert_eq!(alert.base.button_props.ok_text.as_deref(), Some("Delete"));
457        });
458    }
459
460    /// A callback installed with `on_ok` survives a later props value that
461    /// carries no callback of its own.
462    #[gpui::test]
463    fn button_props_after_on_ok_keeps_the_callback(cx: &mut TestAppContext) {
464        let cx = window(cx, size(px(800.), px(600.)));
465        let confirmed = Rc::new(Cell::new(0));
466        let counter = confirmed.clone();
467        cx.update(|window, cx| {
468            let alert = AlertDialog::new(cx)
469                .on_ok(move |_, _, _| {
470                    counter.set(counter.get() + 1);
471                    true
472                })
473                .button_props(DialogButtonProps::default().ok_text("Delete"));
474
475            assert!(alert.base.button_props.ok_handler()(
476                &ClickEvent::default(),
477                window,
478                cx
479            ));
480        });
481
482        assert_eq!(confirmed.get(), 1);
483    }
484
485    /// The direct builders resolve to the same buttons as a props value.
486    #[gpui::test]
487    fn the_direct_builders_match_button_props(cx: &mut TestAppContext) {
488        let cx = window(cx, size(px(800.), px(600.)));
489        cx.update(|_, cx| {
490            let direct = AlertDialog::new(cx)
491                .confirm()
492                .ok_text("Delete")
493                .ok_variant(ButtonVariant::Danger)
494                .cancel_text("Keep")
495                .cancel_variant(ButtonVariant::Ghost);
496            let bundled = AlertDialog::new(cx).button_props(
497                DialogButtonProps::default()
498                    .show_cancel(true)
499                    .ok_text("Delete")
500                    .ok_variant(ButtonVariant::Danger)
501                    .cancel_text("Keep")
502                    .cancel_variant(ButtonVariant::Ghost),
503            );
504
505            for props in [&direct.base.button_props, &bundled.base.button_props] {
506                assert!(props.is_cancel_shown());
507                assert_eq!(props.ok_text.as_deref(), Some("Delete"));
508                assert_eq!(props.ok_variant, Some(ButtonVariant::Danger));
509                assert_eq!(props.cancel_text.as_deref(), Some("Keep"));
510                assert_eq!(props.cancel_variant, Some(ButtonVariant::Ghost));
511            }
512        });
513    }
514
515    /// `margin_top` overrides the tenth-of-the-viewport default offset, which
516    /// seats a short alert near the top of a tall window.
517    #[gpui::test]
518    fn margin_top_moves_the_alert_surface_off_the_default_offset(cx: &mut TestAppContext) {
519        let cx = window(cx, size(px(800.), px(600.)));
520        cx.update(|window, cx| {
521            window.open_alert_dialog(cx, |alert, _, _| {
522                alert
523                    .title("Unsaved changes")
524                    .description("Discard the draft?")
525                    .confirm()
526                    .margin_top(px(100.))
527            })
528        });
529        cx.run_until_parked();
530        // One frame mounts the layer, the next paints it at rest.
531        cx.update(|window, cx| window.draw(cx).clear(cx));
532        cx.update(|window, cx| window.draw(cx).clear(cx));
533
534        let bounds = cx
535            .debug_bounds("dialog-0")
536            .expect("the alert dialog surface was not painted");
537        // The alert chrome carries fractional text metrics (this surface is
538        // 128.5px tall), so the painted origin lands within a subpixel of the
539        // requested offset. The default offset would be a tenth of the
540        // viewport: 60px.
541        assert!(
542            (bounds.origin.y - px(100.)).abs() <= px(0.5),
543            "expected the surface within 0.5px of y=100, got {bounds:?}"
544        );
545    }
546
547    /// `centered` seats the surface in the vertical middle of the window,
548    /// whatever its height.
549    #[gpui::test]
550    fn centered_seats_the_alert_surface_in_the_middle(cx: &mut TestAppContext) {
551        let cx = window(cx, size(px(800.), px(600.)));
552        cx.update(|window, cx| {
553            window.open_alert_dialog(cx, |alert, _, _| {
554                alert
555                    .title("Unsaved changes")
556                    .description("Discard the draft?")
557                    .confirm()
558                    .centered()
559            })
560        });
561        cx.run_until_parked();
562        cx.update(|window, cx| window.draw(cx).clear(cx));
563        cx.update(|window, cx| window.draw(cx).clear(cx));
564
565        let bounds = cx
566            .debug_bounds("dialog-0")
567            .expect("the alert dialog surface was not painted");
568        assert!(
569            (bounds.center().y - px(300.)).abs() <= px(0.5),
570            "expected the surface centered on y=300, got {bounds:?}"
571        );
572    }
573}