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
9/// Decorative Material divider, with logical start and end insets.
10#[derive(IntoElement)]
11pub struct Divider {
12    axis: Axis,
13    thickness: gpui::Pixels,
14    color_role: ColorRole,
15    color_override: Option<gpui::Hsla>,
16    start: gpui::Pixels,
17    end: gpui::Pixels,
18}
19
20impl Divider {
21    const DEFAULT_THICKNESS: gpui::Pixels = px(1.);
22
23    pub fn horizontal() -> Self {
24        Self {
25            axis: Axis::Horizontal,
26            thickness: Self::DEFAULT_THICKNESS,
27            color_role: ColorRole::OutlineVariant,
28            color_override: None,
29            start: px(0.),
30            end: px(0.),
31        }
32    }
33
34    pub fn vertical() -> Self {
35        Self {
36            axis: Axis::Vertical,
37            ..Self::horizontal()
38        }
39    }
40
41    /// Sets the stroke thickness in logical pixels. Zero requests a one-device-pixel hairline.
42    /// Negative or non-finite values use the default thickness of one logical pixel.
43    pub fn thickness(mut self, thickness: gpui::Pixels) -> Self {
44        self.thickness = if f32::from(thickness).is_finite() && thickness >= px(0.) {
45            thickness
46        } else {
47            Self::DEFAULT_THICKNESS
48        };
49        self
50    }
51
52    /// Resolves the stroke color from the current window theme.
53    pub fn color(mut self, role: ColorRole) -> Self {
54        self.color_role = role;
55        self.color_override = None;
56        self
57    }
58
59    /// Sets a literal stroke color. A later call to `color` restores theme-role lookup.
60    pub fn color_override(mut self, color: impl Into<gpui::Hsla>) -> Self {
61        self.color_override = Some(color.into());
62        self
63    }
64
65    pub fn inset(mut self, start: gpui::Pixels, end: gpui::Pixels) -> Self {
66        self.start = start.max(px(0.));
67        self.end = end.max(px(0.));
68        self
69    }
70}
71
72impl RenderOnce for Divider {
73    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
74        let fill = self
75            .color_override
76            .unwrap_or_else(|| tone(self.color_role, window, cx));
77        let thickness = if self.thickness == px(0.) {
78            px(window.scale_factor().recip())
79        } else {
80            self.thickness
81        };
82        let (left, right) = current_material_theme(window, cx)
83            .layout
84            .horizontal(self.start, self.end);
85        if self.axis == Axis::Vertical {
86            div()
87                .w(thickness)
88                .h_full()
89                .pt(self.start)
90                .pb(self.end)
91                .child(div().size_full().bg(fill))
92        } else {
93            div()
94                .w_full()
95                .h(thickness)
96                .pl(left)
97                .pr(right)
98                .child(div().size_full().bg(fill))
99        }
100    }
101}
102
103/// A standalone or anchored Material badge. For anchored badges, include the
104/// badge's information in the host's accessible name.
105#[derive(IntoElement)]
106pub struct Badge {
107    host: Option<AnyElement>,
108    content: BadgeContent,
109    container_color: Option<Hsla>,
110    content_color: Option<Hsla>,
111    accessible_label: Option<(ElementId, SharedString)>,
112}
113
114enum BadgeContent {
115    Dot,
116    Text(SharedString),
117    Custom(ElementId, AnyElement),
118}
119
120impl Badge {
121    /// A small badge that participates in the surrounding layout.
122    pub fn standalone() -> Self {
123        Self {
124            host: None,
125            content: BadgeContent::Dot,
126            container_color: None,
127            content_color: None,
128            accessible_label: None,
129        }
130    }
131
132    /// Anchors a small badge to the host's upper trailing edge.
133    pub fn dot(host: impl IntoElement) -> Self {
134        Self {
135            host: Some(host.into_any_element()),
136            ..Self::standalone()
137        }
138    }
139
140    pub fn label(host: impl IntoElement, text: impl Into<SharedString>) -> Self {
141        Self {
142            content: BadgeContent::Text(text.into()),
143            ..Self::dot(host)
144        }
145    }
146
147    pub fn count(host: impl IntoElement, count: usize, maximum: usize) -> Self {
148        Self::label(
149            host,
150            if count > maximum {
151                format!("{maximum}+")
152            } else {
153                count.to_string()
154            },
155        )
156    }
157
158    /// Uses large badge styling with caller-supplied visual content.
159    ///
160    /// Use a stable ID within the parent and keep the content noninteractive.
161    /// The badge or its host supplies the accessible name.
162    pub fn content(mut self, id: impl Into<ElementId>, content: impl IntoElement) -> Self {
163        self.content = BadgeContent::Custom(id.into(), content.into_any_element());
164        self
165    }
166
167    /// Sets the background color, which defaults to the window theme's `Error` role.
168    pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
169        self.container_color = Some(color.into());
170        self
171    }
172
173    /// Sets the inherited content color, which defaults to the window theme's `OnError` role.
174    pub fn content_color(mut self, color: impl Into<Hsla>) -> Self {
175        self.content_color = Some(color.into());
176        self
177    }
178
179    /// Names a badge for assistive technology without adding a focus stop.
180    /// Anchored badges normally use their host's accessible name instead.
181    pub fn accessible_label(
182        mut self,
183        id: impl Into<ElementId>,
184        label: impl Into<SharedString>,
185    ) -> Self {
186        self.accessible_label = Some((id.into(), label.into()));
187        self
188    }
189
190    #[cfg(feature = "navigation")]
191    pub(crate) fn take_accessible_label(&mut self) -> Option<SharedString> {
192        self.accessible_label.take().map(|(_, label)| label)
193    }
194
195    #[cfg(feature = "navigation")]
196    pub(crate) fn attach_to(mut self, host: impl IntoElement) -> Self {
197        self.host = Some(host.into_any_element());
198        self
199    }
200}
201
202impl RenderOnce for Badge {
203    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
204        let large = !matches!(self.content, BadgeContent::Dot);
205        let side = px(if large { 16. } else { 6. });
206        let container_color = self
207            .container_color
208            .unwrap_or_else(|| tone(ColorRole::Error, window, cx));
209        let content_color = self
210            .content_color
211            .unwrap_or_else(|| tone(ColorRole::OnError, window, cx));
212        let typography = TypeRole::LabelSmall.style(TypographyEmphasis::Baseline);
213        let overlap = px(if large { 12. } else { 6. });
214        let mark = div()
215            .min_w(side)
216            .rounded_full()
217            .when(large, |badge| badge.px(px(4.)))
218            .when(self.host.is_some(), |badge| {
219                badge
220                    .absolute()
221                    .top(if large { px(-2.) } else { px(0.) })
222                    .when_else(
223                        current_material_theme(window, cx).layout.direction == Direction::Rtl,
224                        |badge| badge.right(gpui::relative(1.)).mr(-overlap),
225                        |badge| badge.left(gpui::relative(1.)).ml(-overlap),
226                    )
227            })
228            .bg(container_color)
229            .text_color(content_color)
230            .flex()
231            .items_center()
232            .justify_center();
233        let mark = match self.content {
234            BadgeContent::Dot => mark.h(side).w(side),
235            BadgeContent::Text(text) => mark.h(side).child(crate::text::single_line(
236                text,
237                typography,
238                1.,
239                content_color,
240                (None, 1., 1.),
241                window,
242                cx,
243            )),
244            BadgeContent::Custom(id, content) => {
245                text_style(mark.min_h(side), typography, 1., window, cx).child(
246                    div()
247                        .id(id)
248                        .role(Role::Group)
249                        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
250                        .child(content),
251                )
252            }
253        };
254        let mark = if let Some((id, label)) = self.accessible_label {
255            mark.id(id)
256                .role(Role::Label)
257                .aria_label(label)
258                .into_any_element()
259        } else {
260            mark.into_any_element()
261        };
262        if let Some(host) = self.host {
263            div().relative().child(host).child(mark)
264        } else {
265            div().flex().items_center().child(mark)
266        }
267    }
268}
269
270fn tone(role: ColorRole, window: &Window, cx: &App) -> gpui::Hsla {
271    color(current_material_theme(window, cx).colors.color(role))
272}