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. /// // or if its height is greater than 25% of the total widget height.
/// let _chart: Chart<String, String> = Chart::default() /// let _chart: Chart<String, String> = Chart::default()
/// .hidden_legend_constraints(constraints); /// .hidden_legend_constraints(constraints);
/// ```
pub fn hidden_legend_constraints( pub fn hidden_legend_constraints(
mut self, mut self,
constraints: (Constraint, Constraint), constraints: (Constraint, Constraint),
@ -499,12 +500,12 @@ where
color: dataset.style.fg, color: dataset.style.fg,
}); });
if let GraphType::Line = dataset.graph_type { 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 { ctx.draw(&Line {
x1: dataset.data[i].0, x1: data[0].0,
y1: dataset.data[i].1, y1: data[0].1,
x2: dataset.data[i + 1].0, x2: data[1].0,
y2: dataset.data[i + 1].1, y2: data[1].1,
color: dataset.style.fg, color: dataset.style.fg,
}) })
} }

View File

@ -3,7 +3,7 @@ use tui::{
layout::Rect, layout::Rect,
style::{Color, Style}, style::{Color, Style},
symbols, symbols,
widgets::{Axis, Block, Borders, Chart, Dataset}, widgets::{Axis, Block, Borders, Chart, Dataset, GraphType::Line},
Terminal, Terminal,
}; };
@ -72,3 +72,33 @@ fn handles_overflow() {
}) })
.unwrap(); .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();
}