A modal that asks the user to confirm or cancel an important action.
use gpui::{prelude::*, Context, Window};
use crate::ui::alert_dialog::AlertDialog;
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct DeleteProjectView {
open: bool,
}
impl Render for DeleteProjectView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("delete-project", self.open, "Delete this project?")
.trigger(Button::new("delete-trigger", "Delete project").variant(ButtonVariant::Outline))
.description(
"This permanently deletes the project and its deployments. You can't undo this.",
)
.action_label("Delete")
.destructive(true)
.on_action(|_, _, _| println!("project deleted"))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}Installation
Copies src/ui/alert_dialog.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/alert_dialog.rs.src/ui/alert_dialog.rs use std::rc::Rc; use gpui::{ div, prelude::*, px, AnyElement, App, ClickEvent, ElementId, FontWeight, SharedString, Window, }; use crate::theme::ActiveTheme; use crate::ui::button::{Button, ButtonVariant}; use crate::ui::dialog::Modal; /// How wide an [`AlertDialog`] is and how it lays out its content. #[derive(Clone, Copy, Default, PartialEq)] pub enum AlertDialogSize { /// 448px wide, text aligned left, buttons at the end of the footer. #[default] Default, /// 320px wide, text centered, buttons sharing the footer's width. Sm, } type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; type ActionHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// A modal that asks the user to confirm or cancel. Unlike a dialog it has no close button and /// ignores clicks outside, so it only closes through Cancel, the action, or Escape. /// The parent owns `open`. #[derive(IntoElement)] pub struct AlertDialog { id: ElementId, open: bool, trigger: Option<AnyElement>, title: SharedString, description: Option<SharedString>, cancel_label: SharedString, action_label: SharedString, destructive: bool, size: AlertDialogSize, media: Option<AnyElement>, on_action: Option<ActionHandler>, on_open_change: Option<OpenChangeHandler>, } impl AlertDialog { pub fn new(id: impl Into<ElementId>, open: bool, title: impl Into<SharedString>) -> Self { Self { id: id.into(), open, trigger: None, title: title.into(), description: None, cancel_label: "Cancel".into(), action_label: "Continue".into(), destructive: false, size: AlertDialogSize::default(), media: None, on_action: None, on_open_change: None, } } /// Clicking this element asks the parent to open the dialog. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self { self.cancel_label = label.into(); self } pub fn action_label(mut self, label: impl Into<SharedString>) -> Self { self.action_label = label.into(); self } /// Paints the action button red, for irreversible actions. pub fn destructive(mut self, destructive: bool) -> Self { self.destructive = destructive; self } /// The dialog's width and layout; `Sm` suits short yes-or-no questions. pub fn size(mut self, size: AlertDialogSize) -> Self { self.size = size; self } /// An icon or image shown in a muted 40px tile beside the title, or above it when the dialog /// is `Sm`. Draw icons at 24px. pub fn media(mut self, media: impl IntoElement) -> Self { self.media = Some(media.into_any_element()); self } /// Runs when the action button is clicked, before the dialog asks to close. pub fn on_action( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_action = Some(Rc::new(handler)); self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl RenderOnce for AlertDialog { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let on_open_change = self.on_open_change; let cancel = on_open_change.clone(); let confirm = on_open_change.clone(); let on_action = self.on_action; let small = self.size == AlertDialogSize::Sm; let media = self.media.map(|media| { div() .flex_none() .size(px(40.0)) .flex() .items_center() .justify_center() .rounded(theme.radius) .bg(theme.muted) .text_color(theme.foreground) .child(media) }); let text = div() .flex() .flex_col() .gap_2() .when(small, |this| this.items_center().text_center()) .child( div() .text_lg() .font_weight(FontWeight::SEMIBOLD) .line_height(px(20.0)) .child(self.title), ) .when_some(self.description, |this, description| { this.child(div().text_sm().text_color(theme.muted_foreground).child(description)) }); let header = if small { div().flex().flex_col().items_center().gap_2().children(media).child(text) } else { div() .flex() .items_start() .gap_4() .children(media) .child(text.flex_1().min_w(px(0.0))) }; let cancel_button = Button::new("alert-dialog-cancel", self.cancel_label) .variant(ButtonVariant::Outline) .on_click(move |_, window, cx| { if let Some(cancel) = &cancel { cancel(&false, window, cx); } }); let action_button = Button::new("alert-dialog-action", self.action_label) .variant(if self.destructive { ButtonVariant::Destructive } else { ButtonVariant::Default }) .on_click(move |event, window, cx| { if let Some(on_action) = &on_action { on_action(event, window, cx); } if let Some(confirm) = &confirm { confirm(&false, window, cx); } }); let footer = if small { // Each button gets half the row, as shadcn's two-column footer grid. div() .flex() .gap_2() .child(div().flex_1().flex().flex_col().child(cancel_button)) .child(div().flex_1().flex().flex_col().child(action_button)) } else { div().flex().justify_end().gap_2().child(cancel_button).child(action_button) }; let panel = div() .relative() .flex() .flex_col() .gap_4() .w(px(if small { 320.0 } else { 448.0 })) .p_6() .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .text_color(theme.foreground) .shadow_lg() .child(header) .child(footer); // The modal fades and zooms the panel in and out, like the dialog. Modal::new(self.id, self.open) .close_on_outside_click(false) .when_some(self.trigger, |this, trigger| this.trigger(trigger)) .when_some(on_open_change, |this, handler| { this.on_open_change(move |open, window, cx| handler(open, window, cx)) }) .panel(panel) } }Register the module
// src/ui/mod.rs pub mod alert_dialog;
Usage
use crate::ui::alert_dialog::*;Examples
Basic
A title, a description, and Cancel and Continue buttons. Only those buttons or Escape close it.
use gpui::{prelude::*, Context, Window};
use crate::ui::alert_dialog::AlertDialog;
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct AlertDialogBasic {
open: bool,
}
impl Render for AlertDialogBasic {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("alert-dialog-basic", self.open, "Are you absolutely sure?")
.trigger(Button::new("alert-dialog-basic-trigger", "Show Dialog").variant(ButtonVariant::Outline))
.description(
"This action cannot be undone. This will permanently delete your account and remove \
your data from our servers.",
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}Small
AlertDialogSize::Sm makes a narrower dialog with centered text and buttons that split the footer, for short yes-or-no questions.
use gpui::{prelude::*, Context, Window};
use crate::ui::alert_dialog::{AlertDialog, AlertDialogSize};
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct AlertDialogSmall {
open: bool,
}
impl Render for AlertDialogSmall {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("alert-dialog-small", self.open, "Allow accessory to connect?")
.trigger(Button::new("alert-dialog-small-trigger", "Show Dialog").variant(ButtonVariant::Outline))
.size(AlertDialogSize::Sm)
.description("Do you want to allow the USB accessory to connect to this device?")
.cancel_label("Don't allow")
.action_label("Allow")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}Media
media puts an icon or image in a muted tile beside the title. The icon here is Lucide's circle-plus, drawn as a path.
use gpui::{
canvas, point, prelude::*, px, Bounds, Context, Hsla, LineCap, LineJoin, PathBuilder, PathStyle,
Pixels, StrokeOptions, Window,
};
use crate::theme::ActiveTheme;
use crate::ui::alert_dialog::AlertDialog;
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct AlertDialogMedia {
open: bool,
}
impl Render for AlertDialogMedia {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("alert-dialog-media", self.open, "Share this project?")
.trigger(Button::new("alert-dialog-media-trigger", "Share Project").variant(ButtonVariant::Outline))
.media(circle_plus(cx.theme().foreground))
.description("Anyone with the link will be able to view and edit this project.")
.action_label("Share")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}
/// Lucide's circle-plus at 24px: a circle with a plus inside, in 2px round strokes.
fn circle_plus(color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| {},
move |bounds: Bounds<Pixels>, _, window, _| {
let unit = bounds.size.width / 24.0;
let at = |x: f32, y: f32| point(bounds.origin.x + unit * x, bounds.origin.y + unit * y);
let mut path = PathBuilder::stroke(unit * 2.0).with_style(PathStyle::Stroke(StrokeOptions {
line_width: (unit * 2.0).as_f32(),
line_cap: LineCap::Round,
line_join: LineJoin::Round,
..Default::default()
}));
let radii = point(unit * 10.0, unit * 10.0);
path.move_to(at(2.0, 12.0));
path.arc_to(radii, px(0.0), false, true, at(22.0, 12.0));
path.arc_to(radii, px(0.0), false, true, at(2.0, 12.0));
path.close();
path.move_to(at(8.0, 12.0));
path.line_to(at(16.0, 12.0));
path.move_to(at(12.0, 8.0));
path.line_to(at(12.0, 16.0));
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size(px(24.0))
}Small with Media
With AlertDialogSize::Sm the media tile sits centered above the title.
use gpui::{
canvas, point, prelude::*, px, Bounds, Context, Hsla, LineCap, LineJoin, PathBuilder, PathStyle,
Pixels, StrokeOptions, Window,
};
use crate::theme::ActiveTheme;
use crate::ui::alert_dialog::{AlertDialog, AlertDialogSize};
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct AlertDialogSmallWithMedia {
open: bool,
}
impl Render for AlertDialogSmallWithMedia {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("alert-dialog-small-media", self.open, "Allow accessory to connect?")
.trigger(
Button::new("alert-dialog-small-media-trigger", "Show Dialog").variant(ButtonVariant::Outline),
)
.size(AlertDialogSize::Sm)
.media(bluetooth(cx.theme().foreground))
.description("Do you want to allow the USB accessory to connect to this device?")
.cancel_label("Don't allow")
.action_label("Allow")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}
/// Lucide's bluetooth rune at 24px, in 2px round strokes.
fn bluetooth(color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| {},
move |bounds: Bounds<Pixels>, _, window, _| {
let unit = bounds.size.width / 24.0;
let at = |x: f32, y: f32| point(bounds.origin.x + unit * x, bounds.origin.y + unit * y);
let mut path = PathBuilder::stroke(unit * 2.0).with_style(PathStyle::Stroke(StrokeOptions {
line_width: (unit * 2.0).as_f32(),
line_cap: LineCap::Round,
line_join: LineJoin::Round,
..Default::default()
}));
path.move_to(at(7.0, 7.0));
for (x, y) in [(17.0, 17.0), (12.0, 22.0), (12.0, 2.0), (17.0, 7.0), (7.0, 17.0)] {
path.line_to(at(x, y));
}
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size(px(24.0))
}Destructive
destructive(true) paints the action button red for an irreversible step, here with a trash icon as media in a small dialog.
use gpui::{
canvas, point, prelude::*, px, Bounds, Context, Hsla, LineCap, LineJoin, PathBuilder, PathStyle,
Pixels, StrokeOptions, Window,
};
use crate::theme::ActiveTheme;
use crate::ui::alert_dialog::{AlertDialog, AlertDialogSize};
use crate::ui::button::{Button, ButtonVariant};
#[derive(Default)]
pub struct AlertDialogDestructive {
open: bool,
}
impl Render for AlertDialogDestructive {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
AlertDialog::new("alert-dialog-destructive", self.open, "Delete chat?")
.trigger(
Button::new("alert-dialog-destructive-trigger", "Delete Chat").variant(ButtonVariant::Destructive),
)
.size(AlertDialogSize::Sm)
.media(trash(cx.theme().destructive))
.description(
"This will permanently delete this chat conversation. View Settings to delete any \
memories saved during this chat.",
)
.action_label("Delete")
.destructive(true)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
}
}
/// Lucide's trash-2 at 24px with its rounded corners simplified to bevels.
fn trash(color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| {},
move |bounds: Bounds<Pixels>, _, window, _| {
let unit = bounds.size.width / 24.0;
let at = |x: f32, y: f32| point(bounds.origin.x + unit * x, bounds.origin.y + unit * y);
let mut path = PathBuilder::stroke(unit * 2.0).with_style(PathStyle::Stroke(StrokeOptions {
line_width: (unit * 2.0).as_f32(),
line_cap: LineCap::Round,
line_join: LineJoin::Round,
..Default::default()
}));
let lines: [&[(f32, f32)]; 5] = [
&[(3.0, 6.0), (21.0, 6.0)],
&[(19.0, 6.0), (19.0, 20.0), (17.0, 22.0), (7.0, 22.0), (5.0, 20.0), (5.0, 6.0)],
&[(8.0, 6.0), (8.0, 4.0), (10.0, 2.0), (14.0, 2.0), (16.0, 4.0), (16.0, 6.0)],
&[(10.0, 11.0), (10.0, 17.0)],
&[(14.0, 11.0), (14.0, 17.0)],
];
for line in lines {
path.move_to(at(line[0].0, line[0].1));
for &(x, y) in &line[1..] {
path.line_to(at(x, y));
}
}
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size(px(24.0))
}API Reference
AlertDialogSize
How wide an [AlertDialog] is and how it lays out its content.
AlertDialogSize::Default448px wide, text aligned left, buttons at the end of the footer.
AlertDialogSize::Sm320px wide, text centered, buttons sharing the footer's width.
AlertDialog
A modal that asks the user to confirm or cancel. Unlike a dialog it has no close button and ignores clicks outside, so it only closes through Cancel, the action, or Escape. The parent owns open.
AlertDialog::new(id: impl Into<ElementId>, open: bool, title: impl Into<SharedString>) -> Self.trigger(trigger: impl IntoElement)Clicking this element asks the parent to open the dialog.
.description(description: impl Into<SharedString>).cancel_label(label: impl Into<SharedString>).action_label(label: impl Into<SharedString>).destructive(destructive: bool)Paints the action button red, for irreversible actions.
.size(size: AlertDialogSize)The dialog's width and layout; Sm suits short yes-or-no questions.
.media(media: impl IntoElement)An icon or image shown in a muted 40px tile beside the title, or above it when the dialog is Sm. Draw icons at 24px.
.on_action(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Runs when the action button is clicked, before the dialog asks to close.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.