fix(barchart): render value labels with unicode correctly (#515)

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>
This commit is contained in:
Hichem 2023-09-20 03:06:32 +02:00 committed by GitHub
parent 5498a889ae
commit c9b8e7cf41
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View file

@ -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);
}
}

View file

@ -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.
@ -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),