Skip to content

Commit

Permalink
fix(chart): use graph style for top line (#462)
Browse files Browse the repository at this point in the history
A bug in the rendering caused the top line of the chart to be rendered
using the style of the chart, instead of the dataset style. This is
fixed by only setting the style for the width of the text, and not the
entire row.

Fixes: #379
  • Loading branch information
aatukaj authored Sep 5, 2023
1 parent 572df75 commit c8ab2d5
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/widgets/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ impl<'a> Widget for Chart<'a> {

if let Some((x, y)) = layout.title_x {
let title = self.x_axis.title.unwrap();
let width = graph_area.right().saturating_sub(x);
let width = title.width() as u16;
buf.set_style(
Rect {
x,
Expand All @@ -575,7 +575,7 @@ impl<'a> Widget for Chart<'a> {

if let Some((x, y)) = layout.title_y {
let title = self.y_axis.title.unwrap();
let width = graph_area.right().saturating_sub(x);
let width = title.width() as u16;
buf.set_style(
Rect {
x,
Expand Down Expand Up @@ -718,4 +718,15 @@ mod tests {
assert_eq!("Line".parse::<GraphType>(), Ok(GraphType::Line));
assert_eq!("".parse::<GraphType>(), Err(ParseError::VariantNotFound));
}

#[test]
fn it_does_not_panic_if_title_is_wider_than_buffer() {
let widget = Chart::default()
.y_axis(Axis::default().title("xxxxxxxxxxxxxxxx"))
.x_axis(Axis::default().title("xxxxxxxxxxxxxxxx"));
let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 4));
widget.render(buffer.area, &mut buffer);

assert_eq!(buffer, Buffer::with_lines(vec![" ".repeat(8); 4]))
}
}
38 changes: 38 additions & 0 deletions tests/widgets_chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,41 @@ fn widgets_chart_can_have_a_legend() {

terminal.backend().assert_buffer(&expected);
}

#[test]
fn widgets_chart_top_line_styling_is_correct() {
let backend = TestBackend::new(9, 5);
let mut terminal = Terminal::new(backend).unwrap();

let title_style = Style::default().fg(Color::Red).bg(Color::LightRed);
let data_style = Style::default().fg(Color::Blue);

terminal
.draw(|f| {
let data: [(f64, f64); 2] = [(0.0, 1.0), (1.0, 1.0)];
let widget = Chart::new(vec![Dataset::default()
.data(&data)
.graph_type(ratatui::widgets::GraphType::Line)
.style(data_style)])
.y_axis(
Axis::default()
.title(Span::styled("abc", title_style))
.bounds([0.0, 1.0])
.labels(create_labels(&["a", "b"])),
)
.x_axis(Axis::default().bounds([0.0, 1.0]));
f.render_widget(widget, f.size());
})
.unwrap();

let mut expected = Buffer::with_lines(vec![
"b│abc••••",
" │ ",
" │ ",
" │ ",
"a│ ",
]);
expected.set_style(Rect::new(2, 0, 3, 1), title_style);
expected.set_style(Rect::new(5, 0, 4, 1), data_style);
terminal.backend().assert_buffer(&expected);
}

0 comments on commit c8ab2d5

Please sign in to comment.