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