fix(widgets/chart): remove overflow when dataset if empty (#274)

* docs: Fix missing code block fence
* use slice::windows to deal with underflow issue
* add test for empty dataset and lines
This commit is contained in:
Clement Tsang 2020-05-10 17:48:12 -04:00 committed by GitHub
parent eb47c778db
commit b72ced4511
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 6 deletions

View file

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

View file

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