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