Skip to content

Commit

Permalink
fix(barchart): use width() instead of len() to get unicode string length
Browse files Browse the repository at this point in the history
value_label.len() deliver byte length of the unicode strings, which are
not printed as a result.

use witdh() instead.

Signed-off-by: Ben Fekih, Hichem <hichem.f@live.de>
  • Loading branch information
karthago1 committed Sep 19, 2023
1 parent dd9a8df commit 15f63ef
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/widgets/barchart.rs
Expand Up @@ -1149,4 +1149,35 @@ mod tests {
let expected = Buffer::with_lines(vec![" █", "▆ █", " G"]);
assert_buffer_eq!(buffer, expected);
}

#[test]
fn test_unicode_as_value() {
let group = BarGroup::default().bars(&[
Bar::default()
.value(123)
.label("B1".into())
.text_value("写".into()),
Bar::default()
.value(321)
.label("B2".into())
.text_value("写".into()),
Bar::default()
.value(333)
.label("B2".into())
.text_value("写".into()),
]);
let chart = BarChart::default().data(group).bar_width(3).bar_gap(1);

let mut buffer = Buffer::empty(Rect::new(0, 0, 11, 5));
chart.render(buffer.area, &mut buffer);

let expected = Buffer::with_lines(vec![
" ▆▆▆ ███",
" ███ ███",
"▃▃▃ ███ ███",
"写█ 写█ 写█",
"B1 B2 B2 ",
]);
assert_buffer_eq!(buffer, expected);
}
}
4 changes: 3 additions & 1 deletion src/widgets/barchart/bar.rs
@@ -1,3 +1,5 @@
use unicode_width::UnicodeWidthStr;

use crate::{buffer::Buffer, prelude::Rect, style::Style, text::Line};

/// A bar to be shown by the [`BarChart`](crate::widgets::BarChart) widget.
Expand Down Expand Up @@ -154,7 +156,7 @@ impl<'a> Bar<'a> {
self.value.to_string()
};

let width = value_label.len() as u16;
let width = value_label.width() as u16;
if width < max_width {
buf.set_string(
x + (max_width.saturating_sub(value_label.len() as u16) >> 1),
Expand Down

0 comments on commit 15f63ef

Please sign in to comment.