Skip to main content

gpui_material_components/
display.rs

1use gpui::{
2    AnyElement, App, Axis, ElementId, Empty, Hsla, InteractiveElement, IntoElement, ParentElement,
3    Pixels, Point, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window, div,
4    prelude::FluentBuilder, px,
5};
6use gpui_base::TestSupportExt;
7use gpui_material_foundation::{color, current_material_theme, text_style};
8use gpui_material_theme::{ColorRole, Direction, TypeRole, TypographyEmphasis};
9
10use crate::SemanticTone;
11
12/// Decorative Material divider, with logical start and end insets.
13#[derive(IntoElement)]
14pub struct Divider {
15    axis: Axis,
16    thickness: gpui::Pixels,
17    color_role: ColorRole,
18    color_override: Option<gpui::Hsla>,
19    start: gpui::Pixels,
20    end: gpui::Pixels,
21}
22
23impl Divider {
24    const DEFAULT_THICKNESS: gpui::Pixels = px(1.);
25
26    pub fn horizontal() -> Self {
27        Self {
28            axis: Axis::Horizontal,
29            thickness: Self::DEFAULT_THICKNESS,
30            color_role: ColorRole::OutlineVariant,
31            color_override: None,
32            start: px(0.),
33            end: px(0.),
34        }
35    }
36
37    pub fn vertical() -> Self {
38        Self {
39            axis: Axis::Vertical,
40            ..Self::horizontal()
41        }
42    }
43
44    /// Sets the stroke thickness in logical pixels. Zero requests a one-device-pixel hairline.
45    /// Negative or non-finite values use the default thickness of one logical pixel.
46    pub fn thickness(mut self, thickness: gpui::Pixels) -> Self {
47        self.thickness = if f32::from(thickness).is_finite() && thickness >= px(0.) {
48            thickness
49        } else {
50            Self::DEFAULT_THICKNESS
51        };
52        self
53    }
54
55    /// Resolves the stroke color from the current window theme.
56    pub fn color(mut self, role: ColorRole) -> Self {
57        self.color_role = role;
58        self.color_override = None;
59        self
60    }
61
62    /// Sets a literal stroke color. A later call to `color` restores theme-role lookup.
63    pub fn color_override(mut self, color: impl Into<gpui::Hsla>) -> Self {
64        self.color_override = Some(color.into());
65        self
66    }
67
68    pub fn inset(mut self, start: gpui::Pixels, end: gpui::Pixels) -> Self {
69        self.start = start.max(px(0.));
70        self.end = end.max(px(0.));
71        self
72    }
73}
74
75impl RenderOnce for Divider {
76    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
77        let fill = self
78            .color_override
79            .unwrap_or_else(|| tone(self.color_role, window, cx));
80        let thickness = if self.thickness == px(0.) {
81            px(window.scale_factor().recip())
82        } else {
83            self.thickness
84        };
85        let (left, right) = current_material_theme(window, cx)
86            .layout
87            .horizontal(self.start, self.end);
88        if self.axis == Axis::Vertical {
89            div()
90                .w(thickness)
91                .h_full()
92                .pt(self.start)
93                .pb(self.end)
94                .child(div().size_full().bg(fill))
95        } else {
96            div()
97                .w_full()
98                .h(thickness)
99                .pl(left)
100                .pr(right)
101                .child(div().size_full().bg(fill))
102        }
103    }
104}
105
106/// A standalone or anchored Material badge. For anchored badges, include the
107/// badge's information in the host's accessible name.
108#[derive(IntoElement)]
109pub struct Badge {
110    host: Option<AnyElement>,
111    content: BadgeContent,
112    tone: SemanticTone,
113    color_roles: Option<(ColorRole, ColorRole)>,
114    container_color: Option<Hsla>,
115    content_color: Option<Hsla>,
116    accessible_label: Option<(ElementId, SharedString)>,
117    visible: bool,
118    offset: Point<Pixels>,
119}
120
121enum BadgeContent {
122    Dot,
123    Text(SharedString),
124    Custom(ElementId, AnyElement),
125}
126
127fn format_badge_count(count: usize, maximum: usize) -> SharedString {
128    if count > maximum {
129        format!("{maximum}+").into()
130    } else {
131        count.to_string().into()
132    }
133}
134
135fn resolve_badge_roles(
136    tone: SemanticTone,
137    color_roles: Option<(ColorRole, ColorRole)>,
138) -> (ColorRole, ColorRole) {
139    color_roles.unwrap_or_else(|| {
140        tone.roles().map_or(
141            (ColorRole::Error, ColorRole::OnError),
142            |(role, on_role, _, _)| (role, on_role),
143        )
144    })
145}
146
147impl Badge {
148    /// A small badge that participates in the surrounding layout.
149    pub fn standalone() -> Self {
150        Self {
151            host: None,
152            content: BadgeContent::Dot,
153            tone: SemanticTone::Default,
154            color_roles: None,
155            container_color: None,
156            content_color: None,
157            accessible_label: None,
158            visible: true,
159            offset: Point::default(),
160        }
161    }
162
163    /// A standalone text badge that participates in the surrounding layout.
164    pub fn standalone_label(text: impl Into<SharedString>) -> Self {
165        Self {
166            content: BadgeContent::Text(text.into()),
167            ..Self::standalone()
168        }
169    }
170
171    /// A standalone capped numeric badge that participates in the surrounding layout.
172    pub fn standalone_count(count: usize, maximum: usize) -> Self {
173        Self::standalone_label(format_badge_count(count, maximum))
174    }
175
176    /// Anchors a small badge to the host's upper trailing edge.
177    pub fn dot(host: impl IntoElement) -> Self {
178        Self {
179            host: Some(host.into_any_element()),
180            ..Self::standalone()
181        }
182    }
183
184    pub fn label(host: impl IntoElement, text: impl Into<SharedString>) -> Self {
185        Self {
186            content: BadgeContent::Text(text.into()),
187            ..Self::dot(host)
188        }
189    }
190
191    pub fn count(host: impl IntoElement, count: usize, maximum: usize) -> Self {
192        Self::label(host, format_badge_count(count, maximum))
193    }
194
195    /// Uses large badge styling with caller-supplied visual content.
196    ///
197    /// Use a stable ID within the parent and keep the content noninteractive.
198    /// The badge or its host supplies the accessible name.
199    pub fn content(mut self, id: impl Into<ElementId>, content: impl IntoElement) -> Self {
200        self.content = BadgeContent::Custom(id.into(), content.into_any_element());
201        self
202    }
203
204    /// Applies a Material 3 semantic tone shortcut.
205    ///
206    /// [`SemanticTone::Default`] and [`SemanticTone::Danger`] use `Error`/`OnError`.
207    /// Explicit [`Self::color_role`], [`Self::container_color`], and
208    /// [`Self::content_color`] overrides take precedence.
209    pub fn tone(mut self, tone: SemanticTone) -> Self {
210        self.tone = tone;
211        self
212    }
213
214    /// Resolves container and content pigments from the window theme's semantic color roles.
215    ///
216    /// Takes precedence over [`Self::tone`], and is overridden by explicit
217    /// [`Self::container_color`] and [`Self::content_color`] values.
218    pub fn color_role(mut self, container: ColorRole, content: ColorRole) -> Self {
219        self.color_roles = Some((container, content));
220        self
221    }
222
223    /// Sets the background color, overriding [`Self::color_role`] and [`Self::tone`].
224    pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
225        self.container_color = Some(color.into());
226        self
227    }
228
229    /// Sets the inherited content color, overriding [`Self::color_role`] and [`Self::tone`].
230    pub fn content_color(mut self, color: impl Into<Hsla>) -> Self {
231        self.content_color = Some(color.into());
232        self
233    }
234
235    /// Controls whether the badge mark is rendered. When `false`, anchored badges render only
236    /// their host and standalone badges render empty. Defaults to `true`.
237    pub fn visible(mut self, visible: bool) -> Self {
238        self.visible = visible;
239        self
240    }
241
242    /// Shifts an anchored badge from its default upper-trailing anchor (`x` follows logical
243    /// direction; `y` shifts downward).
244    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
245        self.offset = offset;
246        self
247    }
248
249    /// Names a badge for assistive technology without adding a focus stop.
250    /// Anchored badges normally use their host's accessible name instead.
251    pub fn accessible_label(
252        mut self,
253        id: impl Into<ElementId>,
254        label: impl Into<SharedString>,
255    ) -> Self {
256        self.accessible_label = Some((id.into(), label.into()));
257        self
258    }
259
260    #[cfg(feature = "navigation")]
261    pub(crate) fn take_accessible_label(&mut self) -> Option<SharedString> {
262        if !self.visible {
263            return None;
264        }
265        self.accessible_label.take().map(|(_, label)| label)
266    }
267
268    #[cfg(feature = "navigation")]
269    pub(crate) fn attach_to(mut self, host: impl IntoElement) -> Self {
270        self.host = Some(host.into_any_element());
271        self
272    }
273}
274
275impl RenderOnce for Badge {
276    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
277        if !self.visible {
278            return self.host.unwrap_or_else(|| Empty.into_any_element());
279        }
280        let large = !matches!(self.content, BadgeContent::Dot);
281        let side = px(if large { 16. } else { 6. });
282        let (container_role, content_role) = resolve_badge_roles(self.tone, self.color_roles);
283        let container_color = self
284            .container_color
285            .unwrap_or_else(|| tone(container_role, window, cx));
286        let content_color = self
287            .content_color
288            .unwrap_or_else(|| tone(content_role, window, cx));
289        let typography = TypeRole::LabelSmall.style(TypographyEmphasis::Baseline);
290        let overlap = px(if large { 12. } else { 6. });
291        let dx = if f32::from(self.offset.x).is_finite() {
292            self.offset.x
293        } else {
294            px(0.)
295        };
296        let dy = if f32::from(self.offset.y).is_finite() {
297            self.offset.y
298        } else {
299            px(0.)
300        };
301        let mark = div()
302            .min_w(side)
303            .rounded_full()
304            .when(large, |badge| badge.px(px(4.)))
305            .when(self.host.is_some(), |badge| {
306                badge
307                    .absolute()
308                    .top(if large { px(-2.) } else { px(0.) } + dy)
309                    .when_else(
310                        current_material_theme(window, cx).layout.direction == Direction::Rtl,
311                        |badge| badge.right(gpui::relative(1.)).mr(-overlap + dx),
312                        |badge| badge.left(gpui::relative(1.)).ml(-overlap + dx),
313                    )
314            })
315            .bg(container_color)
316            .text_color(content_color)
317            .flex()
318            .items_center()
319            .justify_center();
320        let mark = match self.content {
321            BadgeContent::Dot => mark.h(side).w(side),
322            BadgeContent::Text(text) => mark.min_h(side).child(crate::text::single_line(
323                text,
324                typography,
325                1.,
326                content_color,
327                (None, 1., 1.),
328                window,
329                cx,
330            )),
331            BadgeContent::Custom(id, content) => {
332                text_style(mark.min_h(side), typography, 1., window, cx).child(
333                    div()
334                        .id(id)
335                        .role(Role::Group)
336                        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
337                        .child(content),
338                )
339            }
340        };
341        let mark = if let Some((id, label)) = self.accessible_label {
342            mark.id(id)
343                .test_support()
344                .role(Role::Label)
345                .aria_label(label)
346                .into_any_element()
347        } else {
348            mark.into_any_element()
349        };
350        if let Some(host) = self.host {
351            div().relative().child(host).child(mark).into_any_element()
352        } else {
353            div().flex().items_center().child(mark).into_any_element()
354        }
355    }
356}
357
358fn tone(role: ColorRole, window: &Window, cx: &App) -> gpui::Hsla {
359    color(current_material_theme(window, cx).colors.color(role))
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn badge_roles_follow_tone_and_explicit_color_role_precedence() {
368        use ColorRole::*;
369        assert_eq!(
370            resolve_badge_roles(SemanticTone::Default, None),
371            (Error, OnError)
372        );
373        assert_eq!(
374            resolve_badge_roles(SemanticTone::Danger, None),
375            (Error, OnError)
376        );
377        assert_eq!(
378            resolve_badge_roles(SemanticTone::Success, None),
379            (Success, OnSuccess)
380        );
381        assert_eq!(
382            resolve_badge_roles(SemanticTone::Warning, None),
383            (Warning, OnWarning)
384        );
385        assert_eq!(
386            resolve_badge_roles(SemanticTone::Info, None),
387            (Info, OnInfo)
388        );
389        assert_eq!(
390            resolve_badge_roles(
391                SemanticTone::Danger,
392                Some((PrimaryContainer, OnPrimaryContainer))
393            ),
394            (PrimaryContainer, OnPrimaryContainer)
395        );
396    }
397
398    #[test]
399    fn standalone_badge_constructors_format_labels_and_capped_counts() {
400        assert_eq!(format_badge_count(0, 99), SharedString::from("0"));
401        assert_eq!(format_badge_count(99, 99), SharedString::from("99"));
402        assert_eq!(format_badge_count(120, 99), SharedString::from("99+"));
403
404        let label = Badge::standalone_label("NEW");
405        assert!(label.host.is_none());
406        assert!(matches!(label.content, BadgeContent::Text(ref text) if text == "NEW"));
407
408        let count = Badge::standalone_count(150, 99);
409        assert!(count.host.is_none());
410        assert!(matches!(count.content, BadgeContent::Text(ref text) if text == "99+"));
411    }
412}