Skip to main content

tui_chart/
bullet.rs

1//! Bullet chart: a value bar against a target marker over qualitative ranges.
2
3use crate::text::put_str;
4use crate::theme::{self, Theme};
5use crate::util::{darken, format_compact};
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// One bullet row.
14#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct BulletItem {
17    /// Row label.
18    pub label: String,
19    /// Measured value.
20    pub value: f64,
21    /// Target marker position.
22    pub target: Option<f64>,
23    /// Ascending upper bounds of the qualitative ranges (e.g. poor/ok/good).
24    pub ranges: Vec<f64>,
25}
26
27impl BulletItem {
28    /// Create an item with no target or ranges.
29    pub fn new(label: impl Into<String>, value: f64) -> Self {
30        Self {
31            label: label.into(),
32            value,
33            target: None,
34            ranges: vec![],
35        }
36    }
37
38    /// Target marker.
39    pub fn target(mut self, t: f64) -> Self {
40        self.target = Some(t);
41        self
42    }
43
44    /// Ascending range bounds.
45    pub fn ranges(mut self, r: impl IntoIterator<Item = f64>) -> Self {
46        self.ranges = r.into_iter().collect();
47        self
48    }
49}
50
51/// Bullet chart widget (one row per item, shared scale `0..max`).
52#[derive(Debug, Clone, Default)]
53pub struct Bullet {
54    items: Vec<BulletItem>,
55    max: Option<f64>,
56    color: Option<Color>,
57    theme: Option<Theme>,
58    base: Option<Style>,
59    block: Option<Block<'static>>,
60}
61
62fn fin(v: f64) -> f64 {
63    if v.is_finite() {
64        v
65    } else {
66        0.0
67    }
68}
69
70impl Bullet {
71    /// Create a bullet chart.
72    pub fn new(items: impl IntoIterator<Item = BulletItem>) -> Self {
73        Self {
74            items: items.into_iter().collect(),
75            ..Self::default()
76        }
77    }
78
79    /// Fixed scale maximum shared by all rows (default: each row is scaled to
80    /// its own largest value/target/range, so mixed units work).
81    pub fn max(mut self, m: f64) -> Self {
82        self.max = Some(m);
83        self
84    }
85
86    /// Value bar color.
87    pub fn color(mut self, c: Color) -> Self {
88        self.color = Some(c);
89        self
90    }
91
92    theme_setter!(
93        /// Apply a [`Theme`]; explicit colors win.
94        theme
95    );
96
97    base_style_setter!(base);
98
99    block_setter!(block, 'static);
100
101    fn scale_max(&self, it: &BulletItem) -> f64 {
102        let m = self.max.map(fin).unwrap_or_else(|| {
103            it.ranges
104                .iter()
105                .copied()
106                .chain([it.value])
107                .chain(it.target)
108                .map(fin)
109                .fold(0.0, f64::max)
110        });
111        if m > 0.0 {
112            m
113        } else {
114            1.0
115        }
116    }
117
118    fn render_into(&self, area: Rect, buf: &mut Buffer) {
119        let area = area.intersection(buf.area);
120        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
121        if inner.width < 8 || inner.height == 0 || self.items.is_empty() {
122            return;
123        }
124        let lw = (self
125            .items
126            .iter()
127            .map(|i| i.label.chars().count())
128            .max()
129            .unwrap_or(0) as u16)
130            .min(inner.width / 3);
131        let vw = (self
132            .items
133            .iter()
134            .map(|i| format_compact(fin(i.value)).chars().count())
135            .max()
136            .unwrap_or(0) as u16
137            + 1)
138        .min(inner.width / 4);
139        let bx = inner.x + lw + 1;
140        let bw = inner.width.saturating_sub(lw + 1 + vw);
141        if bw < 2 {
142            return;
143        }
144        let th = self.theme.as_ref();
145        let text = th.map_or(Style::default(), |t| t.label_style());
146        let bar = self
147            .color
148            .unwrap_or_else(|| th.map_or(Color::Cyan, |t| t.accent));
149        let marker = th.map_or(Color::White, |t| t.foreground);
150        let bands: [Color; 3] = th.map_or(
151            [
152                Color::Rgb(70, 70, 70),
153                Color::Rgb(52, 52, 52),
154                Color::Rgb(36, 36, 36),
155            ],
156            |t| {
157                let f = t.foreground;
158                [darken(f, 0.68), darken(f, 0.8), darken(f, 0.9)]
159            },
160        );
161        let col = |v: f64, max: f64| -> u16 {
162            ((fin(v) / max).clamp(0.0, 1.0) * (bw - 1) as f64).round() as u16
163        };
164        // Row height 3 → 2 → 1 (with a blank spacer row when it fits).
165        let n = self.items.len();
166        let avail = inner.height as usize;
167        let (rh, gap) = [(3usize, 1usize), (2, 1), (1, 1), (1, 0)]
168            .into_iter()
169            .find(|(h, g)| n * h + n.saturating_sub(1) * g <= avail)
170            .unwrap_or((1, 0));
171        let total = n * rh + n.saturating_sub(1) * gap;
172        let top = inner.y as usize + avail.saturating_sub(total) / 2;
173        let good = Color::Rgb(80, 200, 120);
174        let warn = Color::Rgb(240, 180, 60);
175        for (i, it) in self.items.iter().enumerate() {
176            let y0 = top + i * (rh + gap);
177            if y0 >= inner.bottom() as usize {
178                break;
179            }
180            let rh = rh.min(inner.bottom() as usize - y0) as u16;
181            let y0 = y0 as u16;
182            let ymid = y0 + rh / 2;
183            put_str(buf, inner.x, ymid, bx, &it.label, text);
184            let max = self.scale_max(it);
185            // qualitative ranges: lightest = worst; no ranges → one neutral band
186            let nb = it.ranges.len();
187            let mut shade_at = vec![bands[2]; bw as usize];
188            let mut from = 0u16;
189            for (k, r) in it.ranges.iter().enumerate() {
190                let to = col(*r, max) + 1;
191                let shade = bands[(k * 3 / nb.max(1)).min(2)];
192                for x in from..to.min(bw) {
193                    shade_at[x as usize] = shade;
194                }
195                from = from.max(to);
196            }
197            for r in 0..rh {
198                for x in 0..bw {
199                    buf[(bx + x, y0 + r)]
200                        .set_char(' ')
201                        .set_bg(shade_at[x as usize]);
202                }
203            }
204            // value bar: eighth-block precision on the middle row (lower half if 1 row)
205            let frac = (fin(it.value) / max).clamp(0.0, 1.0);
206            let bar_y = y0 + if rh == 1 { 0 } else { rh / 2 };
207            if rh == 1 {
208                let end = col(it.value, max) + u16::from(fin(it.value) > 0.0);
209                for x in 0..end.min(bw) {
210                    buf[(bx + x, bar_y)].set_char('▄').set_fg(bar);
211                }
212            } else {
213                let eighths = (frac * bw as f64 * 8.0).round() as u32;
214                for x in 0..bw {
215                    let rem = eighths.saturating_sub(x as u32 * 8);
216                    let cell = &mut buf[(bx + x, bar_y)];
217                    if rem >= 8 {
218                        cell.set_char('█').set_fg(bar);
219                    } else if rem > 0 {
220                        cell.set_char(['▏', '▎', '▍', '▌', '▋', '▊', '▉'][rem as usize - 1])
221                            .set_fg(bar);
222                    }
223                }
224            }
225            if let Some(t) = it.target {
226                let x = col(t, max).min(bw - 1);
227                for r in 0..rh {
228                    buf[(bx + x, y0 + r)]
229                        .set_char(if rh == 1 { '│' } else { '┃' })
230                        .set_fg(marker);
231                }
232            }
233            let mut vstyle = text;
234            let mut note = String::new();
235            if let Some(t) = it.target.filter(|t| fin(*t) > 0.0) {
236                let pct = fin(it.value) / fin(t) * 100.0;
237                vstyle = vstyle.fg(if pct >= 100.0 { good } else { warn });
238                note = format!(" {pct:.0}%");
239            }
240            let vx = bx + bw + 1;
241            put_str(
242                buf,
243                vx,
244                ymid,
245                inner.right(),
246                &format_compact(fin(it.value)),
247                vstyle,
248            );
249            if !note.is_empty() && rh >= 2 && ymid + 1 < y0 + rh {
250                put_str(
251                    buf,
252                    vx,
253                    ymid + 1,
254                    inner.right(),
255                    note.trim_start(),
256                    Style::default().fg(darken(marker, 0.35)),
257                );
258            }
259        }
260    }
261}
262
263widget_impls!(Bullet);
264
265#[cfg(feature = "theme")]
266impl tui_nuances::Themed for Bullet {
267    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
268        self.theme(theme)
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use ratatui::widgets::Widget;
276
277    fn render(b: &Bullet, w: u16, h: u16) -> Buffer {
278        let a = Rect::new(0, 0, w, h);
279        let mut buf = Buffer::empty(a);
280        b.render(a, &mut buf);
281        buf
282    }
283
284    #[test]
285    fn draws_value_target_and_ranges() {
286        let b = Bullet::new([BulletItem::new("Rev", 70.0)
287            .target(85.0)
288            .ranges([50.0, 80.0, 100.0])]);
289        let buf = render(&b, 40, 2);
290        let all: String = buf.content().iter().map(|c| c.symbol()).collect();
291        assert!(all.contains('█') && all.contains('┃') && all.contains("Rev"));
292        let one = render(&b, 40, 1);
293        let all: String = one.content().iter().map(|c| c.symbol()).collect();
294        assert!(all.contains('▄') && all.contains('│'));
295        assert!(buf.content().iter().any(|c| c.bg != Color::Reset));
296    }
297
298    #[test]
299    fn degenerate_inputs_do_not_panic() {
300        let b = Bullet::new([BulletItem::new("x", f64::NAN).target(f64::INFINITY)]);
301        render(&b, 40, 1);
302        render(&b, 3, 1);
303        render(&b, 0, 0);
304        render(&Bullet::new([]), 20, 3);
305        render(
306            &Bullet::new([BulletItem::new("a", -5.0).ranges([f64::NAN])]).max(0.0),
307            20,
308            3,
309        );
310    }
311
312    #[test]
313    fn custom_color_and_max() {
314        let b = Bullet::new([BulletItem::new("a", 50.0)])
315            .max(200.0)
316            .color(Color::Magenta);
317        let buf = render(&b, 40, 2);
318        assert!(buf.content().iter().any(|c| c.fg == Color::Magenta));
319        // a larger axis max shrinks the bar
320        let full = |m: f64| {
321            render(&Bullet::new([BulletItem::new("a", 50.0)]).max(m), 40, 2)
322                .content()
323                .iter()
324                .filter(|c| c.symbol() == "█")
325                .count()
326        };
327        assert!(full(100.0) > full(400.0));
328    }
329
330    #[test]
331    fn many_items_and_row_heights() {
332        let items = (0..6).map(|i| BulletItem::new(format!("m{i}"), i as f64 * 10.0));
333        let b = Bullet::new(items);
334        for h in [1, 2, 3, 6, 18, 40] {
335            render(&b, 50, h);
336        }
337    }
338}