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