1use crate::axis::Axis;
4use crate::canvas::{Canvas, Marker};
5use crate::heatmap::Gradient;
6use crate::layout::{self, text_width};
7use crate::theme::{self, Theme};
8use crate::util::{format_compact, nice_bounds};
9use crate::PALETTE;
10use ratatui::{
11 buffer::Buffer,
12 layout::Rect,
13 style::{Color, Style},
14 widgets::Block,
15};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum BarOrientation {
21 #[default]
23 Vertical,
24 Horizontal,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub enum BarMode {
32 #[default]
34 Grouped,
35 Stacked,
37}
38
39#[derive(Debug, Clone, Default, PartialEq)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub struct BarGroup {
43 pub label: String,
45 pub values: Vec<f64>,
47 pub bar_colors: Vec<Option<Color>>,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54pub enum LabelPosition {
55 #[default]
57 Outside,
58 Inside,
60}
61
62impl BarGroup {
63 pub fn new(label: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
65 Self {
66 label: label.into(),
67 values: values.into_iter().collect(),
68 bar_colors: vec![],
69 }
70 }
71
72 pub fn bar_color(mut self, index: usize, color: Color) -> Self {
74 if self.bar_colors.len() <= index {
75 self.bar_colors.resize(index + 1, None);
76 }
77 self.bar_colors[index] = Some(color);
78 self
79 }
80}
81
82const BOTTOM_EIGHTHS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
83const LEFT_EIGHTHS: [char; 9] = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
84
85#[derive(Debug, Clone, Default)]
99pub struct BarChart {
100 groups: Vec<BarGroup>,
101 series_names: Vec<String>,
102 colors: Vec<Color>,
103 orientation: BarOrientation,
104 mode: BarMode,
105 bar_width: Option<u16>,
106 bar_gap: u16,
107 group_gap: Option<u16>,
108 show_values: bool,
109 label_position: LabelPosition,
110 max: Option<f64>,
111 block: Option<Block<'static>>,
112 value_axis: Axis,
113 category_axis: Axis,
114 gradient: Option<Gradient>,
115 theme: Option<Theme>,
116 style: Option<Style>,
117 marker: Option<Marker>,
118}
119
120impl BarChart {
121 pub fn new(groups: Vec<BarGroup>) -> Self {
123 Self {
124 groups,
125 value_axis: Axis::new().grid(true),
126 ..Default::default()
127 }
128 }
129
130 opt_setter!(
131 marker: Marker
136 );
137
138 pub fn marker_kind(&self) -> Option<Marker> {
140 self.marker
141 }
142
143 fn dot_cell(
146 buf: &mut Buffer,
147 m: Marker,
148 (x, y, w): (u16, u16, u16),
149 fill: usize,
150 vertical: bool,
151 color: Color,
152 ) {
153 let mut cv = Canvas::new(w, 1, m);
154 let (pw, ph) = (cv.px_w(), cv.px_h());
155 if vertical {
156 let n = ((fill as i32 * ph + 4) / 8).clamp(1, ph);
157 for py in ph - n..ph {
158 for px in 0..pw {
159 cv.set(px, py, color);
160 }
161 }
162 } else {
163 let (rx, _) = m.resolution();
164 let n = ((fill as i32 * rx as i32 + 4) / 8).clamp(1, rx as i32);
166 for cx in 0..w as i32 {
167 for dx in 0..n {
168 for py in 0..ph {
169 cv.set(cx * rx as i32 + dx, py, color);
170 }
171 }
172 }
173 }
174 cv.render(buf, Rect::new(x, y, w, 1));
175 }
176
177 pub fn series_names<I, S>(mut self, names: I) -> Self
179 where
180 I: IntoIterator<Item = S>,
181 S: Into<String>,
182 {
183 self.series_names = names.into_iter().map(Into::into).collect();
184 self
185 }
186
187 setter!(
188 colors: Vec<Color>
190 );
191
192 setter!(
193 orientation: BarOrientation
195 );
196
197 setter!(
198 mode: BarMode
200 );
201
202 pub fn bar_width(mut self, w: u16) -> Self {
204 self.bar_width = Some(w.max(1));
205 self
206 }
207
208 setter!(
209 bar_gap: u16
211 );
212
213 opt_setter!(
214 group_gap: u16
216 );
217
218 setter!(
219 show_values: bool
221 );
222
223 setter!(
224 label_position: LabelPosition
226 );
227
228 opt_setter!(
229 max: f64
231 );
232
233 opt_setter!(
234 gradient: Gradient
237 );
238
239 #[cfg(feature = "theme")]
241 pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
242 let t = theme.into();
243 self.value_axis.theme_in_place(&t);
244 self.category_axis.theme_in_place(&t);
245 self.theme = Some(t);
246 self
247 }
248
249 base_style_setter!(style);
250
251 fn label_color(&self) -> Color {
252 self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
253 }
254
255 block_setter!(block, 'static);
256
257 setter!(
258 value_axis: Axis
260 );
261
262 setter!(
263 category_axis: Axis
265 );
266
267 fn n_series(&self) -> usize {
268 self.groups
269 .iter()
270 .map(|g| g.values.len())
271 .max()
272 .unwrap_or(1)
273 .max(1)
274 }
275
276 fn color(&self, i: usize) -> Color {
277 self.colors
278 .get(i)
279 .copied()
280 .unwrap_or_else(|| match &self.theme {
281 Some(t) => t.color(i),
282 None => PALETTE[i % PALETTE.len()],
283 })
284 }
285
286 fn color_for(&self, g: &BarGroup, i: usize) -> Color {
287 g.bar_colors
288 .get(i)
289 .copied()
290 .flatten()
291 .unwrap_or_else(|| self.color(i))
292 }
293
294 fn clean(v: f64) -> f64 {
296 if v.is_finite() && v > 0.0 {
297 v
298 } else {
299 0.0
300 }
301 }
302
303 fn group_total(&self, g: &BarGroup) -> f64 {
304 match self.mode {
305 BarMode::Stacked => g.values.iter().map(|&v| Self::clean(v)).sum(),
306 BarMode::Grouped => g.values.iter().map(|&v| Self::clean(v)).fold(0.0, f64::max),
307 }
308 }
309
310 fn neg(v: f64) -> f64 {
312 if v.is_finite() && v < 0.0 {
313 -v
314 } else {
315 0.0
316 }
317 }
318
319 fn group_neg_total(&self, g: &BarGroup) -> f64 {
321 match self.mode {
322 BarMode::Stacked => g.values.iter().map(|&v| Self::neg(v)).sum(),
323 BarMode::Grouped => g.values.iter().map(|&v| Self::neg(v)).fold(0.0, f64::max),
324 }
325 }
326
327 fn baseline(cells: u16, lo: f64, hi: f64) -> u16 {
329 if lo >= 0.0 || cells == 0 {
330 0
331 } else if hi <= 0.0 {
332 cells
333 } else {
334 let z = (-lo / (hi - lo) * cells as f64).round() as i64;
335 z.clamp(1, (cells as i64 - 1).max(1)) as u16
336 }
337 }
338
339 fn display_frac(f: f64, lo: f64, hi: f64, cells: u16, zc: u16) -> f64 {
341 if zc == 0 || cells == 0 {
342 return f;
343 }
344 let v = lo + f * (hi - lo);
345 let z = zc as f64;
346 let c = cells as f64;
347 let cell = if v >= 0.0 && hi > 0.0 {
348 z + v / hi * (c - z)
349 } else if lo < 0.0 {
350 z + v / -lo * z
351 } else {
352 z
353 };
354 cell / c
355 }
356
357 fn neg_eighths(&self, g: &BarGroup, lo: f64, cells: u16) -> Vec<i32> {
360 if lo >= 0.0 || cells == 0 {
361 return vec![0; g.values.len()];
362 }
363 let scale = cells as f64 * 8.0 / -lo;
364 let cap = cells as i32 * 8;
365 match self.mode {
366 BarMode::Stacked => {
367 let mut acc = 0.0;
368 g.values
369 .iter()
370 .map(|&v| {
371 acc += Self::neg(v);
372 ((acc * scale).round() as i32).clamp(0, cap)
373 })
374 .collect()
375 }
376 BarMode::Grouped => g
377 .values
378 .iter()
379 .map(|&v| ((Self::neg(v) * scale).round() as i32).clamp(0, cap))
380 .collect(),
381 }
382 }
383
384 pub fn bounds(&self) -> (f64, f64) {
386 if let Some(b) = self.value_axis.bounds {
387 return b;
388 }
389 let min_neg = self
390 .groups
391 .iter()
392 .map(|g| self.group_neg_total(g))
393 .fold(0.0, f64::max);
394 if min_neg > 0.0 {
395 let max = self.max.unwrap_or_else(|| {
396 self.groups
397 .iter()
398 .map(|g| self.group_total(g))
399 .fold(0.0, f64::max)
400 });
401 let (lo, hi) = nice_bounds(-min_neg, max.max(0.0), self.value_axis.ticks);
402 return (lo, if max > 0.0 { hi } else { 0.0 });
403 }
404 let max = self.max.unwrap_or_else(|| {
405 self.groups
406 .iter()
407 .map(|g| self.group_total(g))
408 .fold(0.0, f64::max)
409 });
410 if max <= 0.0 {
411 return (0.0, 1.0);
412 }
413 let (_, hi) = nice_bounds(0.0, max, self.value_axis.ticks);
414 (0.0, hi)
415 }
416
417 fn format_value(&self, v: f64) -> String {
418 match self.value_axis.format(v) {
419 Some(l) => l,
420 None => format_compact(v),
421 }
422 }
423
424 fn eighths_for(&self, g: &BarGroup, lo: f64, hi: f64, cells: u16) -> Vec<i32> {
426 if hi <= lo || cells == 0 {
427 return vec![0; g.values.len()];
428 }
429 let scale = cells as f64 * 8.0 / (hi - lo);
430 match self.mode {
431 BarMode::Stacked => {
432 let mut acc = 0.0;
433 g.values
434 .iter()
435 .map(|&v| {
436 acc += Self::clean(v);
437 (((acc - lo) * scale).round() as i32).clamp(0, cells as i32 * 8)
438 })
439 .collect()
440 }
441 BarMode::Grouped => g
442 .values
443 .iter()
444 .map(|&v| {
445 (((Self::clean(v) - lo) * scale).round() as i32).clamp(0, cells as i32 * 8)
446 })
447 .collect(),
448 }
449 }
450
451 fn auto_thickness(&self, avail: u16, n_groups: usize, per_group: usize, group_gap: u16) -> u16 {
452 if let Some(w) = self.bar_width {
453 return w;
454 }
455 let g = n_groups.max(1) as i32;
456 let n = per_group.max(1) as i32;
457 let slot = avail as i32 / g;
458 let w = (slot - group_gap as i32 - self.bar_gap as i32 * (n - 1)) / n;
459 w.clamp(
460 1,
461 if self.orientation == BarOrientation::Vertical {
462 8
463 } else {
464 3
465 },
466 ) as u16
467 }
468
469 pub(crate) fn vertical_geometry(&self, area: Rect) -> Option<(Rect, f64, f64, u16)> {
472 let inner = match &self.block {
473 Some(b) => b.inner(area),
474 None => area,
475 };
476 let (lo, hi) = self.bounds();
477 if hi <= lo {
478 return None;
479 }
480 let marks = self.value_axis.tick_marks((lo, hi));
481 let yw = marks.iter().map(|(_, l)| text_width(l)).max().unwrap_or(0);
482 let has_labels = self.groups.iter().any(|g| !g.label.is_empty());
483 let a = layout::compute(
484 inner,
485 yw,
486 has_labels,
487 self.category_axis.title.is_some(),
488 self.value_axis.title.is_some(),
489 )?;
490 let n = if self.mode == BarMode::Stacked {
491 1
492 } else {
493 self.n_series()
494 };
495 let gg = self.group_gap.unwrap_or(1);
496 let bw = self.auto_thickness(a.plot.width, self.groups.len(), n, gg);
497 Some((a.plot, lo, hi, bw))
498 }
499
500 fn render_into(&self, area: Rect, buf: &mut Buffer) {
501 let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
502 match self.orientation {
503 BarOrientation::Vertical => self.render_vertical(inner, buf),
504 BarOrientation::Horizontal => self.render_horizontal(inner, buf),
505 }
506 }
507
508 fn render_vertical(&self, inner: Rect, buf: &mut Buffer) {
509 let (lo, hi) = self.bounds();
510 if hi <= lo {
511 return;
512 }
513 let marks = self.value_axis.tick_marks((lo, hi));
514 let yw = marks.iter().map(|(_, l)| text_width(l)).max().unwrap_or(0);
515 let has_labels = self.groups.iter().any(|g| !g.label.is_empty());
516 let Some(a) = layout::compute(
517 inner,
518 yw,
519 has_labels,
520 self.category_axis.title.is_some(),
521 self.value_axis.title.is_some(),
522 ) else {
523 return;
524 };
525 let plot = a.plot;
526 let n = if self.mode == BarMode::Stacked {
527 1
528 } else {
529 self.n_series()
530 };
531 let gg = self.group_gap.unwrap_or(1);
532 let bw = self.auto_thickness(plot.width, self.groups.len(), n, gg);
533 let group_w = bw * n as u16 + self.bar_gap * (n as u16 - 1);
534 let slot = (group_w + gg) as usize;
535 let visible = ((plot.width as usize + gg as usize) / slot).max(1);
536
537 let zc = Self::baseline(plot.height, lo, hi);
538 let pos_cells = plot.height - zc;
539 let (plo, phi) = if zc > 0 { (0.0, hi) } else { (lo, hi) };
540 let y_ticks: Vec<(u16, String)> = marks
541 .iter()
542 .map(|(f, l)| {
543 let df = Self::display_frac(*f, lo, hi, plot.height, zc);
544 (layout::frac_row(df, plot.height, 8), l.clone())
545 })
546 .collect();
547 if self.value_axis.grid {
548 let rows: Vec<u16> = y_ticks.iter().map(|t| t.0).collect();
549 layout::draw_grid(
550 buf,
551 plot,
552 &[],
553 &rows,
554 self.value_axis.grid_style,
555 self.value_axis.grid_kind,
556 );
557 }
558
559 let mut x_ticks = vec![];
560 for (gi, g) in self.groups.iter().take(visible).enumerate() {
561 let gx = plot.x + (gi * slot) as u16;
562 if gx + group_w > plot.right() {
563 break;
564 }
565 x_ticks.push((gx - plot.x + group_w / 2, g.label.clone()));
566 let eighths = self.eighths_for(g, plo, phi, pos_cells);
567 let negs = self.neg_eighths(g, lo, zc);
568 let bars = if self.mode == BarMode::Stacked {
569 1
570 } else {
571 g.values.len()
572 };
573 for bi in 0..bars {
574 let x = gx + bi as u16 * (bw + self.bar_gap);
575 self.draw_neg_vertical(buf, plot, g, &negs, bi, x, bw, zc);
576 let total = if self.mode == BarMode::Stacked {
577 eighths.last().copied().unwrap_or(0)
578 } else {
579 eighths[bi]
580 };
581 for r in 0..pos_cells as i32 {
582 let fill = (total - r * 8).clamp(0, 8) as usize;
583 if fill == 0 {
584 break;
585 }
586 let color = if self.mode == BarMode::Stacked {
587 let p = r * 8 + fill as i32 - 1;
588 let k = eighths
589 .iter()
590 .position(|&c| p < c)
591 .unwrap_or(eighths.len() - 1);
592 self.color_for_cell(
593 g,
594 k,
595 (r * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0),
596 )
597 } else {
598 self.color_for_cell(
599 g,
600 bi,
601 (r * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0),
602 )
603 };
604 let y = plot.bottom() - 1 - zc - r as u16;
605 if let Some(m) = self.marker {
606 Self::dot_cell(buf, m, (x, y, bw), fill, true, color);
607 continue;
608 }
609 for dx in 0..bw {
610 buf.set_string(
611 x + dx,
612 y,
613 BOTTOM_EIGHTHS[fill].to_string(),
614 Style::default().fg(color),
615 );
616 }
617 }
618 if self.show_values && total > 0 {
619 let value = if self.mode == BarMode::Stacked {
620 self.group_total(g)
621 } else {
622 g.values[bi]
623 };
624 let text = self.format_value(value);
625 let tw = text_width(&text);
626 let top_cells = (total + 7) / 8;
627 if self.label_position == LabelPosition::Inside {
628 if top_cells >= 1 && tw <= bw {
629 let y = plot.bottom() - zc - top_cells as u16;
630 let tx = x + (bw - tw) / 2;
631 let c = if self.mode == BarMode::Stacked {
632 self.color_for(g, g.values.len().saturating_sub(1))
633 } else {
634 self.color_for(g, bi)
635 };
636 buf.set_string(tx, y, text, Style::default().fg(Color::Black).bg(c));
637 }
638 } else if top_cells < pos_cells as i32 && tw <= bw + 1 + self.bar_gap {
639 let y = plot.bottom() - 1 - zc - top_cells as u16;
640 let tx = (x + bw / 2).saturating_sub(tw / 2).max(plot.x);
641 let tx = tx.min(plot.right().saturating_sub(tw));
642 buf.set_string(tx, y, text, Style::default().fg(self.label_color()));
643 }
644 }
645 }
646 }
647
648 layout::draw_axes(buf, &a, self.category_axis.style, self.value_axis.style);
649 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.value_axis.label_style);
650 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.category_axis.label_style);
651 layout::draw_titles(
652 buf,
653 inner,
654 &a,
655 self.category_axis
656 .title
657 .as_deref()
658 .map(|t| (t, self.category_axis.label_style)),
659 self.value_axis
660 .title
661 .as_deref()
662 .map(|t| (t, self.value_axis.label_style)),
663 );
664 self.draw_legend(buf, plot);
665 }
666
667 fn render_horizontal(&self, inner: Rect, buf: &mut Buffer) {
668 let (lo, hi) = self.bounds();
669 if hi <= lo {
670 return;
671 }
672 let marks = self.value_axis.tick_marks((lo, hi));
673 let yw = self
674 .groups
675 .iter()
676 .map(|g| text_width(&g.label))
677 .max()
678 .unwrap_or(0)
679 .min(16);
680 let Some(a) = layout::compute(
681 inner,
682 yw,
683 !marks.is_empty(),
684 self.value_axis.title.is_some(),
685 self.category_axis.title.is_some(),
686 ) else {
687 return;
688 };
689 let plot = a.plot;
690 let n = if self.mode == BarMode::Stacked {
691 1
692 } else {
693 self.n_series()
694 };
695 let gg = self
696 .group_gap
697 .unwrap_or(if plot.height as usize >= self.groups.len() * (n + 1) {
698 1
699 } else {
700 0
701 });
702 let bh = self.auto_thickness(plot.height, self.groups.len(), n, gg);
703 let group_h = bh * n as u16 + self.bar_gap * (n as u16 - 1);
704 let slot = (group_h + gg) as usize;
705 let visible = ((plot.height as usize + gg as usize) / slot).max(1);
706
707 let zc = Self::baseline(plot.width, lo, hi);
708 let pos_cells = plot.width - zc;
709 let (plo, phi) = if zc > 0 { (0.0, hi) } else { (lo, hi) };
710 let x_ticks: Vec<(u16, String)> = marks
711 .iter()
712 .map(|(f, l)| {
713 let df = Self::display_frac(*f, lo, hi, plot.width, zc);
714 (layout::frac_col(df, plot.width, 1), l.clone())
715 })
716 .collect();
717 if self.value_axis.grid {
718 let cols: Vec<u16> = x_ticks.iter().map(|t| t.0).collect();
719 layout::draw_grid(
720 buf,
721 plot,
722 &cols,
723 &[],
724 self.value_axis.grid_style,
725 self.value_axis.grid_kind,
726 );
727 }
728
729 let mut y_ticks = vec![];
730 for (gi, g) in self.groups.iter().take(visible).enumerate() {
731 let gy = plot.y + (gi * slot) as u16;
732 if gy + group_h > plot.bottom() {
733 break;
734 }
735 let label: String = g.label.chars().take(yw as usize).collect();
736 y_ticks.push((gy - plot.y + group_h / 2, label));
737 let eighths = self.eighths_for(g, plo, phi, pos_cells);
738 let negs = self.neg_eighths(g, lo, zc);
739 let bars = if self.mode == BarMode::Stacked {
740 1
741 } else {
742 g.values.len()
743 };
744 for bi in 0..bars {
745 let y = gy + bi as u16 * (bh + self.bar_gap);
746 self.draw_neg_horizontal(buf, plot, g, &negs, bi, y, bh, zc);
747 let total = if self.mode == BarMode::Stacked {
748 eighths.last().copied().unwrap_or(0)
749 } else {
750 eighths[bi]
751 };
752 for c in 0..pos_cells as i32 {
753 let fill = (total - c * 8).clamp(0, 8) as usize;
754 if fill == 0 {
755 break;
756 }
757 let frac = (c * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0);
758 let color = if self.mode == BarMode::Stacked {
759 let p = c * 8 + fill as i32 - 1;
760 let k = eighths
761 .iter()
762 .position(|&e| p < e)
763 .unwrap_or(eighths.len() - 1);
764 self.color_for_cell(g, k, frac)
765 } else {
766 self.color_for_cell(g, bi, frac)
767 };
768 if let Some(m) = self.marker {
769 for dy in 0..bh {
770 let cx = plot.x + zc + c as u16;
771 Self::dot_cell(buf, m, (cx, y + dy, 1), fill, false, color);
772 }
773 continue;
774 }
775 for dy in 0..bh {
776 buf.set_string(
777 plot.x + zc + c as u16,
778 y + dy,
779 LEFT_EIGHTHS[fill].to_string(),
780 Style::default().fg(color),
781 );
782 }
783 }
784 if self.show_values && total > 0 {
785 let value = if self.mode == BarMode::Stacked {
786 self.group_total(g)
787 } else {
788 g.values[bi]
789 };
790 let text = self.format_value(value);
791 let tw = text_width(&text);
792 let end = ((total + 7) / 8) as u16;
793 if self.label_position == LabelPosition::Inside {
794 if end >= tw {
795 let c = if self.mode == BarMode::Stacked {
796 self.color_for(g, g.values.len().saturating_sub(1))
797 } else {
798 self.color_for(g, bi)
799 };
800 buf.set_string(
801 plot.x + zc + end - tw,
802 y + bh / 2,
803 text,
804 Style::default().fg(Color::Black).bg(c),
805 );
806 }
807 } else if zc + end + 1 + tw <= plot.width {
808 buf.set_string(
809 plot.x + zc + end + 1,
810 y + bh / 2,
811 text,
812 Style::default().fg(self.label_color()),
813 );
814 }
815 }
816 }
817 }
818
819 layout::draw_axes(buf, &a, self.value_axis.style, self.category_axis.style);
820 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.category_axis.label_style);
821 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.value_axis.label_style);
822 layout::draw_titles(
823 buf,
824 inner,
825 &a,
826 self.value_axis
827 .title
828 .as_deref()
829 .map(|t| (t, self.value_axis.label_style)),
830 self.category_axis
831 .title
832 .as_deref()
833 .map(|t| (t, self.category_axis.label_style)),
834 );
835 self.draw_legend(buf, plot);
836 }
837
838 fn color_for_cell(&self, g: &BarGroup, i: usize, frac: f64) -> Color {
841 let explicit = g.bar_colors.get(i).copied().flatten();
842 match (&self.gradient, explicit) {
843 (_, Some(c)) => c,
844 (Some(grad), None) => grad.color_at(frac),
845 (None, None) => self.color(i),
846 }
847 }
848
849 #[allow(clippy::too_many_arguments)]
851 fn draw_neg_vertical(
852 &self,
853 buf: &mut Buffer,
854 plot: Rect,
855 g: &BarGroup,
856 negs: &[i32],
857 bi: usize,
858 x: u16,
859 bw: u16,
860 zc: u16,
861 ) {
862 if zc == 0 {
863 return;
864 }
865 let total = if self.mode == BarMode::Stacked {
866 negs.last().copied().unwrap_or(0)
867 } else {
868 negs[bi]
869 };
870 if total <= 0 {
871 return;
872 }
873 let rows = (total + 7) / 8;
874 for r in 0..rows.min(zc as i32) {
875 let rem = (total - r * 8).clamp(0, 8);
876 let sym = match rem {
877 6..=8 => '█',
878 3..=5 => '▀',
879 _ => '▔',
880 };
881 let k = if self.mode == BarMode::Stacked {
882 let p = r * 8 + rem - 1;
883 negs.iter().position(|&c| p < c).unwrap_or(negs.len() - 1)
884 } else {
885 bi
886 };
887 let color = self.color_for_cell(g, k, 0.0);
888 let y = plot.bottom() - zc + r as u16;
889 if y >= plot.bottom() {
890 break;
891 }
892 for dx in 0..bw {
893 buf.set_string(x + dx, y, sym.to_string(), Style::default().fg(color));
894 }
895 }
896 if self.show_values {
897 let value = if self.mode == BarMode::Stacked {
898 -g.values.iter().map(|&v| Self::neg(v)).sum::<f64>()
899 } else {
900 g.values[bi]
901 };
902 let text = self.format_value(value);
903 let tw = text_width(&text);
904 let y = plot.bottom() - zc + rows as u16;
905 if y < plot.bottom() && tw <= bw + 1 + self.bar_gap {
906 let tx = (x + bw / 2).saturating_sub(tw / 2).max(plot.x);
907 let tx = tx.min(plot.right().saturating_sub(tw));
908 buf.set_string(tx, y, text, Style::default().fg(self.label_color()));
909 }
910 }
911 }
912
913 #[allow(clippy::too_many_arguments)]
915 fn draw_neg_horizontal(
916 &self,
917 buf: &mut Buffer,
918 plot: Rect,
919 g: &BarGroup,
920 negs: &[i32],
921 bi: usize,
922 y: u16,
923 bh: u16,
924 zc: u16,
925 ) {
926 if zc == 0 {
927 return;
928 }
929 let total = if self.mode == BarMode::Stacked {
930 negs.last().copied().unwrap_or(0)
931 } else {
932 negs[bi]
933 };
934 if total <= 0 {
935 return;
936 }
937 let cols = (total + 7) / 8;
938 for c in 0..cols.min(zc as i32) {
939 let rem = (total - c * 8).clamp(0, 8);
940 let sym = match rem {
941 6..=8 => '█',
942 3..=5 => '▐',
943 _ => '▕',
944 };
945 let k = if self.mode == BarMode::Stacked {
946 let p = c * 8 + rem - 1;
947 negs.iter().position(|&e| p < e).unwrap_or(negs.len() - 1)
948 } else {
949 bi
950 };
951 let color = self.color_for_cell(g, k, 0.0);
952 let x = plot.x + zc - 1 - c as u16;
953 for dy in 0..bh {
954 buf.set_string(x, y + dy, sym.to_string(), Style::default().fg(color));
955 }
956 }
957 if self.show_values {
958 let value = if self.mode == BarMode::Stacked {
959 -g.values.iter().map(|&v| Self::neg(v)).sum::<f64>()
960 } else {
961 g.values[bi]
962 };
963 let text = self.format_value(value);
964 let tw = text_width(&text);
965 let tip = zc as i32 - cols;
966 if tip - 1 - tw as i32 >= 0 {
967 buf.set_string(
968 plot.x + (tip - 1) as u16 - tw,
969 y + bh / 2,
970 text,
971 Style::default().fg(self.label_color()),
972 );
973 }
974 }
975 }
976
977 fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
978 let w = self
979 .series_names
980 .iter()
981 .map(|n| text_width(n) + 2)
982 .max()
983 .unwrap_or(0);
984 if w == 0 || w > plot.width {
985 return;
986 }
987 for (i, name) in self.series_names.iter().enumerate() {
988 if i as u16 >= plot.height {
989 break;
990 }
991 let y = plot.y + i as u16;
992 for x in plot.right() - w..plot.right() {
994 buf.set_string(x, y, " ", Style::default());
995 }
996 buf.set_string(plot.right() - w, y, "■", Style::default().fg(self.color(i)));
997 buf.set_string(
998 plot.right() - w + 2,
999 y,
1000 name,
1001 Style::default().fg(self.label_color()),
1002 );
1003 }
1004 }
1005}
1006
1007widget_impls!(BarChart);
1008
1009#[cfg(feature = "theme")]
1010impl tui_nuances::Themed for BarChart {
1011 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
1012 self.theme(theme)
1013 }
1014}
1015
1016#[cfg(test)]
1017mod tests {
1018 use super::*;
1019 use ratatui::widgets::Widget;
1020
1021 fn groups() -> Vec<BarGroup> {
1022 vec![
1023 BarGroup::new("Q1", [10.0, 20.0]),
1024 BarGroup::new("Q2", [30.0, 5.0]),
1025 BarGroup::new("Q3", [25.0, 15.0]),
1026 ]
1027 }
1028
1029 fn dump(buf: &Buffer, area: Rect) -> String {
1030 (area.y..area.bottom())
1031 .flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
1032 .map(|p| buf[p].symbol().to_string())
1033 .collect()
1034 }
1035
1036 #[test]
1037 fn bounds_grouped_vs_stacked() {
1038 let g = BarChart::new(groups());
1039 assert_eq!(g.bounds(), (0.0, 30.0));
1040 let s = BarChart::new(groups()).mode(BarMode::Stacked);
1041 assert_eq!(s.bounds().1, 40.0);
1042 assert_eq!(BarChart::new(groups()).max(100.0).bounds().1, 100.0);
1043 assert_eq!(BarChart::new(vec![]).bounds(), (0.0, 1.0));
1044 }
1045
1046 #[test]
1047 fn negative_and_nan_values_clamped() {
1048 let c = BarChart::new(vec![BarGroup::new("a", [f64::NAN, 3.0])]);
1049 assert_eq!(c.bounds().1, 3.0);
1050 let n = BarChart::new(vec![BarGroup::new("a", [-5.0, f64::NAN, 3.0])]);
1051 assert!(n.bounds().0 <= -5.0);
1052 }
1053
1054 #[test]
1055 fn vertical_grouped_draws_colors() {
1056 let area = Rect::new(0, 0, 40, 14);
1057 let mut buf = Buffer::empty(area);
1058 BarChart::new(groups())
1059 .colors(vec![Color::Red, Color::Blue])
1060 .render(area, &mut buf);
1061 let fg: Vec<Color> = (0..40)
1062 .flat_map(|x| (0..14).map(move |y| (x, y)))
1063 .filter(|p| buf[*p].symbol() == "█")
1064 .map(|p| buf[p].fg)
1065 .collect();
1066 assert!(fg.contains(&Color::Red));
1067 assert!(fg.contains(&Color::Blue));
1068 assert!(dump(&buf, area).contains("Q1"));
1069 }
1070
1071 #[test]
1072 fn vertical_stacked_uses_segment_colors() {
1073 let area = Rect::new(0, 0, 40, 14);
1074 let mut buf = Buffer::empty(area);
1075 BarChart::new(groups())
1076 .mode(BarMode::Stacked)
1077 .colors(vec![Color::Red, Color::Blue])
1078 .render(area, &mut buf);
1079 let fg: Vec<Color> = (0..40)
1080 .flat_map(|x| (0..14).map(move |y| (x, y)))
1081 .filter(|p| matches!(buf[*p].symbol(), "█" | "▄" | "▅" | "▆" | "▇"))
1082 .map(|p| buf[p].fg)
1083 .collect();
1084 assert!(fg.contains(&Color::Red) && fg.contains(&Color::Blue));
1085 }
1086
1087 #[test]
1088 fn horizontal_draws_partial_blocks_and_values() {
1089 let area = Rect::new(0, 0, 40, 12);
1090 let mut buf = Buffer::empty(area);
1091 BarChart::new(groups())
1092 .orientation(BarOrientation::Horizontal)
1093 .show_values(true)
1094 .render(area, &mut buf);
1095 let t = dump(&buf, area);
1096 assert!(t.contains('█'));
1097 assert!(t.contains("Q3"));
1098 assert!(t.contains("25"));
1099 }
1100
1101 #[test]
1102 fn horizontal_stacked() {
1103 let area = Rect::new(0, 0, 40, 12);
1104 let mut buf = Buffer::empty(area);
1105 BarChart::new(groups())
1106 .orientation(BarOrientation::Horizontal)
1107 .mode(BarMode::Stacked)
1108 .series_names(["a", "b"])
1109 .render(area, &mut buf);
1110 assert!(dump(&buf, area).contains('■'));
1111 }
1112
1113 #[test]
1114 fn value_labels_vertical() {
1115 let area = Rect::new(0, 0, 40, 14);
1116 let mut buf = Buffer::empty(area);
1117 BarChart::new(groups())
1118 .bar_width(3)
1119 .show_values(true)
1120 .render(area, &mut buf);
1121 let t = dump(&buf, area);
1122 assert!(t.contains("10") || t.contains("20"));
1123 }
1124
1125 #[test]
1126 fn many_groups_are_truncated_not_panicking() {
1127 let g: Vec<BarGroup> = (0..100)
1128 .map(|i| BarGroup::new(format!("{i}"), [i as f64]))
1129 .collect();
1130 let area = Rect::new(0, 0, 30, 10);
1131 let mut buf = Buffer::empty(area);
1132 BarChart::new(g.clone()).render(area, &mut buf);
1133 BarChart::new(g)
1134 .orientation(BarOrientation::Horizontal)
1135 .render(area, &mut buf);
1136 }
1137
1138 #[test]
1139 fn tiny_and_empty_safe() {
1140 for (w, h) in [(0, 0), (2, 2), (8, 4), (10, 5)] {
1141 let area = Rect::new(0, 0, w, h);
1142 let mut buf = Buffer::empty(area);
1143 BarChart::new(groups()).render(area, &mut buf);
1144 BarChart::new(vec![]).render(area, &mut buf);
1145 BarChart::new(groups())
1146 .orientation(BarOrientation::Horizontal)
1147 .render(area, &mut buf);
1148 }
1149 }
1150
1151 #[test]
1152 fn group_helper() {
1153 let g = BarGroup::new("x", [1.0, 2.0]);
1154 assert_eq!(g.label, "x");
1155 assert_eq!(g.values, vec![1.0, 2.0]);
1156 }
1157}