| 1 | //! Compact numeric count badges (`0`, `12`, `99+`). |
| 2 | |
| 3 | use std::fmt; |
| 4 | |
| 5 | use ratatui::{ |
| 6 | buffer::Buffer, |
| 7 | layout::Rect, |
| 8 | text::{Line, Span}, |
| 9 | widgets::Widget, |
| 10 | }; |
| 11 | |
| 12 | use crate::{Paint, Role, Theme, text}; |
| 13 | |
| 14 | /// Compact numeric count badge matching Desktop `packages/ui` `<Count>`. |
| 15 | /// |
| 16 | /// Formats values directly (`"0"`, `"12"`) or capped with a trailing `+` |
| 17 | /// (`Count::new(120).max(99)` → `"99+"`). |
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 19 | pub struct Count { |
| 20 | /// Numeric value to display. |
| 21 | pub value: usize, |
| 22 | /// Optional inclusive maximum; larger values format as `"{cap}+"`. |
| 23 | pub cap: Option<usize>, |
| 24 | /// Theme role used to paint the badge. |
| 25 | pub role: Role, |
| 26 | } |
| 27 | |
| 28 | impl Count { |
| 29 | /// Create a count badge for `value`. |
| 30 | #[must_use] |
| 31 | pub const fn new(value: usize) -> Self { |
| 32 | Self { |
| 33 | value, |
| 34 | cap: None, |
| 35 | role: Role::Muted, |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | /// Cap display at `cap`, rendering larger counts as `"{cap}+"`. |
| 40 | #[must_use] |
| 41 | pub const fn max(mut self, cap: usize) -> Self { |
| 42 | self.cap = Some(cap); |
| 43 | self |
| 44 | } |
| 45 | |
| 46 | /// Override the painted theme [`Role`] (defaults to [`Role::Muted`]). |
| 47 | #[must_use] |
| 48 | pub const fn role(mut self, role: Role) -> Self { |
| 49 | self.role = role; |
| 50 | self |
| 51 | } |
| 52 | |
| 53 | /// Formatted badge text. |
| 54 | #[must_use] |
| 55 | pub fn label(&self) -> String { |
| 56 | self.to_string() |
| 57 | } |
| 58 | |
| 59 | /// Display width in terminal cells. |
| 60 | #[must_use] |
| 61 | pub fn width(&self) -> usize { |
| 62 | text::width(&self.label()) |
| 63 | } |
| 64 | |
| 65 | /// Build a styled [`Span`] for inline composition. |
| 66 | #[must_use] |
| 67 | pub fn span(&self, theme: &Theme) -> Span<'static> { |
| 68 | Span::styled(self.label(), theme.fg(self.role)) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl fmt::Display for Count { |
| 73 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 74 | match self.cap { |
| 75 | Some(cap) if self.value > cap => write!(f, "{cap}+"), |
| 76 | _ => write!(f, "{}", self.value), |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl Paint for Count { |
| 82 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 83 | let area = area.intersection(buf.area); |
| 84 | if area.is_empty() { |
| 85 | return; |
| 86 | } |
| 87 | let label = self.label(); |
| 88 | let clipped = text::truncate(&label, usize::from(area.width), theme.ascii()); |
| 89 | Line::from(Span::styled(clipped.into_owned(), theme.fg(self.role))).render( |
| 90 | Rect { |
| 91 | x: area.x, |
| 92 | y: area.y, |
| 93 | width: area.width, |
| 94 | height: 1, |
| 95 | }, |
| 96 | buf, |
| 97 | ); |
| 98 | } |
| 99 | } |
| 100 |