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            // qualitative ranges: lightest = worst; no ranges → one neutral band
198            let nb = it.ranges.len();
199            let mut shade_at = vec![bands[2]; bw as usize];
200            let mut from = 0u16;
201            for (k, r) in it.ranges.iter().enumerate() {
202                let to = col(*r, max) + 1;
203                let shade = bands[(k * 3 / nb.max(1)).min(2)];
204                for x in from..to.min(bw) {
205                    shade_at[x as usize] = shade;
206                }
207                from = from.max(to);
208            }
209            for r in 0..rh {
210                for x in 0..bw {
211                    buf[(bx + x, y0 + r)]
212                        .set_char(' ')
213                        .set_bg(shade_at[x as usize]);
214                }
215            }
216            // value bar: eighth-block precision on the middle row (lower half if 1 row)
217            let frac = (fin(it.value) / max).clamp(0.0, 1.0);
218            let bar_y = y0 + if rh == 1 { 0 } else { rh / 2 };
219            if rh == 1 {
220                let end = col(it.value, max) + u16::from(fin(it.value) > 0.0);
221                for x in 0..end.min(bw) {
222                    buf[(bx + x, bar_y)].set_char('▄').set_fg(bar);
223                }
224            } else {
225                let eighths = (frac * bw as f64 * 8.0).round() as u32;
226                for x in 0..bw {
227                    let rem = eighths.saturating_sub(x as u32 * 8);
228                    let cell = &mut buf[(bx + x, bar_y)];
229                    if rem >= 8 {
230                        cell.set_char('█').set_fg(bar);
231                    } else if rem > 0 {
232                        cell.set_char(['▏', '▎', '▍', '▌', '▋', '▊', '▉'][rem as usize - 1])
233                            .set_fg(bar);
234                    }
235                }
236            }
237            if let Some(t) = it.target {
238                let x = col(t, max).min(bw - 1);
239                for r in 0..rh {
240                    buf[(bx + x, y0 + r)]
241                        .set_char(if rh == 1 { '│' } else { '┃' })
242                        .set_fg(marker);
243                }
244            }
245            let mut vstyle = text;
246            let mut note = String::new();
247            if let Some(t) = it.target.filter(|t| fin(*t) > 0.0) {
248                let pct = fin(it.value) / fin(t) * 100.0;
249                vstyle = vstyle.fg(if pct >= 100.0 { good } else { warn });
250                note = format!(" {pct:.0}%");
251            }
252            let vx = bx + bw + 1;
253            put_str(
254                buf,
255                vx,
256                ymid,
257                inner.right(),
258                &format_compact(fin(it.value)),
259                vstyle,
260            );
261            if !note.is_empty() && rh >= 2 && ymid + 1 < y0 + rh {
262                put_str(
263                    buf,
264                    vx,
265                    ymid + 1,
266                    inner.right(),
267                    note.trim_start(),
268                    Style::default().fg(darken(marker, 0.35)),
269                );
270            }
271        }
272    }
273}
274
275widget_impls!(Bullet);
276
277#[cfg(feature = "theme")]
278impl tui_nuances::Themed for Bullet {
279    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
280        self.theme(theme)
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use ratatui::widgets::Widget;
288
289    fn render(b: &Bullet, w: u16, h: u16) -> Buffer {
290        let a = Rect::new(0, 0, w, h);
291        let mut buf = Buffer::empty(a);
292        b.render(a, &mut buf);
293        buf
294    }
295
296    #[test]
297    fn draws_value_target_and_ranges() {
298        let b = Bullet::new([BulletItem::new("Rev", 70.0)
299            .target(85.0)
300            .ranges([50.0, 80.0, 100.0])]);
301        let buf = render(&b, 40, 2);
302        let all: String = buf.content().iter().map(|c| c.symbol()).collect();
303        assert!(all.contains('█') && all.contains('┃') && all.contains("Rev"));
304        let one = render(&b, 40, 1);
305        let all: String = one.content().iter().map(|c| c.symbol()).collect();
306        assert!(all.contains('▄') && all.contains('│'));
307        assert!(buf.content().iter().any(|c| c.bg != Color::Reset));
308    }
309
310    #[test]
311    fn degenerate_inputs_do_not_panic() {
312        let b = Bullet::new([BulletItem::new("x", f64::NAN).target(f64::INFINITY)]);
313        render(&b, 40, 1);
314        render(&b, 3, 1);
315        render(&b, 0, 0);
316        render(&Bullet::new([]), 20, 3);
317        render(
318            &Bullet::new([BulletItem::new("a", -5.0).ranges([f64::NAN])]).max(0.0),
319            20,
320            3,
321        );
322    }
323
324    #[test]
325    fn custom_color_and_max() {
326        let b = Bullet::new([BulletItem::new("a", 50.0)])
327            .max(200.0)
328            .color(Color::Magenta);
329        let buf = render(&b, 40, 2);
330        assert!(buf.content().iter().any(|c| c.fg == Color::Magenta));
331        // a larger axis max shrinks the bar
332        let full = |m: f64| {
333            render(&Bullet::new([BulletItem::new("a", 50.0)]).max(m), 40, 2)
334                .content()
335                .iter()
336                .filter(|c| c.symbol() == "█")
337                .count()
338        };
339        assert!(full(100.0) > full(400.0));
340    }
341
342    #[test]
343    fn many_items_and_row_heights() {
344        let items = (0..6).map(|i| BulletItem::new(format!("m{i}"), i as f64 * 10.0));
345        let b = Bullet::new(items);
346        for h in [1, 2, 3, 6, 18, 40] {
347            render(&b, 50, h);
348        }
349    }
350}