Skip to main content

gpui_material_components/
banner.rs

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_strings, 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/// Optional per-region colors for [`Banner`].
20///
21/// Explicit overrides always take precedence over [`SemanticTone`] defaults.
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct BannerColors {
24    /// Surface background color of the banner container.
25    pub container: Option<Hsla>,
26    /// Text color of the optional title line.
27    pub title: Option<Hsla>,
28    /// Text color of the banner message body.
29    pub message: Option<Hsla>,
30    /// Tint color applied to the optional leading icon.
31    pub icon: Option<Hsla>,
32    /// Color of the 1 px border surrounding the banner surface.
33    pub border: Option<Hsla>,
34    /// Icon tint color for the optional trailing dismiss button.
35    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/// An in-flow, non-blocking Material 3 banner/callout surface.
68///
69/// Visibility is owned by the caller; `Banner` keeps no internal hidden state.
70#[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: Option<SharedString>,
82    shape: CornerShape,
83    colors: BannerColors,
84    alert: Option<bool>,
85}
86
87impl Banner {
88    /// Creates an in-flow banner with a stable element ID and message text.
89    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: None,
101            shape: CornerRole::Medium.shape(),
102            colors: BannerColors::default(),
103            alert: None,
104        }
105    }
106
107    /// Sets an optional bold title line above the message.
108    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
109        self.title = Some(title.into());
110        self
111    }
112
113    /// Applies a Material 3 semantic tone palette.
114    ///
115    /// [`SemanticTone::Danger`] defaults to `Role::Alert` unless overridden via
116    /// [`Self::alert`]. Explicit [`Self::colors`] overrides always take precedence.
117    pub fn tone(mut self, tone: SemanticTone) -> Self {
118        self.tone = tone;
119        self
120    }
121
122    /// Sets an optional leading decorative icon tinted to the banner's icon color.
123    pub fn icon(mut self, icon: impl IntoElement) -> Self {
124        self.icon = Some(icon.into_any_element());
125        self
126    }
127
128    /// Sets the primary banner action button, inheriting the banner's semantic tone.
129    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    /// Sets an optional secondary banner action button, inheriting the banner's semantic tone.
139    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    /// Supplies optional custom action controls in the banner's action row.
149    pub fn actions_content(mut self, element: impl IntoElement) -> Self {
150        self.actions_content = Some(element.into_any_element());
151        self
152    }
153
154    /// Adds a trailing close [`IconButton`] that invokes `handler` when activated.
155    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    /// Sets the accessible label for the optional dismiss button. Defaults to
161    /// [`gpui_material_theme::MaterialStrings::dismiss`] (`"Dismiss"`).
162    pub fn dismiss_label(mut self, label: impl Into<SharedString>) -> Self {
163        self.dismiss_label = Some(label.into());
164        self
165    }
166
167    /// Sets the container corner shape. Defaults to `CornerRole::Medium`.
168    pub fn shape(mut self, shape: CornerShape) -> Self {
169        self.shape = shape;
170        self
171    }
172
173    /// Overrides banner region colors. Explicit values always take precedence over `.tone(...)`.
174    pub fn colors(mut self, colors: BannerColors) -> Self {
175        self.colors = colors;
176        self
177    }
178
179    /// Explicitly chooses `Role::Alert` (`true`) or `Role::Status` (`false`).
180    ///
181    /// When unset, [`SemanticTone::Danger`] uses `Role::Alert` and other tones use `Role::Status`.
182    pub fn alert(mut self, alert: bool) -> Self {
183        self.alert = Some(alert);
184        self
185    }
186
187    fn resolved_role(&self) -> Role {
188        let is_alert = self.alert.unwrap_or(self.tone == SemanticTone::Danger);
189        if is_alert { Role::Alert } else { Role::Status }
190    }
191}
192
193impl RenderOnce for Banner {
194    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
195        let role = self.resolved_role();
196        let roles = banner_tone_roles(self.tone);
197        let theme = current_material_theme(window, cx);
198        let direction = theme.layout.direction;
199        let rtl = direction == Direction::Rtl;
200        let theme_color = |r| color(theme.colors.color(r));
201
202        let container_color = self
203            .colors
204            .container
205            .unwrap_or_else(|| theme_color(roles.container));
206        let title_color = self
207            .colors
208            .title
209            .unwrap_or_else(|| theme_color(roles.content));
210        let message_color = self
211            .colors
212            .message
213            .unwrap_or_else(|| theme_color(roles.content));
214        let icon_color = self.colors.icon.unwrap_or_else(|| theme_color(roles.icon));
215        let border_color = self
216            .colors
217            .border
218            .unwrap_or_else(|| theme_color(roles.border));
219        let dismiss_color = self
220            .colors
221            .dismiss
222            .unwrap_or_else(|| theme_color(roles.dismiss));
223
224        let summary: SharedString = match &self.title {
225            Some(title) if !title.is_empty() => format!("{title}. {}", self.message).into(),
226            _ => self.message.clone(),
227        };
228
229        let icon_slot = self.icon.map(|icon| {
230            div()
231                .id((self.id.clone(), "icon"))
232                .test_support()
233                .flex_none()
234                .pt(px(2.))
235                .text_color(icon_color)
236                .text_size(px(20.))
237                .child(icon)
238        });
239
240        let title_slot = self.title.map(|title| {
241            wrapped_text(
242                title.clone(),
243                TypeRole::TitleSmall.style(TypographyEmphasis::Emphasized),
244                1.,
245                title_color,
246                window,
247                cx,
248            )
249            .w_full()
250            .when(rtl, Styled::text_right)
251            .id((self.id.clone(), "title"))
252            .test_support()
253            .role(Role::Label)
254            .aria_label(title)
255        });
256
257        let message_slot = wrapped_text(
258            self.message.clone(),
259            TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
260            1.,
261            message_color,
262            window,
263            cx,
264        )
265        .w_full()
266        .when(rtl, Styled::text_right)
267        .id((self.id.clone(), "message"))
268        .test_support()
269        .role(Role::Label)
270        .aria_label(self.message);
271
272        let primary_button = self.primary_action.map(|(label, handler)| {
273            Button::text((self.id.clone(), "action"), label)
274                .size(ControlSize::ExtraSmall)
275                .tone(self.tone)
276                .on_activate(move |window, cx| handler(window, cx))
277        });
278        let secondary_button = self.secondary_action.map(|(label, handler)| {
279            Button::text((self.id.clone(), "secondary-action"), label)
280                .size(ControlSize::ExtraSmall)
281                .tone(self.tone)
282                .on_activate(move |window, cx| handler(window, cx))
283        });
284
285        let has_actions = primary_button.is_some()
286            || secondary_button.is_some()
287            || self.actions_content.is_some();
288        let actions_slot = has_actions.then(|| {
289            div()
290                .id((self.id.clone(), "actions"))
291                .test_support()
292                .mt(px(8.))
293                .flex()
294                .flex_row()
295                .flex_wrap()
296                .items_center()
297                .gap(px(8.))
298                .when(rtl, Styled::flex_row_reverse)
299                .children(primary_button)
300                .children(secondary_button)
301                .children(self.actions_content)
302        });
303
304        let dismiss_label = self.dismiss_label.unwrap_or_else(|| {
305            SharedString::from(current_material_strings(window, cx).dismiss.clone())
306        });
307        let dismiss_slot = self.on_dismiss.map(|handler| {
308            div().flex_none().child(
309                IconButton::standard(
310                    (self.id.clone(), "dismiss"),
311                    dismiss_label,
312                    Icon::new(IconName::Close),
313                )
314                .size(ControlSize::ExtraSmall)
315                .colors(ButtonColors {
316                    content: Some(dismiss_color),
317                    ..Default::default()
318                })
319                .on_activate(move |window, cx| handler(window, cx)),
320            )
321        });
322
323        let surface = Surface::new(roles.container)
324            .container_color(container_color)
325            .content_color(message_color)
326            .shape(self.shape)
327            .border(SurfaceBorder {
328                width: px(1.),
329                color: border_color,
330            })
331            .w_full()
332            .px(px(16.))
333            .py(px(12.))
334            .flex()
335            .flex_row()
336            .items_start()
337            .gap(px(12.))
338            .when(rtl, Styled::flex_row_reverse)
339            .children(icon_slot)
340            .child(
341                div()
342                    .flex_1()
343                    .min_w_0()
344                    .flex()
345                    .flex_col()
346                    .gap(px(4.))
347                    .when(rtl, Styled::items_end)
348                    .children(title_slot)
349                    .child(message_slot)
350                    .children(actions_slot),
351            )
352            .children(dismiss_slot);
353
354        let live = if role == Role::Alert {
355            gpui::accesskit::Live::Assertive
356        } else {
357            gpui::accesskit::Live::Polite
358        };
359
360        div()
361            .id(self.id)
362            .test_support()
363            .role(role)
364            .aria_label(summary)
365            .a11y_synthetic_children(move |tree| {
366                let node = tree.parent_node();
367                node.set_live(live);
368                node.set_live_atomic();
369            })
370            .w_full()
371            .child(surface)
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn banner_tone_roles_and_alert_defaults_match_specification() {
381        use ColorRole::*;
382        assert_eq!(
383            banner_tone_roles(SemanticTone::Default),
384            BannerToneRoles {
385                container: SurfaceContainerLow,
386                content: OnSurface,
387                icon: Primary,
388                border: OutlineVariant,
389                dismiss: OnSurfaceVariant,
390            }
391        );
392        for (tone, role, container, on_container) in [
393            (
394                SemanticTone::Danger,
395                Error,
396                ErrorContainer,
397                OnErrorContainer,
398            ),
399            (
400                SemanticTone::Success,
401                Success,
402                SuccessContainer,
403                OnSuccessContainer,
404            ),
405            (
406                SemanticTone::Warning,
407                Warning,
408                WarningContainer,
409                OnWarningContainer,
410            ),
411            (SemanticTone::Info, Info, InfoContainer, OnInfoContainer),
412        ] {
413            assert_eq!(
414                banner_tone_roles(tone),
415                BannerToneRoles {
416                    container,
417                    content: on_container,
418                    icon: role,
419                    border: role,
420                    dismiss: on_container,
421                }
422            );
423        }
424
425        assert_eq!(Banner::new("b1", "Info").resolved_role(), Role::Status);
426        assert_eq!(
427            Banner::new("b2", "Error")
428                .tone(SemanticTone::Danger)
429                .resolved_role(),
430            Role::Alert
431        );
432        assert_eq!(
433            Banner::new("b3", "Error")
434                .tone(SemanticTone::Danger)
435                .alert(false)
436                .resolved_role(),
437            Role::Status
438        );
439        assert_eq!(
440            Banner::new("b4", "Notice").alert(true).resolved_role(),
441            Role::Alert
442        );
443    }
444}