Skip to content

Commit fc727df

Browse files
authored
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 <[email protected]>
1 parent 47fe4ad commit fc727df

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

src/widgets/barchart/mod.rs

+15-15
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ impl<'a> BarChart<'a> {
156156
self
157157
}
158158

159-
/// set the direction ob the bars
159+
/// Set the direction of the bars
160160
pub fn direction(mut self, direction: Direction) -> BarChart<'a> {
161161
self.direction = direction;
162162
self
@@ -228,33 +228,23 @@ impl<'a> BarChart<'a> {
228228
})
229229
.collect();
230230

231-
// print all visible bars (without labels and values)
231+
// print all visible bars
232232
let mut bar_y = bars_area.top();
233233
for (group_data, mut group) in groups.into_iter().zip(self.data) {
234234
let bars = std::mem::take(&mut group.bars);
235235

236-
let label_offset = bars.len() as u16 * (self.bar_width + self.bar_gap) - self.bar_gap;
237-
// if group_gap is zero, then there is no place to print the group label
238-
// check also if the group label is still inside the visible area
239-
if self.group_gap > 0 && bar_y < bars_area.bottom() - label_offset {
240-
let label_rect = Rect {
241-
y: bar_y + label_offset,
242-
..bars_area
243-
};
244-
group.render_label(buf, label_rect, self.label_style);
245-
}
246-
247236
for (bar_length, bar) in group_data.into_iter().zip(bars) {
248237
let bar_style = self.bar_style.patch(bar.style);
249238

250239
for y in 0..self.bar_width {
240+
let bar_y = bar_y + y;
251241
for x in 0..bars_area.width {
252242
let symbol = if x < bar_length {
253243
self.bar_set.full
254244
} else {
255245
self.bar_set.empty
256246
};
257-
buf.get_mut(bars_area.left() + x, bar_y + y)
247+
buf.get_mut(bars_area.left() + x, bar_y)
258248
.set_symbol(symbol)
259249
.set_style(bar_style);
260250
}
@@ -275,7 +265,17 @@ impl<'a> BarChart<'a> {
275265
bar_y += self.bar_gap + self.bar_width;
276266
}
277267

278-
bar_y += self.group_gap;
268+
// if group_gap is zero, then there is no place to print the group label
269+
// check also if the group label is still inside the visible area
270+
let label_y = bar_y - self.bar_gap;
271+
if self.group_gap > 0 && label_y < bars_area.bottom() {
272+
let label_rect = Rect {
273+
y: label_y,
274+
..bars_area
275+
};
276+
group.render_label(buf, label_rect, self.label_style);
277+
bar_y += self.group_gap;
278+
}
279279
}
280280
}
281281

0 commit comments

Comments
 (0)