Skip to main content

gpui_material_components/
empty_view.rs

1use gpui::{
2    AnyElement, App, ElementId, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce,
3    Role, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder,
4    px,
5};
6use gpui_base::TestSupportExt;
7use gpui_material_foundation::{
8    ShapePolygon, Surface, color, current_material_theme, wrapped_text,
9};
10use gpui_material_theme::{
11    ColorRole, CornerShape, Direction, MaterialShape, TypeRole, TypographyEmphasis,
12};
13
14const DEFAULT_MAX_WIDTH: Pixels = px(360.);
15const ICON_CONTAINER_SIZE: Pixels = px(72.);
16const ICON_SIZE: Pixels = px(32.);
17const ACTION_GAP: Pixels = px(12.);
18const ACTIONS_TOP_MARGIN: Pixels = px(24.);
19
20enum EmptyViewVisual {
21    Icon(AnyElement),
22    Custom(AnyElement),
23}
24
25enum SupportingSlot {
26    Text(SharedString),
27    Custom(AnyElement),
28}
29
30enum IconContainerShape {
31    Polygon(ShapePolygon),
32    Corners(CornerShape),
33}
34
35/// A purely presentational Material 3 Expressive empty-state layout shell.
36///
37/// Displays an optional decorative icon backdrop (or custom visual), title, optional
38/// supporting text or content, and optional centered primary/secondary actions.
39#[derive(IntoElement)]
40pub struct EmptyView {
41    id: ElementId,
42    title: SharedString,
43    title_role: TypeRole,
44    supporting: Option<SupportingSlot>,
45    visual: Option<EmptyViewVisual>,
46    icon_container_shape: IconContainerShape,
47    icon_container_role: ColorRole,
48    icon_content_role: ColorRole,
49    primary_action: Option<AnyElement>,
50    secondary_action: Option<AnyElement>,
51    max_width: Pixels,
52}
53
54impl EmptyView {
55    /// Creates an empty-state layout with a stable element ID and required title.
56    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
57        Self {
58            id: id.into(),
59            title: title.into(),
60            title_role: TypeRole::TitleLarge,
61            supporting: None,
62            visual: None,
63            icon_container_shape: IconContainerShape::Polygon(MaterialShape::Cookie7Sided.into()),
64            icon_container_role: ColorRole::SecondaryContainer,
65            icon_content_role: ColorRole::OnSecondaryContainer,
66            primary_action: None,
67            secondary_action: None,
68            max_width: DEFAULT_MAX_WIDTH,
69        }
70    }
71
72    /// Sets wrapped `BodyMedium` supporting copy below the title.
73    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
74        self.supporting = Some(SupportingSlot::Text(text.into()));
75        self
76    }
77
78    /// Replaces the supporting text slot with arbitrary visual content.
79    pub fn supporting_content(mut self, element: impl IntoElement) -> Self {
80        self.supporting = Some(SupportingSlot::Custom(element.into_any_element()));
81        self
82    }
83
84    /// Renders a decorative icon inside an expressive `Surface` container above the title.
85    pub fn icon(mut self, icon: impl IntoElement) -> Self {
86        self.visual = Some(EmptyViewVisual::Icon(icon.into_any_element()));
87        self
88    }
89
90    /// Sets the polygon backdrop shape for `.icon(...)` using any [`ShapePolygon`]
91    /// (including [`MaterialShape`] or [`PolygonRole`](gpui_material_theme::PolygonRole)).
92    /// Defaults to `MaterialShape::Cookie7Sided`.
93    pub fn icon_container_shape(mut self, shape: impl Into<ShapePolygon>) -> Self {
94        self.icon_container_shape = IconContainerShape::Polygon(shape.into());
95        self
96    }
97
98    /// Switches the `.icon(...)` container backdrop to a rounded [`CornerShape`].
99    pub fn shape(mut self, shape: CornerShape) -> Self {
100        self.icon_container_shape = IconContainerShape::Corners(shape);
101        self
102    }
103
104    /// Sets the semantic color roles for the decorative `.icon(...)` container and foreground.
105    /// Defaults to `SecondaryContainer` / `OnSecondaryContainer`.
106    pub fn icon_container_color_role(mut self, container: ColorRole, content: ColorRole) -> Self {
107        self.icon_container_role = container;
108        self.icon_content_role = content;
109        self
110    }
111
112    /// Replaces the decorative icon container with a custom visual illustration element.
113    pub fn visual(mut self, element: impl IntoElement) -> Self {
114        self.visual = Some(EmptyViewVisual::Custom(element.into_any_element()));
115        self
116    }
117
118    /// Adds a caller-provided primary action control to the centered action row.
119    pub fn primary_action(mut self, action: impl IntoElement) -> Self {
120        self.primary_action = Some(action.into_any_element());
121        self
122    }
123
124    /// Adds a caller-provided secondary action control to the centered action row.
125    pub fn secondary_action(mut self, action: impl IntoElement) -> Self {
126        self.secondary_action = Some(action.into_any_element());
127        self
128    }
129
130    /// Constrains the centered content column's maximum width in logical pixels.
131    /// Defaults to `360 dp`. Non-positive or non-finite values fall back to the default.
132    pub fn max_width(mut self, pixels: Pixels) -> Self {
133        self.max_width = resolve_max_width(pixels);
134        self
135    }
136
137    /// Sets the Material typography role used for the title. Defaults to `TypeRole::TitleLarge`.
138    pub fn title_role(mut self, role: TypeRole) -> Self {
139        self.title_role = role;
140        self
141    }
142}
143
144fn resolve_max_width(width: Pixels) -> Pixels {
145    let raw = f32::from(width);
146    if raw.is_finite() && raw > 0. {
147        width
148    } else {
149        DEFAULT_MAX_WIDTH
150    }
151}
152
153impl RenderOnce for EmptyView {
154    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
155        let theme = current_material_theme(window, cx);
156        let direction = theme.layout.direction;
157        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
158        let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
159        let icon_fg = color(theme.colors.color(self.icon_content_role));
160
161        let visual_slot = self.visual.map(|visual| match visual {
162            EmptyViewVisual::Icon(icon) => {
163                let surface = Surface::new(self.icon_container_role).content_color(icon_fg);
164                let surface = match self.icon_container_shape {
165                    IconContainerShape::Polygon(polygon) => surface.polygon_shape(polygon),
166                    IconContainerShape::Corners(corners) => surface.shape(corners),
167                };
168                div()
169                    .id((self.id.clone(), "icon-container"))
170                    .test_support()
171                    .mb(px(20.))
172                    .child(
173                        surface
174                            .size(ICON_CONTAINER_SIZE)
175                            .flex()
176                            .items_center()
177                            .justify_center()
178                            .text_size(ICON_SIZE)
179                            .child(icon),
180                    )
181                    .into_any_element()
182            }
183            EmptyViewVisual::Custom(element) => div()
184                .id((self.id.clone(), "visual"))
185                .test_support()
186                .mb(px(20.))
187                .flex()
188                .items_center()
189                .justify_center()
190                .child(element)
191                .into_any_element(),
192        });
193
194        let title = wrapped_text(
195            self.title.clone(),
196            self.title_role.style(TypographyEmphasis::Baseline),
197            1.,
198            on_surface,
199            window,
200            cx,
201        )
202        .w_full()
203        .text_center()
204        .id((self.id.clone(), "title"))
205        .test_support()
206        .role(Role::Label)
207        .aria_value(self.title.clone())
208        .aria_label(self.title);
209
210        let supporting_slot = self.supporting.map(|slot| match slot {
211            SupportingSlot::Text(text) => div()
212                .w_full()
213                .mt(px(8.))
214                .child(
215                    wrapped_text(
216                        text.clone(),
217                        TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
218                        1.,
219                        on_surface_variant,
220                        window,
221                        cx,
222                    )
223                    .w_full()
224                    .text_center()
225                    .id((self.id.clone(), "supporting"))
226                    .test_support()
227                    .role(Role::Label)
228                    .aria_value(text.clone())
229                    .aria_label(text),
230                )
231                .into_any_element(),
232            SupportingSlot::Custom(element) => div()
233                .id((self.id.clone(), "supporting"))
234                .test_support()
235                .w_full()
236                .mt(px(8.))
237                .flex()
238                .justify_center()
239                .child(element)
240                .into_any_element(),
241        });
242
243        let has_actions = self.primary_action.is_some() || self.secondary_action.is_some();
244        let actions_slot = has_actions.then(|| {
245            div()
246                .id((self.id.clone(), "actions"))
247                .test_support()
248                .mt(ACTIONS_TOP_MARGIN)
249                .flex()
250                .flex_row()
251                .flex_wrap()
252                .items_center()
253                .justify_center()
254                .gap(ACTION_GAP)
255                .when(direction == Direction::Rtl, Styled::flex_row_reverse)
256                .children(self.primary_action)
257                .children(self.secondary_action)
258        });
259
260        div()
261            .id(self.id.clone())
262            .test_support()
263            .w_full()
264            .flex()
265            .flex_col()
266            .items_center()
267            .justify_center()
268            .px(px(24.))
269            .py(px(32.))
270            .child(
271                div()
272                    .id((self.id, "content"))
273                    .test_support()
274                    .w_full()
275                    .max_w(self.max_width)
276                    .flex()
277                    .flex_col()
278                    .items_center()
279                    .children(visual_slot)
280                    .child(title)
281                    .children(supporting_slot)
282                    .children(actions_slot),
283            )
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn empty_state_max_width_clamps_invalid_values_to_default() {
293        assert_eq!(resolve_max_width(px(420.)), px(420.));
294        assert_eq!(resolve_max_width(px(0.)), DEFAULT_MAX_WIDTH);
295        assert_eq!(resolve_max_width(px(-120.)), DEFAULT_MAX_WIDTH);
296        assert_eq!(resolve_max_width(px(f32::NAN)), DEFAULT_MAX_WIDTH);
297        assert_eq!(resolve_max_width(px(f32::INFINITY)), DEFAULT_MAX_WIDTH);
298    }
299}