1use 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#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct PairedBarsItem {
17 pub label: String,
19 pub before: f64,
21 pub after: f64,
23 pub unit: String,
25}
26
27impl PairedBarsItem {
28 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 pub fn unit(mut self, unit: impl Into<String>) -> Self {
40 self.unit = unit.into();
41 self
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48pub enum PairedBarsLayout {
49 #[default]
51 Inline,
52 Stacked,
54}
55
56#[derive(Debug, Clone, Default)]
76pub struct PairedBars {
77 items: Vec<PairedBarsItem>,
78 layout: PairedBarsLayout,
79 legend: Option<(String, String)>,
80 decimals: usize,
81 max_bar: Option<u16>,
82 before_color: Option<Color>,
83 after_color: Option<Color>,
84 label_color: Option<Color>,
85 theme: Option<Theme>,
86 base: Option<Style>,
87 block: Option<Block<'static>>,
88}
89
90fn fin(v: f64) -> f64 {
91 if v.is_finite() {
92 v.max(0.0)
93 } else {
94 0.0
95 }
96}
97
98impl PairedBars {
99 pub fn new(items: impl IntoIterator<Item = PairedBarsItem>) -> Self {
101 Self {
102 items: items.into_iter().collect(),
103 decimals: 1,
104 ..Self::default()
105 }
106 }
107
108 pub fn layout(mut self, l: PairedBarsLayout) -> Self {
110 self.layout = l;
111 self
112 }
113
114 pub fn legend(mut self, before: impl Into<String>, after: impl Into<String>) -> Self {
116 self.legend = Some((before.into(), after.into()));
117 self
118 }
119
120 pub fn decimals(mut self, d: usize) -> Self {
122 self.decimals = d;
123 self
124 }
125
126 pub fn max_bar_width(mut self, w: u16) -> Self {
128 self.max_bar = Some(w);
129 self
130 }
131
132 pub fn before_color(mut self, c: Color) -> Self {
134 self.before_color = Some(c);
135 self
136 }
137
138 pub fn label_color(mut self, c: Color) -> Self {
140 self.label_color = Some(c);
141 self
142 }
143
144 pub fn after_color(mut self, c: Color) -> Self {
146 self.after_color = Some(c);
147 self
148 }
149
150 theme_setter!(
151 theme
153 );
154
155 base_style_setter!(base);
156
157 block_setter!(block, 'static);
158
159 fn row_height(&self) -> u16 {
161 match self.layout {
162 PairedBarsLayout::Inline => 2,
163 PairedBarsLayout::Stacked => 3,
164 }
165 }
166
167 fn value(&self, it: &PairedBarsItem, v: f64) -> String {
168 format!("{:.*}{}", self.decimals, fin(v), it.unit)
169 }
170
171 fn record_pair(&self, it: &PairedBarsItem, ii: usize, at: [(u16, u16); 2], w: u16) {
173 for (k, (x, y)) in at.into_iter().enumerate() {
174 let v = if k == 0 { it.before } else { it.after };
175 crate::interact::record_point(Rect::new(x, y, w, 1), k, ii, || {
176 let side = if k == 0 { "before" } else { "after" };
177 (
178 it.label.clone(),
179 vec![format!("{side}: {}", self.value(it, v))],
180 )
181 });
182 }
183 }
184
185 fn render_into(&self, area: Rect, buf: &mut Buffer) {
186 let area = area.intersection(buf.area);
187 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
188 if inner.width < 8 || inner.height == 0 || self.items.is_empty() {
189 return;
190 }
191 let th = self.theme.as_ref();
192 let text = th.map_or(Style::default(), |t| t.label_style());
193 let text = self.label_color.map_or(text, |c| text.fg(c));
194 let accent = th.map_or(Color::Cyan, |t| t.accent);
195 let muted = th.map_or(Color::DarkGray, |t| darken(t.foreground, 0.45));
196 let before = self.before_color.unwrap_or(muted);
197 let after = self.after_color.unwrap_or(accent);
198 let rh = self.row_height();
199 let wide = self
200 .items
201 .iter()
202 .map(|i| self.value(i, i.before).chars().count());
203 let vb = wide.max().unwrap_or(0) as u16 + 1;
204 let wide = self
205 .items
206 .iter()
207 .map(|i| self.value(i, i.after).chars().count());
208 let va = wide.max().unwrap_or(0) as u16 + 1;
209 let mut y = inner.y;
210 let rows_fit = (inner.height / rh) as usize;
211 for (ii, it) in self.items.iter().take(rows_fit.max(1)).enumerate() {
212 if y + rh > inner.bottom() {
213 break;
214 }
215 put_str(buf, inner.x, y, inner.right(), &it.label, text);
216 let top = fin(it.before).max(fin(it.after)).max(f64::EPSILON);
217 let cells = |v: f64, w: u16| -> u16 {
218 if fin(v) <= 0.0 {
219 0
220 } else {
221 ((fin(v) / top * f64::from(w)).round() as u16).clamp(1, w)
222 }
223 };
224 let (vbs, vas) = (self.value(it, it.before), self.value(it, it.after));
225 match self.layout {
226 PairedBarsLayout::Inline => {
227 let gap = 2u16;
228 let free = inner.width.saturating_sub(vb + va + gap);
229 let mut w = free / 2;
230 if let Some(m) = self.max_bar {
231 w = w.min(m);
232 }
233 if w == 0 {
234 y += rh;
235 continue;
236 }
237 let by = y + 1;
238 let x1 = inner.x;
239 self.record_pair(it, ii, [(x1, by), (x1 + w + vb + gap, by)], w);
240 bar(buf, x1, by, cells(it.before, w), before);
241 put_str(
242 buf,
243 x1 + w,
244 by,
245 inner.right(),
246 &format!(" {vbs}"),
247 Style::default().fg(before),
248 );
249 let x2 = x1 + w + vb + gap;
250 bar(buf, x2, by, cells(it.after, w), after);
251 put_str(
252 buf,
253 x2 + w,
254 by,
255 inner.right(),
256 &format!(" {vas}"),
257 Style::default().fg(after),
258 );
259 }
260 PairedBarsLayout::Stacked => {
261 let v = vb.max(va);
262 let mut w = inner.width.saturating_sub(v);
263 if let Some(m) = self.max_bar {
264 w = w.min(m);
265 }
266 if w == 0 {
267 y += rh;
268 continue;
269 }
270 self.record_pair(it, ii, [(inner.x, y + 1), (inner.x, y + 2)], w);
271 bar(buf, inner.x, y + 1, cells(it.before, w), before);
272 put_str(
273 buf,
274 inner.x + w,
275 y + 1,
276 inner.right(),
277 &format!(" {vbs}"),
278 Style::default().fg(before),
279 );
280 bar(buf, inner.x, y + 2, cells(it.after, w), after);
281 put_str(
282 buf,
283 inner.x + w,
284 y + 2,
285 inner.right(),
286 &format!(" {vas}"),
287 Style::default().fg(after),
288 );
289 }
290 }
291 y += rh;
292 }
293 if let Some((b, a)) = &self.legend {
294 if y < inner.bottom() {
295 let mut x = inner.x;
296 for (name, color) in [(b, before), (a, after)] {
297 put_str(buf, x, y, inner.right(), "■ ", Style::default().fg(color));
298 put_str(buf, x + 2, y, inner.right(), name, text);
299 x += 2 + name.chars().count() as u16 + 3;
300 }
301 }
302 }
303 }
304}
305
306fn bar(buf: &mut Buffer, x: u16, y: u16, cells: u16, color: Color) {
308 for dx in 0..cells {
309 if let Some(c) = buf.cell_mut((x + dx, y)) {
310 c.set_char('█').set_fg(color);
311 }
312 }
313}
314
315widget_impls!(PairedBars);
316
317#[cfg(feature = "theme")]
318impl tui_nuances::Themed for PairedBars {
319 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
320 self.theme(theme)
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use ratatui::widgets::Widget;
328
329 fn render(c: &PairedBars, w: u16, h: u16) -> Buffer {
330 let a = Rect::new(0, 0, w, h);
331 let mut buf = Buffer::empty(a);
332 c.render(a, &mut buf);
333 buf
334 }
335
336 fn text(buf: &Buffer) -> String {
337 buf.content().iter().map(|c| c.symbol()).collect()
338 }
339
340 fn blocks(buf: &Buffer, color: Color) -> usize {
341 buf.content()
342 .iter()
343 .filter(|c| c.symbol() == "█" && c.fg == color)
344 .count()
345 }
346
347 #[test]
348 fn the_larger_value_gets_the_longer_bar() {
349 let c = PairedBars::new([PairedBarsItem::new("mean", 4.0, 1.0)])
350 .before_color(Color::Red)
351 .after_color(Color::Green);
352 let buf = render(&c, 50, 2);
353 assert!(blocks(&buf, Color::Red) > blocks(&buf, Color::Green));
354 assert!(text(&buf).contains("mean"));
355 assert!(text(&buf).contains("4.0") && text(&buf).contains("1.0"));
356 }
357
358 #[test]
359 fn a_value_above_zero_always_shows_a_bar() {
360 let c =
361 PairedBars::new([PairedBarsItem::new("m", 1000.0, 0.001)]).after_color(Color::Green);
362 assert_eq!(blocks(&render(&c, 50, 2), Color::Green), 1);
363 let zero = PairedBars::new([PairedBarsItem::new("m", 5.0, 0.0)]).after_color(Color::Green);
364 assert_eq!(blocks(&render(&zero, 50, 2), Color::Green), 0);
365 }
366
367 #[test]
368 fn each_measure_has_its_own_scale_and_unit() {
369 let c = PairedBars::new([
370 PairedBarsItem::new("a", 2.0, 1.0),
371 PairedBarsItem::new("b", 90.0, 45.0).unit("%"),
372 ])
373 .before_color(Color::Red);
374 let buf = render(&c, 50, 4);
375 assert!(text(&buf).contains("90.0%"));
376 let per_row = |y: u16| {
378 (0..50)
379 .filter(|x| buf[(*x, y)].fg == Color::Red && buf[(*x, y)].symbol() == "█")
380 .count()
381 };
382 assert_eq!(per_row(1), per_row(3));
383 }
384
385 #[test]
386 fn stacked_puts_the_bars_on_two_rows() {
387 let c = PairedBars::new([PairedBarsItem::new("m", 4.0, 2.0)])
388 .layout(PairedBarsLayout::Stacked)
389 .before_color(Color::Red)
390 .after_color(Color::Green);
391 let buf = render(&c, 40, 3);
392 let row = |y: u16, color: Color| {
393 (0..40)
394 .filter(|x| buf[(*x, y)].fg == color && buf[(*x, y)].symbol() == "█")
395 .count()
396 };
397 assert!(row(1, Color::Red) > 0 && row(1, Color::Green) == 0);
398 assert!(row(2, Color::Green) > 0 && row(2, Color::Red) == 0);
399 }
400
401 #[test]
402 fn the_legend_needs_a_spare_row() {
403 let c = PairedBars::new([PairedBarsItem::new("m", 4.0, 2.0)]).legend("old", "new");
404 assert!(text(&render(&c, 40, 3)).contains("new"));
405 assert!(!text(&render(&c, 40, 2)).contains("new"));
406 }
407
408 #[test]
409 fn decimals_and_a_cap_on_the_bar() {
410 let c = PairedBars::new([PairedBarsItem::new("m", 4.0, 2.0)])
411 .decimals(2)
412 .max_bar_width(5)
413 .before_color(Color::Red);
414 let buf = render(&c, 80, 2);
415 assert!(text(&buf).contains("4.00"));
416 assert_eq!(blocks(&buf, Color::Red), 5);
417 }
418
419 #[test]
420 fn degenerate_inputs_do_not_panic() {
421 let c = PairedBars::new([PairedBarsItem::new("x", f64::NAN, f64::INFINITY)]);
422 for l in [PairedBarsLayout::Inline, PairedBarsLayout::Stacked] {
423 let c = c.clone().layout(l).legend("a", "b");
424 for (w, h) in [(0, 0), (3, 1), (8, 1), (20, 2), (40, 12)] {
425 render(&c, w, h);
426 }
427 }
428 render(&PairedBars::new([]), 20, 3);
429 render(
430 &PairedBars::new([PairedBarsItem::new("n", -3.0, -1.0)]),
431 20,
432 3,
433 );
434 }
435
436 #[test]
437 fn labels_take_their_color() {
438 let c = PairedBars::new([PairedBarsItem::new("lab", 4.0, 2.0)]).label_color(Color::Magenta);
439 let buf = render(&c, 40, 2);
440 assert_eq!(buf[(0, 0)].fg, Color::Magenta);
441 }
442
443 #[test]
444 fn many_measures_are_cut_to_fit() {
445 let items = (0..8).map(|i| PairedBarsItem::new(format!("m{i}"), 3.0, 1.0));
446 let c = PairedBars::new(items);
447 for h in [1, 2, 3, 7, 40] {
448 render(&c, 50, h);
449 }
450 }
451}