use tuirealm::props::{LineStatic, Style};
use tuirealm::ratatui::symbols::Marker;
use tuirealm::ratatui::widgets::{Dataset as TuiDataset, GraphType};
#[derive(Clone, Debug)]
pub struct ChartDataset {
pub name: LineStatic,
pub marker: Marker,
pub graph_type: GraphType,
pub style: Style,
data: Vec<(f64, f64)>,
}
impl Default for ChartDataset {
fn default() -> Self {
Self {
name: LineStatic::default(),
marker: Marker::Dot,
graph_type: GraphType::Scatter,
style: Style::default(),
data: Vec::default(),
}
}
}
impl ChartDataset {
pub fn name<S: Into<LineStatic>>(mut self, name: S) -> Self {
self.name = name.into();
self
}
pub fn marker(mut self, m: Marker) -> Self {
self.marker = m;
self
}
pub fn graph_type(mut self, g: GraphType) -> Self {
self.graph_type = g;
self
}
pub fn style(mut self, s: Style) -> Self {
self.style = s;
self
}
pub fn data(mut self, data: Vec<(f64, f64)>) -> Self {
self.data = data;
self
}
pub fn push(&mut self, point: (f64, f64)) {
self.data.push(point);
}
pub fn pop(&mut self) {
self.data.pop();
}
pub fn pop_front(&mut self) {
if !self.data.is_empty() {
self.data.remove(0);
}
}
pub fn get_data(&self) -> &[(f64, f64)] {
&self.data
}
pub fn as_tuichart<'a>(&'a self, start: usize) -> TuiDataset<'a> {
TuiDataset::default()
.name(self.name.clone())
.marker(self.marker)
.graph_type(self.graph_type)
.style(self.style)
.data(&self.get_data()[start..])
}
}
impl PartialEq for ChartDataset {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.data == other.data
}
}
impl<'a> From<&'a ChartDataset> for TuiDataset<'a> {
fn from(data: &'a ChartDataset) -> TuiDataset<'a> {
data.as_tuichart(0)
}
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use tuirealm::ratatui::style::Color;
use super::*;
#[test]
fn dataset() {
let mut dataset: ChartDataset = ChartDataset::default()
.name("Avg temperatures")
.graph_type(GraphType::Scatter)
.marker(Marker::Braille)
.style(Style::default().fg(Color::Cyan))
.data(vec![
(0.0, -1.0),
(1.0, 1.0),
(2.0, 3.0),
(3.0, 7.0),
(4.0, 11.0),
(5.0, 15.0),
(6.0, 17.0),
(7.0, 17.0),
(8.0, 13.0),
(9.0, 9.0),
(10.0, 4.0),
(11.0, 0.0),
]);
assert_eq!(dataset.name.to_string(), "Avg temperatures");
assert_eq!(dataset.style.fg.unwrap_or(Color::Reset), Color::Cyan);
assert_eq!(dataset.get_data().len(), 12);
dataset.push((12.0, 1.0));
assert_eq!(dataset.get_data().len(), 13);
dataset.pop();
assert_eq!(dataset.get_data().len(), 12);
dataset.pop_front();
assert_eq!(dataset.get_data().len(), 11);
let _: TuiDataset = TuiDataset::from(&dataset);
}
}