From fc727df7d2d8347434a7d3a4e19465b29d7a0ed8 Mon Sep 17 00:00:00 2001 From: Hichem Date: Sun, 27 Aug 2023 23:10:49 +0200 Subject: [PATCH] refactor(barchart): reduce some calculations (#430) Calculating the label_offset is unnecessary, if we just render the group label after rendering the bars. We can just reuse bar_y. Signed-off-by: Ben Fekih, Hichem --- src/widgets/barchart/mod.rs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/widgets/barchart/mod.rs b/src/widgets/barchart/mod.rs index 21dd091c..0739790a 100644 --- a/src/widgets/barchart/mod.rs +++ b/src/widgets/barchart/mod.rs @@ -156,7 +156,7 @@ impl<'a> BarChart<'a> { self } - /// set the direction ob the bars + /// Set the direction of the bars pub fn direction(mut self, direction: Direction) -> BarChart<'a> { self.direction = direction; self @@ -228,33 +228,23 @@ impl<'a> BarChart<'a> { }) .collect(); - // print all visible bars (without labels and values) + // print all visible bars let mut bar_y = bars_area.top(); for (group_data, mut group) in groups.into_iter().zip(self.data) { let bars = std::mem::take(&mut group.bars); - let label_offset = bars.len() as u16 * (self.bar_width + self.bar_gap) - self.bar_gap; - // if group_gap is zero, then there is no place to print the group label - // check also if the group label is still inside the visible area - if self.group_gap > 0 && bar_y < bars_area.bottom() - label_offset { - let label_rect = Rect { - y: bar_y + label_offset, - ..bars_area - }; - group.render_label(buf, label_rect, self.label_style); - } - for (bar_length, bar) in group_data.into_iter().zip(bars) { let bar_style = self.bar_style.patch(bar.style); for y in 0..self.bar_width { + let bar_y = bar_y + y; for x in 0..bars_area.width { let symbol = if x < bar_length { self.bar_set.full } else { self.bar_set.empty }; - buf.get_mut(bars_area.left() + x, bar_y + y) + buf.get_mut(bars_area.left() + x, bar_y) .set_symbol(symbol) .set_style(bar_style); } @@ -275,7 +265,17 @@ impl<'a> BarChart<'a> { bar_y += self.bar_gap + self.bar_width; } - bar_y += self.group_gap; + // if group_gap is zero, then there is no place to print the group label + // check also if the group label is still inside the visible area + let label_y = bar_y - self.bar_gap; + if self.group_gap > 0 && label_y < bars_area.bottom() { + let label_rect = Rect { + y: label_y, + ..bars_area + }; + group.render_label(buf, label_rect, self.label_style); + bar_y += self.group_gap; + } } }