1use std::{cell::RefCell, rc::Rc};
14
15use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
16use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
17use gpui_kit::{
18 App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
19 assets::IconName,
20 base::{Button as BaseButton, StyledExt as _},
21 canvas,
22 component::Icon,
23 div,
24 prelude::*,
25 px,
26};
27
28type DismissHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
29
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub enum AlertTone {
33 #[default]
34 Info,
35 Success,
36 Warning,
37 Danger,
38}
39
40struct AlertInternal {
41 dismissed: bool,
42 measured_height: Rc<RefCell<Option<f32>>>,
43}
44
45#[derive(IntoElement)]
47pub struct Alert {
48 id: ElementId,
49 tone: AlertTone,
50 title: SharedString,
51 description: Option<SharedString>,
52 open: Option<bool>,
53 dismissible: bool,
54 on_dismiss: Option<DismissHandler>,
55}
56
57impl Alert {
58 pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
59 Self {
60 id: id.into(),
61 tone: AlertTone::Info,
62 title: title.into(),
63 description: None,
64 open: None,
65 dismissible: false,
66 on_dismiss: None,
67 }
68 }
69
70 pub fn tone(mut self, tone: AlertTone) -> Self {
71 self.tone = tone;
72 self
73 }
74
75 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
76 self.description = Some(description.into());
77 self
78 }
79
80 pub fn open(mut self, open: bool) -> Self {
82 self.open = Some(open);
83 self
84 }
85
86 pub fn on_dismiss(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
88 self.dismissible = true;
89 self.on_dismiss = Some(Rc::new(handler));
90 self
91 }
92
93 pub fn dismissible(mut self, dismissible: bool) -> Self {
95 self.dismissible = dismissible;
96 self
97 }
98}
99
100impl RenderOnce for Alert {
101 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
102 let theme = cx.arc_theme().clone();
103 let colors = theme.colors;
104 let motion = theme.motion;
105 let reduced = is_reduced_motion(cx);
106
107 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-alert".into());
108 let internal = window.use_keyed_state(state_id, cx, |_, _| AlertInternal {
109 dismissed: false,
110 measured_height: Rc::new(RefCell::new(None)),
111 });
112 let dismissed = internal.read(cx).dismissed;
113 let measured_ref = internal.read(cx).measured_height.clone();
114 let measured = *measured_ref.borrow();
115
116 let is_open = self.open.unwrap_or(!dismissed);
117
118 let (height, fade, settled_open) = match measured {
121 Some(h) => {
122 let target = if is_open { h } else { 0.0 };
123 let cur = if reduced {
124 target
125 } else {
126 arc_spring(
127 (self.id.clone(), "alert-height"),
128 target,
129 motion.spring.smooth,
130 window,
131 cx,
132 )
133 };
134 let op = arc_transition(
135 (self.id.clone(), "alert-fade"),
136 if is_open { 1.0 } else { 0.0 },
137 if reduced {
138 std::time::Duration::ZERO
139 } else if is_open {
140 motion.duration.standard
141 } else {
142 motion.duration.exit
143 },
144 if is_open {
145 motion.ease.enter
146 } else {
147 motion.ease.standard
148 },
149 window,
150 cx,
151 );
152 let settled = is_open && (cur - h).abs() < 0.5 && op > 0.99;
153 (Some(cur.max(0.0)), op.clamp(0.0, 1.0), settled)
154 }
155 None => (None, 1.0, is_open),
156 };
157
158 let icon_color = match self.tone {
159 AlertTone::Info => colors.info,
160 AlertTone::Success => colors.success,
161 AlertTone::Warning => colors.warning,
162 AlertTone::Danger => colors.danger,
163 };
164 let icon = match self.tone {
165 AlertTone::Info => IconName::Info,
166 AlertTone::Success => IconName::Check,
167 AlertTone::Warning => IconName::TriangleAlert,
168 AlertTone::Danger => IconName::CircleX,
169 };
170
171 let probe_ref = measured_ref.clone();
172 let probe = canvas(
173 move |rect, _, _| {
174 let h = f32::from(rect.size.height);
175 if h > 1.0 {
176 *probe_ref.borrow_mut() = Some(h);
177 }
178 },
179 |_, _, _, _| {},
180 )
181 .absolute()
182 .inset_0();
183
184 let dismiss_btn = self.dismissible.then(|| {
185 let int = internal.clone();
186 let controlled = self.open.is_some();
187 let cb = self.on_dismiss.clone();
188 let hover_bg = colors.surface_muted;
189 let hover_fg = colors.foreground;
190 BaseButton::new(ElementId::NamedChild(
191 self.id.clone().into(),
192 "dismiss".into(),
193 ))
194 .accessibility_label(format!("Dismiss: {}", self.title))
195 .on_click(move |_, window, cx| {
196 if !controlled {
197 int.update(cx, |s, _| s.dismissed = true);
198 }
199 if let Some(cb) = &cb {
200 cb(&(), window, cx);
201 }
202 window.refresh();
203 })
204 .flex_none()
205 .w(px(28.0))
206 .h(px(28.0))
207 .mt(px(-5.0))
208 .mr(px(-6.0))
209 .flex()
210 .items_center()
211 .justify_center()
212 .rounded(Radii::PILL)
213 .text_color(colors.text_muted)
214 .cursor_pointer()
215 .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
216 .child(Icon::new(IconName::X).text_size(px(16.0)))
217 });
218
219 let body = div()
220 .relative()
221 .w_full()
222 .flex()
223 .items_start()
224 .gap(Spacing::S3)
225 .p(Spacing::S4)
226 .rounded(Radii::CONTROL)
227 .border_1()
228 .border_color(colors.border)
229 .bg(colors.surface)
230 .child(probe)
231 .child(
232 div()
233 .flex_none()
234 .mt(px(1.0))
235 .child(Icon::new(icon).text_size(px(18.0)).text_color(icon_color)),
236 )
237 .child(
238 div()
239 .flex_1()
240 .min_w_0()
241 .flex()
242 .flex_col()
243 .child(
244 div()
245 .text_size(Typography::TEXT_SM)
246 .font_medium()
247 .text_color(colors.foreground)
248 .child(self.title.clone()),
249 )
250 .when_some(self.description, |this, d| {
251 this.child(
252 div()
253 .mt(Spacing::S1)
254 .text_size(Typography::TEXT_XS)
255 .text_color(colors.text_secondary)
256 .child(d),
257 )
258 }),
259 )
260 .children(dismiss_btn);
261
262 div()
263 .id(self.id)
264 .w_full()
265 .min_w_0()
266 .when(!settled_open, |this| {
267 this.overflow_hidden()
268 .when_some(height, |t, h| t.h(px(h)))
269 .opacity(fade)
270 })
271 .child(body)
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use std::{cell::Cell, rc::Rc};
278
279 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
280 use gpui_kit::{
281 Context, MouseButton, Render, Role, TestAppContext, div,
282 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
283 };
284
285 use super::*;
286
287 struct AlertHost {
288 dismissed: Rc<Cell<usize>>,
289 }
290
291 impl Render for AlertHost {
292 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
293 let counter = self.dismissed.clone();
294 div().w(px(420.0)).p(Spacing::S4).child(
295 Alert::new("deploy-alert", "Deploy failed")
296 .tone(AlertTone::Danger)
297 .description("Build exited with code 1.")
298 .on_dismiss(move |_, _, _| counter.set(counter.get() + 1)),
299 )
300 }
301 }
302
303 #[gpui_kit::test]
304 fn alert_dismiss_button_collapses_and_calls_back(cx: &mut TestAppContext) {
305 cx.update(|cx| {
306 gpui_kit::init(cx);
307 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
308 });
309 let count = Rc::new(Cell::new(0));
310 let (_view, cx) = cx.add_window_view(|_, _| AlertHost {
311 dismissed: count.clone(),
312 });
313 cx.update(|window, cx| {
314 window.render_frame(cx);
315 window.render_frame(cx);
316 let btn = window.find_by_label("Dismiss: Deploy failed");
317 assert_eq!(btn.role(), Some(Role::Button));
318 let pos = btn.bounds().center();
319 window.pointer_down(pos, MouseButton::Left, cx);
320 window.pointer_up(pos, MouseButton::Left, cx);
321 window.render_frame(cx);
322 });
323 assert_eq!(count.get(), 1);
324 }
325}