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