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