Skip to main content

tui_chart/
comparison.rs

1//! Comparison chart: two bars per measure, "before" against "after", each measure on its own scale.
2
3use crate::text::put_str;
4use crate::theme::{self, Theme};
5use crate::util::darken;
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// One measure: a value before and a value after.
14#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct ComparisonItem {
17    /// Measure label.
18    pub label: String,
19    /// The first value (the reference).
20    pub before: f64,
21    /// The second value.
22    pub after: f64,
23    /// Printed after both values, e.g. `"%"`.
24    pub unit: String,
25}
26
27impl ComparisonItem {
28    /// Create a measure without a unit.
29    pub fn new(label: impl Into<String>, before: f64, after: f64) -> Self {
30        Self {
31            label: label.into(),
32            before,
33            after,
34            unit: String::new(),
35        }
36    }
37
38    /// The unit printed after both values.
39    pub fn unit(mut self, unit: impl Into<String>) -> Self {
40        self.unit = unit.into();
41        self
42    }
43}
44
45/// How the two bars of a measure sit.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48pub enum ComparisonLayout {
49    /// The label, then both bars on one line (2 rows per measure).
50    #[default]
51    Inline,
52    /// The label, then one bar above the other (3 rows per measure).
53    Stacked,
54}
55
56/// Comparison chart widget: for every measure two bars on one scale `0..max(before, after)`,
57/// so the scales may differ between measures (mixed units work). An optional legend names the
58/// two series.
59///
60/// # Example
61///
62/// ```
63/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
64/// use tui_chart::{Comparison, ComparisonItem};
65///
66/// let chart = Comparison::new([
67///     ComparisonItem::new("mean ΔE", 3.2, 1.8),
68///     ComparisonItem::new("over ΔE 7", 12.0, 4.5).unit("%"),
69/// ])
70/// .legend("46 shipped", "286 in use");
71/// let area = Rect::new(0, 0, 50, 8);
72/// let mut buf = Buffer::empty(area);
73/// chart.render(area, &mut buf);
74/// ```
75#[derive(Debug, Clone, Default)]
76pub struct Comparison {
77    items: Vec<ComparisonItem>,
78    layout: ComparisonLayout,
79    legend: Option<(String, String)>,
80    decimals: usize,
81    max_bar: Option<u16>,
82    before_color: Option<Color>,
83    after_color: Option<Color>,
84    theme: Option<Theme>,
85    base: Option<Style>,
86    block: Option<Block<'static>>,
87}
88
89fn fin(v: f64) -> f64 {
90    if v.is_finite() {
91        v.max(0.0)
92    } else {
93        0.0
94    }
95}
96
97impl Comparison {
98    /// Create a comparison chart (one decimal in the values).
99    pub fn new(items: impl IntoIterator<Item = ComparisonItem>) -> Self {
100        Self {
101            items: items.into_iter().collect(),
102            decimals: 1,
103            ..Self::default()
104        }
105    }
106
107    /// Where the bars of a measure sit (default: [`ComparisonLayout::Inline`]).
108    pub fn layout(mut self, l: ComparisonLayout) -> Self {
109        self.layout = l;
110        self
111    }
112
113    /// A legend line under the measures, naming the series (drawn when a row is left over).
114    pub fn legend(mut self, before: impl Into<String>, after: impl Into<String>) -> Self {
115        self.legend = Some((before.into(), after.into()));
116        self
117    }
118
119    /// Decimals of the printed values (default 1).
120    pub fn decimals(mut self, d: usize) -> Self {
121        self.decimals = d;
122        self
123    }
124
125    /// The longest a bar may be, in cells (default: as wide as the area allows).
126    pub fn max_bar_width(mut self, w: u16) -> Self {
127        self.max_bar = Some(w);
128        self
129    }
130
131    /// Color of the "before" bars.
132    pub fn before_color(mut self, c: Color) -> Self {
133        self.before_color = Some(c);
134        self
135    }
136
137    /// Color of the "after" bars.
138    pub fn after_color(mut self, c: Color) -> Self {
139        self.after_color = Some(c);
140        self
141    }
142
143    theme_setter!(
144        /// Apply a [`Theme`]; explicit colors win.
145        theme
146    );
147
148    base_style_setter!(base);
149
150    block_setter!(block, 'static);
151
152    /// The height one measure takes.
153    fn row_height(&self) -> u16 {
154        match self.layout {
155            ComparisonLayout::Inline => 2,
156            ComparisonLayout::Stacked => 3,
157        }
158    }
159
160    fn value(&self, it: &ComparisonItem, v: f64) -> String {
161        format!("{:.*}{}", self.decimals, fin(v), it.unit)
162    }
163
164    fn render_into(&self, area: Rect, buf: &mut Buffer) {
165        let area = area.intersection(buf.area);
166        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
167        if inner.width < 8 || inner.height == 0 || self.items.is_empty() {
168            return;
169        }
170        let th = self.theme.as_ref();
171        let text = th.map_or(Style::default(), |t| t.label_style());
172        let accent = th.map_or(Color::Cyan, |t| t.accent);
173        let muted = th.map_or(Color::DarkGray, |t| darken(t.foreground, 0.45));
174        let before = self.before_color.unwrap_or(muted);
175        let after = self.after_color.unwrap_or(accent);
176        let rh = self.row_height();
177        let wide = self
178            .items
179            .iter()
180            .map(|i| self.value(i, i.before).chars().count());
181        let vb = wide.max().unwrap_or(0) as u16 + 1;
182        let wide = self
183            .items
184            .iter()
185            .map(|i| self.value(i, i.after).chars().count());
186        let va = wide.max().unwrap_or(0) as u16 + 1;
187        let mut y = inner.y;
188        let rows_fit = (inner.height / rh) as usize;
189        for it in self.items.iter().take(rows_fit.max(1)) {
190            if y + rh > inner.bottom() {
191                break;
192            }
193            put_str(buf, inner.x, y, inner.right(), &it.label, text);
194            let top = fin(it.before).max(fin(it.after)).max(f64::EPSILON);
195            let cells = |v: f64, w: u16| -> u16 {
196                if fin(v) <= 0.0 {
197                    0
198                } else {
199                    ((fin(v) / top * f64::from(w)).round() as u16).clamp(1, w)
200                }
201            };
202            let (vbs, vas) = (self.value(it, it.before), self.value(it, it.after));
203            match self.layout {
204                ComparisonLayout::Inline => {
205                    let gap = 2u16;
206                    let free = inner.width.saturating_sub(vb + va + gap);
207                    let mut w = free / 2;
208                    if let Some(m) = self.max_bar {
209                        w = w.min(m);
210                    }
211                    if w == 0 {
212                        y += rh;
213                        continue;
214                    }
215                    let by = y + 1;
216                    let x1 = inner.x;
217                    bar(buf, x1, by, cells(it.before, w), before);
218                    put_str(
219                        buf,
220                        x1 + w,
221                        by,
222                        inner.right(),
223                        &format!(" {vbs}"),
224                        Style::default().fg(before),
225                    );
226                    let x2 = x1 + w + vb + gap;
227                    bar(buf, x2, by, cells(it.after, w), after);
228                    put_str(
229                        buf,
230                        x2 + w,
231                        by,
232                        inner.right(),
233                        &format!(" {vas}"),
234                        Style::default().fg(after),
235                    );
236                }
237                ComparisonLayout::Stacked => {
238                    let v = vb.max(va);
239                    let mut w = inner.width.saturating_sub(v);
240                    if let Some(m) = self.max_bar {
241                        w = w.min(m);
242                    }
243                    if w == 0 {
244                        y += rh;
245                        continue;
246                    }
247                    bar(buf, inner.x, y + 1, cells(it.before, w), before);
248                    put_str(
249                        buf,
250                        inner.x + w,
251                        y + 1,
252                        inner.right(),
253                        &format!(" {vbs}"),
254                        Style::default().fg(before),
255                    );
256                    bar(buf, inner.x, y + 2, cells(it.after, w), after);
257                    put_str(
258                        buf,
259                        inner.x + w,
260                        y + 2,
261                        inner.right(),
262                        &format!(" {vas}"),
263                        Style::default().fg(after),
264                    );
265                }
266            }
267            y += rh;
268        }
269        if let Some((b, a)) = &self.legend {
270            if y < inner.bottom() {
271                let mut x = inner.x;
272                for (name, color) in [(b, before), (a, after)] {
273                    put_str(buf, x, y, inner.right(), "■ ", Style::default().fg(color));
274                    put_str(buf, x + 2, y, inner.right(), name, text);
275                    x += 2 + name.chars().count() as u16 + 3;
276                }
277            }
278        }
279    }
280}
281
282/// `cells` full blocks from `x`.
283fn bar(buf: &mut Buffer, x: u16, y: u16, cells: u16, color: Color) {
284    for dx in 0..cells {
285        if let Some(c) = buf.cell_mut((x + dx, y)) {
286            c.set_char('█').set_fg(color);
287        }
288    }
289}
290
291widget_impls!(Comparison);
292
293#[cfg(feature = "theme")]
294impl tui_nuances::Themed for Comparison {
295    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
296        self.theme(theme)
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use ratatui::widgets::Widget;
304
305    fn render(c: &Comparison, w: u16, h: u16) -> Buffer {
306        let a = Rect::new(0, 0, w, h);
307        let mut buf = Buffer::empty(a);
308        c.render(a, &mut buf);
309        buf
310    }
311
312    fn text(buf: &Buffer) -> String {
313        buf.content().iter().map(|c| c.symbol()).collect()
314    }
315
316    fn blocks(buf: &Buffer, color: Color) -> usize {
317        buf.content()
318            .iter()
319            .filter(|c| c.symbol() == "█" && c.fg == color)
320            .count()
321    }
322
323    #[test]
324    fn the_larger_value_gets_the_longer_bar() {
325        let c = Comparison::new([ComparisonItem::new("mean", 4.0, 1.0)])
326            .before_color(Color::Red)
327            .after_color(Color::Green);
328        let buf = render(&c, 50, 2);
329        assert!(blocks(&buf, Color::Red) > blocks(&buf, Color::Green));
330        assert!(text(&buf).contains("mean"));
331        assert!(text(&buf).contains("4.0") && text(&buf).contains("1.0"));
332    }
333
334    #[test]
335    fn a_value_above_zero_always_shows_a_bar() {
336        let c =
337            Comparison::new([ComparisonItem::new("m", 1000.0, 0.001)]).after_color(Color::Green);
338        assert_eq!(blocks(&render(&c, 50, 2), Color::Green), 1);
339        let zero = Comparison::new([ComparisonItem::new("m", 5.0, 0.0)]).after_color(Color::Green);
340        assert_eq!(blocks(&render(&zero, 50, 2), Color::Green), 0);
341    }
342
343    #[test]
344    fn each_measure_has_its_own_scale_and_unit() {
345        let c = Comparison::new([
346            ComparisonItem::new("a", 2.0, 1.0),
347            ComparisonItem::new("b", 90.0, 45.0).unit("%"),
348        ])
349        .before_color(Color::Red);
350        let buf = render(&c, 50, 4);
351        assert!(text(&buf).contains("90.0%"));
352        // both rows have the full bar for their larger value
353        let per_row = |y: u16| {
354            (0..50)
355                .filter(|x| buf[(*x, y)].fg == Color::Red && buf[(*x, y)].symbol() == "█")
356                .count()
357        };
358        assert_eq!(per_row(1), per_row(3));
359    }
360
361    #[test]
362    fn stacked_puts_the_bars_on_two_rows() {
363        let c = Comparison::new([ComparisonItem::new("m", 4.0, 2.0)])
364            .layout(ComparisonLayout::Stacked)
365            .before_color(Color::Red)
366            .after_color(Color::Green);
367        let buf = render(&c, 40, 3);
368        let row = |y: u16, color: Color| {
369            (0..40)
370                .filter(|x| buf[(*x, y)].fg == color && buf[(*x, y)].symbol() == "█")
371                .count()
372        };
373        assert!(row(1, Color::Red) > 0 && row(1, Color::Green) == 0);
374        assert!(row(2, Color::Green) > 0 && row(2, Color::Red) == 0);
375    }
376
377    #[test]
378    fn the_legend_needs_a_spare_row() {
379        let c = Comparison::new([ComparisonItem::new("m", 4.0, 2.0)]).legend("old", "new");
380        assert!(text(&render(&c, 40, 3)).contains("new"));
381        assert!(!text(&render(&c, 40, 2)).contains("new"));
382    }
383
384    #[test]
385    fn decimals_and_a_cap_on_the_bar() {
386        let c = Comparison::new([ComparisonItem::new("m", 4.0, 2.0)])
387            .decimals(2)
388            .max_bar_width(5)
389            .before_color(Color::Red);
390        let buf = render(&c, 80, 2);
391        assert!(text(&buf).contains("4.00"));
392        assert_eq!(blocks(&buf, Color::Red), 5);
393    }
394
395    #[test]
396    fn degenerate_inputs_do_not_panic() {
397        let c = Comparison::new([ComparisonItem::new("x", f64::NAN, f64::INFINITY)]);
398        for l in [ComparisonLayout::Inline, ComparisonLayout::Stacked] {
399            let c = c.clone().layout(l).legend("a", "b");
400            for (w, h) in [(0, 0), (3, 1), (8, 1), (20, 2), (40, 12)] {
401                render(&c, w, h);
402            }
403        }
404        render(&Comparison::new([]), 20, 3);
405        render(
406            &Comparison::new([ComparisonItem::new("n", -3.0, -1.0)]),
407            20,
408            3,
409        );
410    }
411
412    #[test]
413    fn many_measures_are_cut_to_fit() {
414        let items = (0..8).map(|i| ComparisonItem::new(format!("m{i}"), 3.0, 1.0));
415        let c = Comparison::new(items);
416        for h in [1, 2, 3, 7, 40] {
417            render(&c, 50, h);
418        }
419    }
420}