Skip to content

Commit

Permalink
fix(barchart): render value labels with unicode correctly (#515)
Browse files Browse the repository at this point in the history
An earlier change introduced a bug where the width of value labels with
unicode characters was incorrectly using the string length in bytes
instead of the unicode character count. This reverts the earlier change.

Signed-off-by: Ben Fekih, Hichem <hichem.f@live.de>
  • Loading branch information
karthago1 committed Sep 20, 2023
1 parent 5498a88 commit c9b8e7c
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 c9b8e7c

Please sign in to comment.