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#[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 {
28 Self {
29 axis: Axis::Horizontal,
30 thickness: Self::DEFAULT_THICKNESS,
31 color_role: ColorRole::OutlineVariant,
32 color_override: None,
33 start: px(0.),
34 end: px(0.),
35 }
36 }
37
38 pub fn vertical() -> Self {
40 Self {
41 axis: Axis::Vertical,
42 ..Self::horizontal()
43 }
44 }
45
46 pub fn thickness(mut self, thickness: gpui::Pixels) -> Self {
49 self.thickness = if f32::from(thickness).is_finite() && thickness >= px(0.) {
50 thickness
51 } else {
52 Self::DEFAULT_THICKNESS
53 };
54 self
55 }
56
57 pub fn color(mut self, role: ColorRole) -> Self {
59 self.color_role = role;
60 self.color_override = None;
61 self
62 }
63
64 pub fn color_override(mut self, color: impl Into<gpui::Hsla>) -> Self {
66 self.color_override = Some(color.into());
67 self
68 }
69
70 pub fn inset(mut self, start: gpui::Pixels, end: gpui::Pixels) -> Self {
72 self.start = start.max(px(0.));
73 self.end = end.max(px(0.));
74 self
75 }
76}
77
78impl RenderOnce for Divider {
79 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
80 let fill = self
81 .color_override
82 .unwrap_or_else(|| tone(self.color_role, window, cx));
83 let thickness = if self.thickness == px(0.) {
84 px(window.scale_factor().recip())
85 } else {
86 self.thickness
87 };
88 let (left, right) = current_material_theme(window, cx)
89 .layout
90 .horizontal(self.start, self.end);
91 if self.axis == Axis::Vertical {
92 div()
93 .w(thickness)
94 .h_full()
95 .pt(self.start)
96 .pb(self.end)
97 .child(div().size_full().bg(fill))
98 } else {
99 div()
100 .w_full()
101 .h(thickness)
102 .pl(left)
103 .pr(right)
104 .child(div().size_full().bg(fill))
105 }
106 }
107}
108
109#[derive(IntoElement)]
112pub struct Badge {
113 host: Option<AnyElement>,
114 content: BadgeContent,
115 tone: SemanticTone,
116 color_roles: Option<(ColorRole, ColorRole)>,
117 container_color: Option<Hsla>,
118 content_color: Option<Hsla>,
119 accessible_label: Option<(ElementId, SharedString)>,
120 visible: bool,
121 offset: Point<Pixels>,
122}
123
124enum BadgeContent {
125 Dot,
126 Text(SharedString),
127 Custom(ElementId, AnyElement),
128}
129
130fn format_badge_count(count: usize, maximum: usize) -> SharedString {
131 if count > maximum {
132 format!("{maximum}+").into()
133 } else {
134 count.to_string().into()
135 }
136}
137
138fn resolve_badge_roles(
139 tone: SemanticTone,
140 color_roles: Option<(ColorRole, ColorRole)>,
141) -> (ColorRole, ColorRole) {
142 color_roles.unwrap_or_else(|| {
143 tone.roles().map_or(
144 (ColorRole::Error, ColorRole::OnError),
145 |(role, on_role, _, _)| (role, on_role),
146 )
147 })
148}
149
150impl Badge {
151 pub fn standalone() -> Self {
153 Self {
154 host: None,
155 content: BadgeContent::Dot,
156 tone: SemanticTone::Default,
157 color_roles: None,
158 container_color: None,
159 content_color: None,
160 accessible_label: None,
161 visible: true,
162 offset: Point::default(),
163 }
164 }
165
166 pub fn standalone_label(text: impl Into<SharedString>) -> Self {
168 Self {
169 content: BadgeContent::Text(text.into()),
170 ..Self::standalone()
171 }
172 }
173
174 pub fn standalone_count(count: usize, maximum: usize) -> Self {
176 Self::standalone_label(format_badge_count(count, maximum))
177 }
178
179 pub fn dot(host: impl IntoElement) -> Self {
181 Self {
182 host: Some(host.into_any_element()),
183 ..Self::standalone()
184 }
185 }
186
187 pub fn label(host: impl IntoElement, text: impl Into<SharedString>) -> Self {
189 Self {
190 content: BadgeContent::Text(text.into()),
191 ..Self::dot(host)
192 }
193 }
194
195 pub fn count(host: impl IntoElement, count: usize, maximum: usize) -> Self {
197 Self::label(host, format_badge_count(count, maximum))
198 }
199
200 pub fn content(mut self, id: impl Into<ElementId>, content: impl IntoElement) -> Self {
205 self.content = BadgeContent::Custom(id.into(), content.into_any_element());
206 self
207 }
208
209 pub fn tone(mut self, tone: SemanticTone) -> Self {
215 self.tone = tone;
216 self
217 }
218
219 pub fn color_role(mut self, container: ColorRole, content: ColorRole) -> Self {
224 self.color_roles = Some((container, content));
225 self
226 }
227
228 pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
230 self.container_color = Some(color.into());
231 self
232 }
233
234 pub fn content_color(mut self, color: impl Into<Hsla>) -> Self {
236 self.content_color = Some(color.into());
237 self
238 }
239
240 pub fn visible(mut self, visible: bool) -> Self {
243 self.visible = visible;
244 self
245 }
246
247 pub fn offset(mut self, offset: Point<Pixels>) -> Self {
250 self.offset = offset;
251 self
252 }
253
254 pub fn accessible_label(
257 mut self,
258 id: impl Into<ElementId>,
259 label: impl Into<SharedString>,
260 ) -> Self {
261 self.accessible_label = Some((id.into(), label.into()));
262 self
263 }
264
265 #[cfg(feature = "navigation")]
266 pub(crate) fn take_accessible_label(&mut self) -> Option<SharedString> {
267 if !self.visible {
268 return None;
269 }
270 self.accessible_label.take().map(|(_, label)| label)
271 }
272
273 #[cfg(feature = "navigation")]
274 pub(crate) fn attach_to(mut self, host: impl IntoElement) -> Self {
275 self.host = Some(host.into_any_element());
276 self
277 }
278}
279
280impl RenderOnce for Badge {
281 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
282 if !self.visible {
283 return self.host.unwrap_or_else(|| Empty.into_any_element());
284 }
285 let large = !matches!(self.content, BadgeContent::Dot);
286 let side = px(if large { 16. } else { 6. });
287 let (container_role, content_role) = resolve_badge_roles(self.tone, self.color_roles);
288 let container_color = self
289 .container_color
290 .unwrap_or_else(|| tone(container_role, window, cx));
291 let content_color = self
292 .content_color
293 .unwrap_or_else(|| tone(content_role, window, cx));
294 let typography = TypeRole::LabelSmall.style(TypographyEmphasis::Baseline);
295 let overlap = px(if large { 12. } else { 6. });
296 let dx = if f32::from(self.offset.x).is_finite() {
297 self.offset.x
298 } else {
299 px(0.)
300 };
301 let dy = if f32::from(self.offset.y).is_finite() {
302 self.offset.y
303 } else {
304 px(0.)
305 };
306 let mark = div()
307 .min_w(side)
308 .rounded_full()
309 .when(large, |badge| badge.px(px(4.)))
310 .when(self.host.is_some(), |badge| {
311 badge
312 .absolute()
313 .top(if large { px(-2.) } else { px(0.) } + dy)
314 .when_else(
315 current_material_theme(window, cx).layout.direction == Direction::Rtl,
316 |badge| badge.right(gpui::relative(1.)).mr(-overlap + dx),
317 |badge| badge.left(gpui::relative(1.)).ml(-overlap + dx),
318 )
319 })
320 .bg(container_color)
321 .text_color(content_color)
322 .flex()
323 .items_center()
324 .justify_center();
325 let mark = match self.content {
326 BadgeContent::Dot => mark.h(side).w(side),
327 BadgeContent::Text(text) => mark.min_h(side).child(crate::text::single_line(
328 text,
329 typography,
330 1.,
331 content_color,
332 (None, 1., 1.),
333 window,
334 cx,
335 )),
336 BadgeContent::Custom(id, content) => {
337 text_style(mark.min_h(side), typography, 1., window, cx).child(
338 div()
339 .id(id)
340 .role(Role::Group)
341 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
342 .child(content),
343 )
344 }
345 };
346 let mark = if let Some((id, label)) = self.accessible_label {
347 mark.id(id)
348 .test_support()
349 .role(Role::Label)
350 .aria_label(label)
351 .into_any_element()
352 } else {
353 mark.into_any_element()
354 };
355 if let Some(host) = self.host {
356 div().relative().child(host).child(mark).into_any_element()
357 } else {
358 div().flex().items_center().child(mark).into_any_element()
359 }
360 }
361}
362
363fn tone(role: ColorRole, window: &Window, cx: &App) -> gpui::Hsla {
364 color(current_material_theme(window, cx).colors.color(role))
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
372 fn badge_roles_follow_tone_and_explicit_color_role_precedence() {
373 use ColorRole::*;
374 assert_eq!(
375 resolve_badge_roles(SemanticTone::Default, None),
376 (Error, OnError)
377 );
378 assert_eq!(
379 resolve_badge_roles(SemanticTone::Danger, None),
380 (Error, OnError)
381 );
382 assert_eq!(
383 resolve_badge_roles(SemanticTone::Success, None),
384 (Success, OnSuccess)
385 );
386 assert_eq!(
387 resolve_badge_roles(SemanticTone::Warning, None),
388 (Warning, OnWarning)
389 );
390 assert_eq!(
391 resolve_badge_roles(SemanticTone::Info, None),
392 (Info, OnInfo)
393 );
394 assert_eq!(
395 resolve_badge_roles(
396 SemanticTone::Danger,
397 Some((PrimaryContainer, OnPrimaryContainer))
398 ),
399 (PrimaryContainer, OnPrimaryContainer)
400 );
401 }
402
403 #[test]
404 fn standalone_badge_constructors_format_labels_and_capped_counts() {
405 assert_eq!(format_badge_count(0, 99), SharedString::from("0"));
406 assert_eq!(format_badge_count(99, 99), SharedString::from("99"));
407 assert_eq!(format_badge_count(120, 99), SharedString::from("99+"));
408
409 let label = Badge::standalone_label("NEW");
410 assert!(label.host.is_none());
411 assert!(matches!(label.content, BadgeContent::Text(ref text) if text == "NEW"));
412
413 let count = Badge::standalone_count(150, 99);
414 assert!(count.host.is_none());
415 assert!(matches!(count.content, BadgeContent::Text(ref text) if text == "99+"));
416 }
417}