1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce,
5 Role, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder,
6 px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{
10 Surface, SurfaceBorder, color, current_material_theme, wrapped_text,
11};
12use gpui_material_theme::{
13 ColorRole, CornerRole, CornerShape, Direction, TypeRole, TypographyEmphasis,
14};
15
16use crate::action::Activate;
17use crate::{Button, ButtonColors, ControlSize, Icon, IconButton, IconName, SemanticTone};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct BannerColors {
24 pub container: Option<Hsla>,
26 pub title: Option<Hsla>,
28 pub message: Option<Hsla>,
30 pub icon: Option<Hsla>,
32 pub border: Option<Hsla>,
34 pub dismiss: Option<Hsla>,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39struct BannerToneRoles {
40 container: ColorRole,
41 content: ColorRole,
42 icon: ColorRole,
43 border: ColorRole,
44 dismiss: ColorRole,
45}
46
47const fn banner_tone_roles(tone: SemanticTone) -> BannerToneRoles {
48 use ColorRole::*;
49 match tone.roles() {
50 Some((role, _, container, on_container)) => BannerToneRoles {
51 container,
52 content: on_container,
53 icon: role,
54 border: role,
55 dismiss: on_container,
56 },
57 None => BannerToneRoles {
58 container: SurfaceContainerLow,
59 content: OnSurface,
60 icon: Primary,
61 border: OutlineVariant,
62 dismiss: OnSurfaceVariant,
63 },
64 }
65}
66
67#[derive(IntoElement)]
71pub struct Banner {
72 id: ElementId,
73 message: SharedString,
74 title: Option<SharedString>,
75 tone: SemanticTone,
76 icon: Option<AnyElement>,
77 primary_action: Option<(SharedString, Activate)>,
78 secondary_action: Option<(SharedString, Activate)>,
79 actions_content: Option<AnyElement>,
80 on_dismiss: Option<Activate>,
81 dismiss_label: SharedString,
82 shape: CornerShape,
83 colors: BannerColors,
84 alert: Option<bool>,
85}
86
87impl Banner {
88 pub fn new(id: impl Into<ElementId>, message: impl Into<SharedString>) -> Self {
90 Self {
91 id: id.into(),
92 message: message.into(),
93 title: None,
94 tone: SemanticTone::Default,
95 icon: None,
96 primary_action: None,
97 secondary_action: None,
98 actions_content: None,
99 on_dismiss: None,
100 dismiss_label: "Dismiss".into(),
101 shape: CornerRole::Medium.shape(),
102 colors: BannerColors::default(),
103 alert: None,
104 }
105 }
106
107 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
109 self.title = Some(title.into());
110 self
111 }
112
113 pub fn tone(mut self, tone: SemanticTone) -> Self {
118 self.tone = tone;
119 self
120 }
121
122 pub fn icon(mut self, icon: impl IntoElement) -> Self {
124 self.icon = Some(icon.into_any_element());
125 self
126 }
127
128 pub fn action(
130 mut self,
131 label: impl Into<SharedString>,
132 handler: impl Fn(&mut Window, &mut App) + 'static,
133 ) -> Self {
134 self.primary_action = Some((label.into(), Rc::new(handler)));
135 self
136 }
137
138 pub fn secondary_action(
140 mut self,
141 label: impl Into<SharedString>,
142 handler: impl Fn(&mut Window, &mut App) + 'static,
143 ) -> Self {
144 self.secondary_action = Some((label.into(), Rc::new(handler)));
145 self
146 }
147
148 pub fn actions_content(mut self, element: impl IntoElement) -> Self {
150 self.actions_content = Some(element.into_any_element());
151 self
152 }
153
154 pub fn on_dismiss(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
156 self.on_dismiss = Some(Rc::new(handler));
157 self
158 }
159
160 pub fn dismiss_label(mut self, label: impl Into<SharedString>) -> Self {
162 self.dismiss_label = label.into();
163 self
164 }
165
166 pub fn shape(mut self, shape: CornerShape) -> Self {
168 self.shape = shape;
169 self
170 }
171
172 pub fn colors(mut self, colors: BannerColors) -> Self {
174 self.colors = colors;
175 self
176 }
177
178 pub fn alert(mut self, alert: bool) -> Self {
182 self.alert = Some(alert);
183 self
184 }
185
186 fn resolved_role(&self) -> Role {
187 let is_alert = self.alert.unwrap_or(self.tone == SemanticTone::Danger);
188 if is_alert { Role::Alert } else { Role::Status }
189 }
190}
191
192impl RenderOnce for Banner {
193 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
194 let role = self.resolved_role();
195 let roles = banner_tone_roles(self.tone);
196 let theme = current_material_theme(window, cx);
197 let direction = theme.layout.direction;
198 let rtl = direction == Direction::Rtl;
199 let theme_color = |r| color(theme.colors.color(r));
200
201 let container_color = self
202 .colors
203 .container
204 .unwrap_or_else(|| theme_color(roles.container));
205 let title_color = self
206 .colors
207 .title
208 .unwrap_or_else(|| theme_color(roles.content));
209 let message_color = self
210 .colors
211 .message
212 .unwrap_or_else(|| theme_color(roles.content));
213 let icon_color = self.colors.icon.unwrap_or_else(|| theme_color(roles.icon));
214 let border_color = self
215 .colors
216 .border
217 .unwrap_or_else(|| theme_color(roles.border));
218 let dismiss_color = self
219 .colors
220 .dismiss
221 .unwrap_or_else(|| theme_color(roles.dismiss));
222
223 let summary: SharedString = match &self.title {
224 Some(title) if !title.is_empty() => format!("{title}. {}", self.message).into(),
225 _ => self.message.clone(),
226 };
227
228 let icon_slot = self.icon.map(|icon| {
229 div()
230 .id((self.id.clone(), "icon"))
231 .test_support()
232 .flex_none()
233 .pt(px(2.))
234 .text_color(icon_color)
235 .text_size(px(20.))
236 .child(icon)
237 });
238
239 let title_slot = self.title.map(|title| {
240 wrapped_text(
241 title.clone(),
242 TypeRole::TitleSmall.style(TypographyEmphasis::Emphasized),
243 1.,
244 title_color,
245 window,
246 cx,
247 )
248 .w_full()
249 .when(rtl, Styled::text_right)
250 .id((self.id.clone(), "title"))
251 .test_support()
252 .role(Role::Label)
253 .aria_label(title)
254 });
255
256 let message_slot = wrapped_text(
257 self.message.clone(),
258 TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
259 1.,
260 message_color,
261 window,
262 cx,
263 )
264 .w_full()
265 .when(rtl, Styled::text_right)
266 .id((self.id.clone(), "message"))
267 .test_support()
268 .role(Role::Label)
269 .aria_label(self.message);
270
271 let primary_button = self.primary_action.map(|(label, handler)| {
272 Button::text((self.id.clone(), "action"), label)
273 .size(ControlSize::ExtraSmall)
274 .tone(self.tone)
275 .on_activate(move |window, cx| handler(window, cx))
276 });
277 let secondary_button = self.secondary_action.map(|(label, handler)| {
278 Button::text((self.id.clone(), "secondary-action"), label)
279 .size(ControlSize::ExtraSmall)
280 .tone(self.tone)
281 .on_activate(move |window, cx| handler(window, cx))
282 });
283
284 let has_actions = primary_button.is_some()
285 || secondary_button.is_some()
286 || self.actions_content.is_some();
287 let actions_slot = has_actions.then(|| {
288 div()
289 .id((self.id.clone(), "actions"))
290 .test_support()
291 .mt(px(8.))
292 .flex()
293 .flex_row()
294 .flex_wrap()
295 .items_center()
296 .gap(px(8.))
297 .when(rtl, Styled::flex_row_reverse)
298 .children(primary_button)
299 .children(secondary_button)
300 .children(self.actions_content)
301 });
302
303 let dismiss_slot = self.on_dismiss.map(|handler| {
304 div().flex_none().child(
305 IconButton::standard(
306 (self.id.clone(), "dismiss"),
307 self.dismiss_label,
308 Icon::new(IconName::Close),
309 )
310 .size(ControlSize::ExtraSmall)
311 .colors(ButtonColors {
312 content: Some(dismiss_color),
313 ..Default::default()
314 })
315 .on_activate(move |window, cx| handler(window, cx)),
316 )
317 });
318
319 let surface = Surface::new(roles.container)
320 .container_color(container_color)
321 .content_color(message_color)
322 .shape(self.shape)
323 .border(SurfaceBorder {
324 width: px(1.),
325 color: border_color,
326 })
327 .w_full()
328 .px(px(16.))
329 .py(px(12.))
330 .flex()
331 .flex_row()
332 .items_start()
333 .gap(px(12.))
334 .when(rtl, Styled::flex_row_reverse)
335 .children(icon_slot)
336 .child(
337 div()
338 .flex_1()
339 .min_w_0()
340 .flex()
341 .flex_col()
342 .gap(px(4.))
343 .when(rtl, Styled::items_end)
344 .children(title_slot)
345 .child(message_slot)
346 .children(actions_slot),
347 )
348 .children(dismiss_slot);
349
350 div()
351 .id(self.id)
352 .test_support()
353 .role(role)
354 .aria_label(summary)
355 .w_full()
356 .child(surface)
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn banner_tone_roles_and_alert_defaults_match_specification() {
366 use ColorRole::*;
367 assert_eq!(
368 banner_tone_roles(SemanticTone::Default),
369 BannerToneRoles {
370 container: SurfaceContainerLow,
371 content: OnSurface,
372 icon: Primary,
373 border: OutlineVariant,
374 dismiss: OnSurfaceVariant,
375 }
376 );
377 for (tone, role, container, on_container) in [
378 (
379 SemanticTone::Danger,
380 Error,
381 ErrorContainer,
382 OnErrorContainer,
383 ),
384 (
385 SemanticTone::Success,
386 Success,
387 SuccessContainer,
388 OnSuccessContainer,
389 ),
390 (
391 SemanticTone::Warning,
392 Warning,
393 WarningContainer,
394 OnWarningContainer,
395 ),
396 (SemanticTone::Info, Info, InfoContainer, OnInfoContainer),
397 ] {
398 assert_eq!(
399 banner_tone_roles(tone),
400 BannerToneRoles {
401 container,
402 content: on_container,
403 icon: role,
404 border: role,
405 dismiss: on_container,
406 }
407 );
408 }
409
410 assert_eq!(Banner::new("b1", "Info").resolved_role(), Role::Status);
411 assert_eq!(
412 Banner::new("b2", "Error")
413 .tone(SemanticTone::Danger)
414 .resolved_role(),
415 Role::Alert
416 );
417 assert_eq!(
418 Banner::new("b3", "Error")
419 .tone(SemanticTone::Danger)
420 .alert(false)
421 .resolved_role(),
422 Role::Status
423 );
424 assert_eq!(
425 Banner::new("b4", "Notice").alert(true).resolved_role(),
426 Role::Alert
427 );
428 }
429}