use std::{cell::RefCell, rc::Rc};
use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
use gpui_kit::{
App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
assets::IconName,
base::{Button as BaseButton, StyledExt as _},
canvas,
component::Icon,
div,
prelude::*,
px,
};
type DismissHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AlertTone {
#[default]
Info,
Success,
Warning,
Danger,
}
struct AlertInternal {
dismissed: bool,
measured_height: Rc<RefCell<Option<f32>>>,
}
#[derive(IntoElement)]
pub struct Alert {
id: ElementId,
tone: AlertTone,
title: SharedString,
description: Option<SharedString>,
open: Option<bool>,
dismissible: bool,
on_dismiss: Option<DismissHandler>,
}
impl Alert {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
tone: AlertTone::Info,
title: title.into(),
description: None,
open: None,
dismissible: false,
on_dismiss: None,
}
}
pub fn tone(mut self, tone: AlertTone) -> Self {
self.tone = tone;
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn open(mut self, open: bool) -> Self {
self.open = Some(open);
self
}
pub fn on_dismiss(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.dismissible = true;
self.on_dismiss = Some(Rc::new(handler));
self
}
pub fn dismissible(mut self, dismissible: bool) -> Self {
self.dismissible = dismissible;
self
}
}
impl RenderOnce for Alert {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-alert".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| AlertInternal {
dismissed: false,
measured_height: Rc::new(RefCell::new(None)),
});
let dismissed = internal.read(cx).dismissed;
let measured_ref = internal.read(cx).measured_height.clone();
let measured = *measured_ref.borrow();
let is_open = self.open.unwrap_or(!dismissed);
let (height, fade, settled_open) = match measured {
Some(h) => {
let target = if is_open { h } else { 0.0 };
let cur = if reduced {
target
} else {
arc_spring(
(self.id.clone(), "alert-height"),
target,
motion.spring.smooth,
window,
cx,
)
};
let op = arc_transition(
(self.id.clone(), "alert-fade"),
if is_open { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else if is_open {
motion.duration.standard
} else {
motion.duration.exit
},
if is_open {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
let settled = is_open && (cur - h).abs() < 0.5 && op > 0.99;
(Some(cur.max(0.0)), op.clamp(0.0, 1.0), settled)
}
None => (None, 1.0, is_open),
};
let icon_color = match self.tone {
AlertTone::Info => colors.info,
AlertTone::Success => colors.success,
AlertTone::Warning => colors.warning,
AlertTone::Danger => colors.danger,
};
let icon = match self.tone {
AlertTone::Info => IconName::Info,
AlertTone::Success => IconName::Check,
AlertTone::Warning => IconName::TriangleAlert,
AlertTone::Danger => IconName::CircleX,
};
let probe_ref = measured_ref.clone();
let probe = canvas(
move |rect, _, _| {
let h = f32::from(rect.size.height);
if h > 1.0 {
*probe_ref.borrow_mut() = Some(h);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let dismiss_btn = self.dismissible.then(|| {
let int = internal.clone();
let controlled = self.open.is_some();
let cb = self.on_dismiss.clone();
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"dismiss".into(),
))
.accessibility_label(format!("Dismiss: {}", self.title))
.on_click(move |_, window, cx| {
if !controlled {
int.update(cx, |s, _| s.dismissed = true);
}
if let Some(cb) = &cb {
cb(&(), window, cx);
}
window.refresh();
})
.flex_none()
.w(px(28.0))
.h(px(28.0))
.mt(px(-5.0))
.mr(px(-6.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.text_color(colors.text_muted)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
.child(Icon::new(IconName::X).text_size(px(16.0)))
});
let body = div()
.relative()
.w_full()
.flex()
.items_start()
.gap(Spacing::S3)
.p(Spacing::S4)
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.child(probe)
.child(
div()
.flex_none()
.mt(px(1.0))
.child(Icon::new(icon).text_size(px(18.0)).text_color(icon_color)),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.title.clone()),
)
.when_some(self.description, |this, d| {
this.child(
div()
.mt(Spacing::S1)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(d),
)
}),
)
.children(dismiss_btn);
div()
.id(self.id)
.w_full()
.min_w_0()
.when(!settled_open, |this| {
this.overflow_hidden()
.when_some(height, |t, h| t.h(px(h)))
.opacity(fade)
})
.child(body)
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct AlertHost {
dismissed: Rc<Cell<usize>>,
}
impl Render for AlertHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let counter = self.dismissed.clone();
div().w(px(420.0)).p(Spacing::S4).child(
Alert::new("deploy-alert", "Deploy failed")
.tone(AlertTone::Danger)
.description("Build exited with code 1.")
.on_dismiss(move |_, _, _| counter.set(counter.get() + 1)),
)
}
}
#[gpui_kit::test]
fn alert_dismiss_button_collapses_and_calls_back(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let count = Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| AlertHost {
dismissed: count.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let btn = window.find_by_label("Dismiss: Deploy failed");
assert_eq!(btn.role(), Some(Role::Button));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
window.render_frame(cx);
});
assert_eq!(count.get(), 1);
}
}