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 {
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 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 pub fn color(mut self, role: ColorRole) -> Self {
57 self.color_role = role;
58 self.color_override = None;
59 self
60 }
61
62 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#[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 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 pub fn standalone_label(text: impl Into<SharedString>) -> Self {
165 Self {
166 content: BadgeContent::Text(text.into()),
167 ..Self::standalone()
168 }
169 }
170
171 pub fn standalone_count(count: usize, maximum: usize) -> Self {
173 Self::standalone_label(format_badge_count(count, maximum))
174 }
175
176 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 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 pub fn tone(mut self, tone: SemanticTone) -> Self {
210 self.tone = tone;
211 self
212 }
213
214 pub fn color_role(mut self, container: ColorRole, content: ColorRole) -> Self {
219 self.color_roles = Some((container, content));
220 self
221 }
222
223 pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
225 self.container_color = Some(color.into());
226 self
227 }
228
229 pub fn content_color(mut self, color: impl Into<Hsla>) -> Self {
231 self.content_color = Some(color.into());
232 self
233 }
234
235 pub fn visible(mut self, visible: bool) -> Self {
238 self.visible = visible;
239 self
240 }
241
242 pub fn offset(mut self, offset: Point<Pixels>) -> Self {
245 self.offset = offset;
246 self
247 }
248
249 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}