Skip to content

Commit

Permalink
fix(widgets/chart): remove overflow when dataset if empty (fdehau#274)
Browse files Browse the repository at this point in the history
* docs: Fix missing code block fence
* use slice::windows to deal with underflow issue
* add test for empty dataset and lines
  • Loading branch information
ClementTsang authored and 24seconds committed Nov 30, 2020
1 parent 75185dd commit e4bd05f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
11 changes: 6 additions & 5 deletions src/widgets/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ where
/// // or if its height is greater than 25% of the total widget height.
/// let _chart: Chart<String, String> = Chart::default()
/// .hidden_legend_constraints(constraints);
/// ```
pub fn hidden_legend_constraints(
mut self,
constraints: (Constraint, Constraint),
Expand Down Expand Up @@ -499,12 +500,12 @@ where
color: dataset.style.fg,
});
if let GraphType::Line = dataset.graph_type {
for i in 0..dataset.data.len() - 1 {
for data in dataset.data.windows(2) {
ctx.draw(&Line {
x1: dataset.data[i].0,
y1: dataset.data[i].1,
x2: dataset.data[i + 1].0,
y2: dataset.data[i + 1].1,
x1: data[0].0,
y1: data[0].1,
x2: data[1].0,
y2: data[1].1,
color: dataset.style.fg,
})
}
Expand Down
32 changes: 31 additions & 1 deletion tests/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use tui::{
layout::Rect,
style::{Color, Style},
symbols,
widgets::{Axis, Block, Borders, Chart, Dataset},
widgets::{Axis, Block, Borders, Chart, Dataset, GraphType::Line},
Terminal,
};

Expand Down Expand Up @@ -72,3 +72,33 @@ fn handles_overflow() {
})
.unwrap();
}

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

terminal
.draw(|mut f| {
let datasets = [Dataset::default().data(&[]).graph_type(Line)];
let chart = Chart::default()
.block(
Block::default()
.title("Empty Dataset With Line")
.borders(Borders::ALL),
)
.x_axis(Axis::default().bounds([0.0, 0.0]).labels(&["0.0", "1.0"]))
.y_axis(Axis::default().bounds([0.0, 1.0]).labels(&["0.0", "1.0"]))
.datasets(&datasets);
f.render_widget(
chart,
Rect {
x: 0,
y: 0,
width: 100,
height: 100,
},
);
})
.unwrap();
}

0 comments on commit e4bd05f

Please sign in to comment.