1use crate::PALETTE;
4use crate::axis::Axis;
5use crate::canvas::{Canvas, Marker};
6use crate::heatmap::Gradient;
7use crate::interact;
8use crate::layout::{self, text_width};
9use crate::theme::{self, Theme};
10use crate::util::{format_compact, nice_bounds};
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 { v } else { 0.0 }
309 }
310
311 fn group_total(&self, g: &BarGroup) -> f64 {
312 match self.mode {
313 BarMode::Stacked => g.values.iter().map(|&v| Self::clean(v)).sum(),
314 BarMode::Grouped => g.values.iter().map(|&v| Self::clean(v)).fold(0.0, f64::max),
315 }
316 }
317
318 fn neg(v: f64) -> f64 {
320 if v.is_finite() && v < 0.0 { -v } else { 0.0 }
321 }
322
323 fn group_neg_total(&self, g: &BarGroup) -> f64 {
325 match self.mode {
326 BarMode::Stacked => g.values.iter().map(|&v| Self::neg(v)).sum(),
327 BarMode::Grouped => g.values.iter().map(|&v| Self::neg(v)).fold(0.0, f64::max),
328 }
329 }
330
331 fn baseline(cells: u16, lo: f64, hi: f64) -> u16 {
333 if lo >= 0.0 || cells == 0 {
334 0
335 } else if hi <= 0.0 {
336 cells
337 } else {
338 let z = (-lo / (hi - lo) * cells as f64).round() as i64;
339 z.clamp(1, (cells as i64 - 1).max(1)) as u16
340 }
341 }
342
343 fn display_frac(f: f64, lo: f64, hi: f64, cells: u16, zc: u16) -> f64 {
345 if zc == 0 || cells == 0 {
346 return f;
347 }
348 let v = lo + f * (hi - lo);
349 let z = zc as f64;
350 let c = cells as f64;
351 let cell = if v >= 0.0 && hi > 0.0 {
352 z + v / hi * (c - z)
353 } else if lo < 0.0 {
354 z + v / -lo * z
355 } else {
356 z
357 };
358 cell / c
359 }
360
361 fn neg_eighths(&self, g: &BarGroup, lo: f64, cells: u16) -> Vec<i32> {
364 if lo >= 0.0 || cells == 0 {
365 return vec![0; g.values.len()];
366 }
367 let scale = cells as f64 * 8.0 / -lo;
368 let cap = cells as i32 * 8;
369 match self.mode {
370 BarMode::Stacked => {
371 let mut acc = 0.0;
372 g.values
373 .iter()
374 .map(|&v| {
375 acc += Self::neg(v);
376 ((acc * scale).round() as i32).clamp(0, cap)
377 })
378 .collect()
379 }
380 BarMode::Grouped => g
381 .values
382 .iter()
383 .map(|&v| ((Self::neg(v) * scale).round() as i32).clamp(0, cap))
384 .collect(),
385 }
386 }
387
388 pub fn bounds(&self) -> (f64, f64) {
390 if let Some(b) = self.value_axis.bounds {
391 return b;
392 }
393 let min_neg = self
394 .groups
395 .iter()
396 .map(|g| self.group_neg_total(g))
397 .fold(0.0, f64::max);
398 if min_neg > 0.0 {
399 let max = self.max.unwrap_or_else(|| {
400 self.groups
401 .iter()
402 .map(|g| self.group_total(g))
403 .fold(0.0, f64::max)
404 });
405 let (lo, hi) = nice_bounds(-min_neg, max.max(0.0), self.value_axis.ticks);
406 return (lo, if max > 0.0 { hi } else { 0.0 });
407 }
408 let max = self.max.unwrap_or_else(|| {
409 self.groups
410 .iter()
411 .map(|g| self.group_total(g))
412 .fold(0.0, f64::max)
413 });
414 if max <= 0.0 {
415 return (0.0, 1.0);
416 }
417 let (_, hi) = nice_bounds(0.0, max, self.value_axis.ticks);
418 (0.0, hi)
419 }
420
421 fn format_value(&self, v: f64) -> String {
422 match self.value_axis.format(v) {
423 Some(l) => l,
424 None => format_compact(v),
425 }
426 }
427
428 fn eighths_for(&self, g: &BarGroup, lo: f64, hi: f64, cells: u16) -> Vec<i32> {
430 if hi <= lo || cells == 0 {
431 return vec![0; g.values.len()];
432 }
433 let scale = cells as f64 * 8.0 / (hi - lo);
434 match self.mode {
435 BarMode::Stacked => {
436 let mut acc = 0.0;
437 g.values
438 .iter()
439 .map(|&v| {
440 acc += Self::clean(v);
441 (((acc - lo) * scale).round() as i32).clamp(0, cells as i32 * 8)
442 })
443 .collect()
444 }
445 BarMode::Grouped => g
446 .values
447 .iter()
448 .map(|&v| {
449 (((Self::clean(v) - lo) * scale).round() as i32).clamp(0, cells as i32 * 8)
450 })
451 .collect(),
452 }
453 }
454
455 fn auto_thickness(&self, avail: u16, n_groups: usize, per_group: usize, group_gap: u16) -> u16 {
456 if let Some(w) = self.bar_width {
457 return w;
458 }
459 let g = n_groups.max(1) as i32;
460 let n = per_group.max(1) as i32;
461 let slot = avail as i32 / g;
462 let w = (slot - group_gap as i32 - self.bar_gap as i32 * (n - 1)) / n;
463 w.clamp(
464 1,
465 if self.orientation == BarOrientation::Vertical {
466 8
467 } else {
468 3
469 },
470 ) as u16
471 }
472
473 pub(crate) fn vertical_geometry(&self, area: Rect) -> Option<(Rect, f64, f64, u16)> {
476 let inner = match &self.block {
477 Some(b) => b.inner(area),
478 None => area,
479 };
480 let (lo, hi) = self.bounds();
481 if hi <= lo {
482 return None;
483 }
484 let marks = self.value_axis.tick_marks((lo, hi));
485 let yw = marks.iter().map(|(_, l)| text_width(l)).max().unwrap_or(0);
486 let has_labels = self.groups.iter().any(|g| !g.label.is_empty());
487 let a = layout::compute(
488 inner,
489 yw,
490 has_labels,
491 self.category_axis.title.is_some(),
492 self.value_axis.title.is_some(),
493 )?;
494 let n = if self.mode == BarMode::Stacked {
495 1
496 } else {
497 self.n_series()
498 };
499 let gg = self.group_gap.unwrap_or(1);
500 let bw = self.auto_thickness(a.plot.width, self.groups.len(), n, gg);
501 Some((a.plot, lo, hi, bw))
502 }
503
504 fn render_into(&self, area: Rect, buf: &mut Buffer) {
505 if !self.hidden.is_empty() {
506 let mut c = self.clone();
507 for g in &mut c.groups {
508 for &h in &self.hidden {
509 if let Some(v) = g.values.get_mut(h) {
510 *v = 0.0;
511 }
512 }
513 }
514 c.hidden.clear();
515 c.hidden_legend = self.hidden.clone();
516 return c.render_into(area, buf);
517 }
518 let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
519 match self.orientation {
520 BarOrientation::Vertical => self.render_vertical(inner, buf),
521 BarOrientation::Horizontal => self.render_horizontal(inner, buf),
522 }
523 }
524
525 fn render_vertical(&self, inner: Rect, buf: &mut Buffer) {
526 let (lo, hi) = self.bounds();
527 if hi <= lo {
528 return;
529 }
530 let marks = self.value_axis.tick_marks((lo, hi));
531 let yw = marks.iter().map(|(_, l)| text_width(l)).max().unwrap_or(0);
532 let has_labels = self.groups.iter().any(|g| !g.label.is_empty());
533 let Some(a) = layout::compute(
534 inner,
535 yw,
536 has_labels,
537 self.category_axis.title.is_some(),
538 self.value_axis.title.is_some(),
539 ) else {
540 return;
541 };
542 let plot = a.plot;
543 let n = if self.mode == BarMode::Stacked {
544 1
545 } else {
546 self.n_series()
547 };
548 let gg = self.group_gap.unwrap_or(1);
549 let bw = self.auto_thickness(plot.width, self.groups.len(), n, gg);
550 let group_w = bw * n as u16 + self.bar_gap * (n as u16 - 1);
551 let slot = (group_w + gg) as usize;
552 let visible = ((plot.width as usize + gg as usize) / slot).max(1);
553
554 let zc = Self::baseline(plot.height, lo, hi);
555 let pos_cells = plot.height - zc;
556 let (plo, phi) = if zc > 0 { (0.0, hi) } else { (lo, hi) };
557 let y_ticks: Vec<(u16, String)> = marks
558 .iter()
559 .map(|(f, l)| {
560 let df = Self::display_frac(*f, lo, hi, plot.height, zc);
561 (layout::frac_row(df, plot.height, 8), l.clone())
562 })
563 .collect();
564 if self.value_axis.grid {
565 let rows: Vec<u16> = y_ticks.iter().map(|t| t.0).collect();
566 layout::draw_grid(
567 buf,
568 plot,
569 &[],
570 &rows,
571 self.value_axis.grid_style,
572 self.value_axis.grid_kind,
573 );
574 }
575
576 let mut x_ticks = vec![];
577 for (gi, g) in self.groups.iter().take(visible).enumerate() {
578 let gx = plot.x + (gi * slot) as u16;
579 if gx + group_w > plot.right() {
580 break;
581 }
582 x_ticks.push((gx - plot.x + group_w / 2, g.label.clone()));
583 let eighths = self.eighths_for(g, plo, phi, pos_cells);
584 let negs = self.neg_eighths(g, lo, zc);
585 let bars = if self.mode == BarMode::Stacked {
586 1
587 } else {
588 g.values.len()
589 };
590 for bi in 0..bars {
591 let x = gx + bi as u16 * (bw + self.bar_gap);
592 self.draw_neg_vertical(buf, plot, g, &negs, bi, x, bw, zc);
593 let total = if self.mode == BarMode::Stacked {
594 eighths.last().copied().unwrap_or(0)
595 } else {
596 eighths[bi]
597 };
598 self.record_hits(g, gi, bi, &eighths, &negs, |a, b| {
599 let top = i32::from(plot.bottom()) - i32::from(zc) - b;
600 Rect::new(x, top.max(i32::from(plot.y)) as u16, bw, (b - a) as u16)
601 .intersection(plot)
602 });
603 for r in 0..pos_cells as i32 {
604 let fill = (total - r * 8).clamp(0, 8) as usize;
605 if fill == 0 {
606 break;
607 }
608 let color = if self.mode == BarMode::Stacked {
609 let p = r * 8 + fill as i32 - 1;
610 let k = eighths
611 .iter()
612 .position(|&c| p < c)
613 .unwrap_or(eighths.len() - 1);
614 self.color_for_cell(
615 g,
616 k,
617 (r * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0),
618 )
619 } else {
620 self.color_for_cell(
621 g,
622 bi,
623 (r * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0),
624 )
625 };
626 let y = plot.bottom() - 1 - zc - r as u16;
627 if let Some(m) = self.marker {
628 Self::dot_cell(buf, m, (x, y, bw), fill, true, color);
629 continue;
630 }
631 for dx in 0..bw {
632 buf.set_string(
633 x + dx,
634 y,
635 BOTTOM_EIGHTHS[fill].to_string(),
636 Style::default().fg(color),
637 );
638 }
639 }
640 if self.show_values && total > 0 {
641 let value = if self.mode == BarMode::Stacked {
642 self.group_total(g)
643 } else {
644 g.values[bi]
645 };
646 let text = self.format_value(value);
647 let tw = text_width(&text);
648 let top_cells = (total + 7) / 8;
649 if self.label_position == LabelPosition::Inside {
650 if top_cells >= 1 && tw <= bw {
651 let y = plot.bottom() - zc - top_cells as u16;
652 let tx = x + (bw - tw) / 2;
653 let c = if self.mode == BarMode::Stacked {
654 self.color_for(g, g.values.len().saturating_sub(1))
655 } else {
656 self.color_for(g, bi)
657 };
658 buf.set_string(tx, y, text, Style::default().fg(Color::Black).bg(c));
659 }
660 } else if top_cells < pos_cells as i32 && tw <= bw + 1 + self.bar_gap {
661 let y = plot.bottom() - 1 - zc - top_cells as u16;
662 let tx = (x + bw / 2).saturating_sub(tw / 2).max(plot.x);
663 let tx = tx.min(plot.right().saturating_sub(tw));
664 buf.set_string(tx, y, text, Style::default().fg(self.label_color()));
665 }
666 }
667 }
668 }
669
670 layout::draw_axes(buf, &a, self.category_axis.style, self.value_axis.style);
671 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.value_axis.label_style);
672 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.category_axis.label_style);
673 layout::draw_titles(
674 buf,
675 inner,
676 &a,
677 self.category_axis
678 .title
679 .as_deref()
680 .map(|t| (t, self.category_axis.label_style)),
681 self.value_axis
682 .title
683 .as_deref()
684 .map(|t| (t, self.value_axis.label_style)),
685 );
686 self.draw_legend(buf, plot);
687 }
688
689 fn render_horizontal(&self, inner: Rect, buf: &mut Buffer) {
690 let (lo, hi) = self.bounds();
691 if hi <= lo {
692 return;
693 }
694 let marks = self.value_axis.tick_marks((lo, hi));
695 let yw = self
696 .groups
697 .iter()
698 .map(|g| text_width(&g.label))
699 .max()
700 .unwrap_or(0)
701 .min(16);
702 let Some(a) = layout::compute(
703 inner,
704 yw,
705 !marks.is_empty(),
706 self.value_axis.title.is_some(),
707 self.category_axis.title.is_some(),
708 ) else {
709 return;
710 };
711 let plot = a.plot;
712 let n = if self.mode == BarMode::Stacked {
713 1
714 } else {
715 self.n_series()
716 };
717 let gg = self
718 .group_gap
719 .unwrap_or(if plot.height as usize >= self.groups.len() * (n + 1) {
720 1
721 } else {
722 0
723 });
724 let bh = self.auto_thickness(plot.height, self.groups.len(), n, gg);
725 let group_h = bh * n as u16 + self.bar_gap * (n as u16 - 1);
726 let slot = (group_h + gg) as usize;
727 let visible = ((plot.height as usize + gg as usize) / slot).max(1);
728
729 let zc = Self::baseline(plot.width, lo, hi);
730 let pos_cells = plot.width - zc;
731 let (plo, phi) = if zc > 0 { (0.0, hi) } else { (lo, hi) };
732 let x_ticks: Vec<(u16, String)> = marks
733 .iter()
734 .map(|(f, l)| {
735 let df = Self::display_frac(*f, lo, hi, plot.width, zc);
736 (layout::frac_col(df, plot.width, 1), l.clone())
737 })
738 .collect();
739 if self.value_axis.grid {
740 let cols: Vec<u16> = x_ticks.iter().map(|t| t.0).collect();
741 layout::draw_grid(
742 buf,
743 plot,
744 &cols,
745 &[],
746 self.value_axis.grid_style,
747 self.value_axis.grid_kind,
748 );
749 }
750
751 let mut y_ticks = vec![];
752 for (gi, g) in self.groups.iter().take(visible).enumerate() {
753 let gy = plot.y + (gi * slot) as u16;
754 if gy + group_h > plot.bottom() {
755 break;
756 }
757 let label: String = g.label.chars().take(yw as usize).collect();
758 y_ticks.push((gy - plot.y + group_h / 2, label));
759 let eighths = self.eighths_for(g, plo, phi, pos_cells);
760 let negs = self.neg_eighths(g, lo, zc);
761 let bars = if self.mode == BarMode::Stacked {
762 1
763 } else {
764 g.values.len()
765 };
766 for bi in 0..bars {
767 let y = gy + bi as u16 * (bh + self.bar_gap);
768 self.draw_neg_horizontal(buf, plot, g, &negs, bi, y, bh, zc);
769 let total = if self.mode == BarMode::Stacked {
770 eighths.last().copied().unwrap_or(0)
771 } else {
772 eighths[bi]
773 };
774 self.record_hits(g, gi, bi, &eighths, &negs, |a, b| {
775 let left = i32::from(plot.x) + i32::from(zc) + a;
776 Rect::new(left.max(i32::from(plot.x)) as u16, y, (b - a) as u16, bh)
777 .intersection(plot)
778 });
779 for c in 0..pos_cells as i32 {
780 let fill = (total - c * 8).clamp(0, 8) as usize;
781 if fill == 0 {
782 break;
783 }
784 let frac = (c * 8 + fill as i32) as f64 / (pos_cells as f64 * 8.0);
785 let color = if self.mode == BarMode::Stacked {
786 let p = c * 8 + fill as i32 - 1;
787 let k = eighths
788 .iter()
789 .position(|&e| p < e)
790 .unwrap_or(eighths.len() - 1);
791 self.color_for_cell(g, k, frac)
792 } else {
793 self.color_for_cell(g, bi, frac)
794 };
795 if let Some(m) = self.marker {
796 for dy in 0..bh {
797 let cx = plot.x + zc + c as u16;
798 Self::dot_cell(buf, m, (cx, y + dy, 1), fill, false, color);
799 }
800 continue;
801 }
802 for dy in 0..bh {
803 buf.set_string(
804 plot.x + zc + c as u16,
805 y + dy,
806 LEFT_EIGHTHS[fill].to_string(),
807 Style::default().fg(color),
808 );
809 }
810 }
811 if self.show_values && total > 0 {
812 let value = if self.mode == BarMode::Stacked {
813 self.group_total(g)
814 } else {
815 g.values[bi]
816 };
817 let text = self.format_value(value);
818 let tw = text_width(&text);
819 let end = ((total + 7) / 8) as u16;
820 if self.label_position == LabelPosition::Inside {
821 if end >= tw {
822 let c = if self.mode == BarMode::Stacked {
823 self.color_for(g, g.values.len().saturating_sub(1))
824 } else {
825 self.color_for(g, bi)
826 };
827 buf.set_string(
828 plot.x + zc + end - tw,
829 y + bh / 2,
830 text,
831 Style::default().fg(Color::Black).bg(c),
832 );
833 }
834 } else if zc + end + 1 + tw <= plot.width {
835 buf.set_string(
836 plot.x + zc + end + 1,
837 y + bh / 2,
838 text,
839 Style::default().fg(self.label_color()),
840 );
841 }
842 }
843 }
844 }
845
846 layout::draw_axes(buf, &a, self.value_axis.style, self.category_axis.style);
847 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.category_axis.label_style);
848 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.value_axis.label_style);
849 layout::draw_titles(
850 buf,
851 inner,
852 &a,
853 self.value_axis
854 .title
855 .as_deref()
856 .map(|t| (t, self.value_axis.label_style)),
857 self.category_axis
858 .title
859 .as_deref()
860 .map(|t| (t, self.category_axis.label_style)),
861 );
862 self.draw_legend(buf, plot);
863 }
864
865 fn color_for_cell(&self, g: &BarGroup, i: usize, frac: f64) -> Color {
868 let explicit = g.bar_colors.get(i).copied().flatten();
869 match (&self.gradient, explicit) {
870 (_, Some(c)) => c,
871 (Some(grad), None) => grad.color_at(frac),
872 (None, None) => self.color(i),
873 }
874 }
875
876 #[allow(clippy::too_many_arguments)]
878 fn draw_neg_vertical(
879 &self,
880 buf: &mut Buffer,
881 plot: Rect,
882 g: &BarGroup,
883 negs: &[i32],
884 bi: usize,
885 x: u16,
886 bw: u16,
887 zc: u16,
888 ) {
889 if zc == 0 {
890 return;
891 }
892 let total = if self.mode == BarMode::Stacked {
893 negs.last().copied().unwrap_or(0)
894 } else {
895 negs[bi]
896 };
897 if total <= 0 {
898 return;
899 }
900 let rows = (total + 7) / 8;
901 for r in 0..rows.min(zc as i32) {
902 let rem = (total - r * 8).clamp(0, 8);
903 let sym = match rem {
904 6..=8 => '█',
905 3..=5 => '▀',
906 _ => '▔',
907 };
908 let k = if self.mode == BarMode::Stacked {
909 let p = r * 8 + rem - 1;
910 negs.iter().position(|&c| p < c).unwrap_or(negs.len() - 1)
911 } else {
912 bi
913 };
914 let color = self.color_for_cell(g, k, 0.0);
915 let y = plot.bottom() - zc + r as u16;
916 if y >= plot.bottom() {
917 break;
918 }
919 for dx in 0..bw {
920 buf.set_string(x + dx, y, sym.to_string(), Style::default().fg(color));
921 }
922 }
923 if self.show_values {
924 let value = if self.mode == BarMode::Stacked {
925 -g.values.iter().map(|&v| Self::neg(v)).sum::<f64>()
926 } else {
927 g.values[bi]
928 };
929 let text = self.format_value(value);
930 let tw = text_width(&text);
931 let y = plot.bottom() - zc + rows as u16;
932 if y < plot.bottom() && tw <= bw + 1 + self.bar_gap {
933 let tx = (x + bw / 2).saturating_sub(tw / 2).max(plot.x);
934 let tx = tx.min(plot.right().saturating_sub(tw));
935 buf.set_string(tx, y, text, Style::default().fg(self.label_color()));
936 }
937 }
938 }
939
940 #[allow(clippy::too_many_arguments)]
942 fn draw_neg_horizontal(
943 &self,
944 buf: &mut Buffer,
945 plot: Rect,
946 g: &BarGroup,
947 negs: &[i32],
948 bi: usize,
949 y: u16,
950 bh: u16,
951 zc: u16,
952 ) {
953 if zc == 0 {
954 return;
955 }
956 let total = if self.mode == BarMode::Stacked {
957 negs.last().copied().unwrap_or(0)
958 } else {
959 negs[bi]
960 };
961 if total <= 0 {
962 return;
963 }
964 let cols = (total + 7) / 8;
965 for c in 0..cols.min(zc as i32) {
966 let rem = (total - c * 8).clamp(0, 8);
967 let sym = match rem {
968 6..=8 => '█',
969 3..=5 => '▐',
970 _ => '▕',
971 };
972 let k = if self.mode == BarMode::Stacked {
973 let p = c * 8 + rem - 1;
974 negs.iter().position(|&e| p < e).unwrap_or(negs.len() - 1)
975 } else {
976 bi
977 };
978 let color = self.color_for_cell(g, k, 0.0);
979 let x = plot.x + zc - 1 - c as u16;
980 for dy in 0..bh {
981 buf.set_string(x, y + dy, sym.to_string(), Style::default().fg(color));
982 }
983 }
984 if self.show_values {
985 let value = if self.mode == BarMode::Stacked {
986 -g.values.iter().map(|&v| Self::neg(v)).sum::<f64>()
987 } else {
988 g.values[bi]
989 };
990 let text = self.format_value(value);
991 let tw = text_width(&text);
992 let tip = zc as i32 - cols;
993 if tip - 1 - tw as i32 >= 0 {
994 buf.set_string(
995 plot.x + (tip - 1) as u16 - tw,
996 y + bh / 2,
997 text,
998 Style::default().fg(self.label_color()),
999 );
1000 }
1001 }
1002 }
1003
1004 fn record_hits(
1007 &self,
1008 g: &BarGroup,
1009 gi: usize,
1010 bi: usize,
1011 eighths: &[i32],
1012 negs: &[i32],
1013 span: impl Fn(i32, i32) -> Rect,
1014 ) {
1015 if !interact::recording() {
1016 return;
1017 }
1018 let tip = |k: usize| {
1019 let name = self
1020 .series_names
1021 .get(k)
1022 .cloned()
1023 .unwrap_or_else(|| format!("series {}", k + 1));
1024 let mut lines = vec![format!(
1025 "{}: {}",
1026 name,
1027 self.format_value(g.values.get(k).copied().unwrap_or(0.0))
1028 )];
1029 if self.mode == BarMode::Stacked {
1030 lines.push(format!("total: {}", self.format_value(self.group_total(g))));
1031 }
1032 (g.label.clone(), lines)
1033 };
1034 let cells = |e: i32| (e + 7) / 8;
1035 if self.mode == BarMode::Stacked {
1036 let mut prev = 0;
1037 for (k, &cur) in eighths.iter().enumerate() {
1038 let (a, b) = (prev / 8, cells(cur));
1039 prev = cur;
1040 if b > a {
1041 interact::record_point(span(a, b), k, gi, || tip(k));
1042 }
1043 }
1044 } else {
1045 let a = -cells(negs.get(bi).copied().unwrap_or(0));
1046 let mut b = cells(eighths.get(bi).copied().unwrap_or(0));
1047 if b <= a {
1048 b = a + 1;
1049 }
1050 interact::record_point(span(a, b), bi, gi, || tip(bi));
1051 }
1052 }
1053
1054 fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
1055 let w = self
1056 .series_names
1057 .iter()
1058 .map(|n| text_width(n) + 2)
1059 .max()
1060 .unwrap_or(0);
1061 if w == 0 || w > plot.width {
1062 return;
1063 }
1064 for (i, name) in self.series_names.iter().enumerate() {
1065 if i as u16 >= plot.height {
1066 break;
1067 }
1068 let y = plot.y + i as u16;
1069 for x in plot.right() - w..plot.right() {
1071 buf.set_string(x, y, " ", Style::default());
1072 }
1073 let off = self.hidden_legend.contains(&i);
1074 let mut text = Style::default().fg(self.label_color());
1075 if off {
1076 text = text.add_modifier(
1077 ratatui::style::Modifier::CROSSED_OUT | ratatui::style::Modifier::DIM,
1078 );
1079 }
1080 buf.set_string(
1081 plot.right() - w,
1082 y,
1083 if off { "□" } else { "■" },
1084 Style::default().fg(self.color(i)),
1085 );
1086 buf.set_string(plot.right() - w + 2, y, name, text);
1087 interact::record_legend(Rect::new(plot.right() - w, y, w, 1), i, name);
1088 }
1089 }
1090}
1091
1092widget_impls!(BarChart);
1093
1094#[cfg(feature = "theme")]
1095impl tui_nuances::Themed for BarChart {
1096 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
1097 self.theme(theme)
1098 }
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104 use ratatui::widgets::Widget;
1105
1106 fn groups() -> Vec<BarGroup> {
1107 vec![
1108 BarGroup::new("Q1", [10.0, 20.0]),
1109 BarGroup::new("Q2", [30.0, 5.0]),
1110 BarGroup::new("Q3", [25.0, 15.0]),
1111 ]
1112 }
1113
1114 fn dump(buf: &Buffer, area: Rect) -> String {
1115 (area.y..area.bottom())
1116 .flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
1117 .map(|p| buf[p].symbol().to_string())
1118 .collect()
1119 }
1120
1121 #[test]
1122 fn bounds_grouped_vs_stacked() {
1123 let g = BarChart::new(groups());
1124 assert_eq!(g.bounds(), (0.0, 30.0));
1125 let s = BarChart::new(groups()).mode(BarMode::Stacked);
1126 assert_eq!(s.bounds().1, 40.0);
1127 assert_eq!(BarChart::new(groups()).max(100.0).bounds().1, 100.0);
1128 assert_eq!(BarChart::new(vec![]).bounds(), (0.0, 1.0));
1129 }
1130
1131 #[test]
1132 fn negative_and_nan_values_clamped() {
1133 let c = BarChart::new(vec![BarGroup::new("a", [f64::NAN, 3.0])]);
1134 assert_eq!(c.bounds().1, 3.0);
1135 let n = BarChart::new(vec![BarGroup::new("a", [-5.0, f64::NAN, 3.0])]);
1136 assert!(n.bounds().0 <= -5.0);
1137 }
1138
1139 #[test]
1140 fn vertical_grouped_draws_colors() {
1141 let area = Rect::new(0, 0, 40, 14);
1142 let mut buf = Buffer::empty(area);
1143 BarChart::new(groups())
1144 .colors(vec![Color::Red, Color::Blue])
1145 .render(area, &mut buf);
1146 let fg: Vec<Color> = (0..40)
1147 .flat_map(|x| (0..14).map(move |y| (x, y)))
1148 .filter(|p| buf[*p].symbol() == "█")
1149 .map(|p| buf[p].fg)
1150 .collect();
1151 assert!(fg.contains(&Color::Red));
1152 assert!(fg.contains(&Color::Blue));
1153 assert!(dump(&buf, area).contains("Q1"));
1154 }
1155
1156 #[test]
1157 fn vertical_stacked_uses_segment_colors() {
1158 let area = Rect::new(0, 0, 40, 14);
1159 let mut buf = Buffer::empty(area);
1160 BarChart::new(groups())
1161 .mode(BarMode::Stacked)
1162 .colors(vec![Color::Red, Color::Blue])
1163 .render(area, &mut buf);
1164 let fg: Vec<Color> = (0..40)
1165 .flat_map(|x| (0..14).map(move |y| (x, y)))
1166 .filter(|p| matches!(buf[*p].symbol(), "█" | "▄" | "▅" | "▆" | "▇"))
1167 .map(|p| buf[p].fg)
1168 .collect();
1169 assert!(fg.contains(&Color::Red) && fg.contains(&Color::Blue));
1170 }
1171
1172 #[test]
1173 fn horizontal_draws_partial_blocks_and_values() {
1174 let area = Rect::new(0, 0, 40, 12);
1175 let mut buf = Buffer::empty(area);
1176 BarChart::new(groups())
1177 .orientation(BarOrientation::Horizontal)
1178 .show_values(true)
1179 .render(area, &mut buf);
1180 let t = dump(&buf, area);
1181 assert!(t.contains('█'));
1182 assert!(t.contains("Q3"));
1183 assert!(t.contains("25"));
1184 }
1185
1186 #[test]
1187 fn horizontal_stacked() {
1188 let area = Rect::new(0, 0, 40, 12);
1189 let mut buf = Buffer::empty(area);
1190 BarChart::new(groups())
1191 .orientation(BarOrientation::Horizontal)
1192 .mode(BarMode::Stacked)
1193 .series_names(["a", "b"])
1194 .render(area, &mut buf);
1195 assert!(dump(&buf, area).contains('■'));
1196 }
1197
1198 #[test]
1199 fn value_labels_vertical() {
1200 let area = Rect::new(0, 0, 40, 14);
1201 let mut buf = Buffer::empty(area);
1202 BarChart::new(groups())
1203 .bar_width(3)
1204 .show_values(true)
1205 .render(area, &mut buf);
1206 let t = dump(&buf, area);
1207 assert!(t.contains("10") || t.contains("20"));
1208 }
1209
1210 #[test]
1211 fn many_groups_are_truncated_not_panicking() {
1212 let g: Vec<BarGroup> = (0..100)
1213 .map(|i| BarGroup::new(format!("{i}"), [i as f64]))
1214 .collect();
1215 let area = Rect::new(0, 0, 30, 10);
1216 let mut buf = Buffer::empty(area);
1217 BarChart::new(g.clone()).render(area, &mut buf);
1218 BarChart::new(g)
1219 .orientation(BarOrientation::Horizontal)
1220 .render(area, &mut buf);
1221 }
1222
1223 #[test]
1224 fn tiny_and_empty_safe() {
1225 for (w, h) in [(0, 0), (2, 2), (8, 4), (10, 5)] {
1226 let area = Rect::new(0, 0, w, h);
1227 let mut buf = Buffer::empty(area);
1228 BarChart::new(groups()).render(area, &mut buf);
1229 BarChart::new(vec![]).render(area, &mut buf);
1230 BarChart::new(groups())
1231 .orientation(BarOrientation::Horizontal)
1232 .render(area, &mut buf);
1233 }
1234 }
1235
1236 #[test]
1237 fn group_helper() {
1238 let g = BarGroup::new("x", [1.0, 2.0]);
1239 assert_eq!(g.label, "x");
1240 assert_eq!(g.values, vec![1.0, 2.0]);
1241 }
1242
1243 #[test]
1244 fn interaction_hits_for_all_modes_and_hidden() {
1245 use crate::{HitKind, HitMap};
1246 let groups = || {
1247 vec![
1248 BarGroup::new("a", [3.0, 2.0]),
1249 BarGroup::new("b", [-1.0, 5.0]),
1250 ]
1251 };
1252 let area = Rect::new(0, 0, 40, 14);
1253 for orient in [BarOrientation::Vertical, BarOrientation::Horizontal] {
1254 for mode in [BarMode::Grouped, BarMode::Stacked] {
1255 let chart = || {
1256 BarChart::new(groups())
1257 .series_names(["x", "y"])
1258 .orientation(orient)
1259 .mode(mode)
1260 };
1261 let mut buf = Buffer::empty(area);
1262 let hits = HitMap::capture(chart(), area, &mut buf);
1263 let pts: Vec<_> = hits
1264 .hits()
1265 .iter()
1266 .filter(|h| h.kind == HitKind::Point)
1267 .collect();
1268 assert!(pts.len() >= 3, "{orient:?} {mode:?}: {}", pts.len());
1269 assert!(pts.iter().all(|h| h.rect.right() <= area.right()));
1270 assert!(
1271 pts.iter()
1272 .any(|h| h.title == "b" && h.lines[0].contains("y: 5"))
1273 );
1274 let mut buf = Buffer::empty(area);
1275 let hidden = HitMap::capture(chart().hidden([1]), area, &mut buf);
1276 assert!(
1277 hidden
1278 .hits()
1279 .iter()
1280 .any(|h| h.kind == HitKind::Legend && h.series == 1)
1281 );
1282 }
1283 }
1284 }
1285}