Skip to main content

gpui_material_components/
display.rs

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