Bar Chart baseline. (#2621)

Bar Chart ready.
This commit is contained in:
Andrés N. Robalino
2020-09-30 13:27:52 -05:00
committed by GitHub
parent 892a416211
commit a56abb6502
16 changed files with 803 additions and 136 deletions

View File

@ -0,0 +1,22 @@
[package]
authors = ["The Nu Project Contributors"]
description = "A plugin to display charts"
edition = "2018"
license = "MIT"
name = "nu_plugin_chart"
version = "0.20.0"
[lib]
doctest = false
[dependencies]
nu-data = {path = "../nu-data", version = "0.20.0"}
nu-errors = {path = "../nu-errors", version = "0.20.0"}
nu-plugin = {path = "../nu-plugin", version = "0.20.0"}
nu-protocol = {path = "../nu-protocol", version = "0.20.0"}
nu-source = {path = "../nu-source", version = "0.20.0"}
nu-cli = {path = "../nu-cli", version = "0.20.0"}
nu-value-ext = {path = "../nu-value-ext", version = "0.20.0"}
crossterm = "0.18"
tui = {version = "0.12.0", default-features = false, features = ["crossterm"]}

View File

@ -0,0 +1,155 @@
use nu_errors::ShellError;
use nu_protocol::Value;
use nu_source::Tagged;
use tui::{
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
widgets::{BarChart as TuiBarChart, Block, Borders},
};
pub enum Columns {
One(Tagged<String>),
Two(Tagged<String>, Tagged<String>),
None,
}
#[allow(clippy::type_complexity)]
pub struct Chart {
pub reduction: nu_data::utils::Reduction,
pub columns: Columns,
pub eval: Option<Box<dyn Fn(usize, &Value) -> Result<Value, ShellError> + Send>>,
pub format: Option<String>,
}
impl Default for Chart {
fn default() -> Self {
Self::new()
}
}
impl Chart {
pub fn new() -> Chart {
Chart {
reduction: nu_data::utils::Reduction::Count,
columns: Columns::None,
eval: None,
format: None,
}
}
}
pub struct BarChart<'a> {
pub title: &'a str,
pub data: Vec<(&'a str, u64)>,
pub enhanced_graphics: bool,
}
impl<'a> BarChart<'a> {
pub fn from_model(model: &'a nu_data::utils::Model) -> Result<BarChart<'a>, ShellError> {
let mut data = Vec::new();
let mut data_points = Vec::new();
for percentages in model
.percentages
.table_entries()
.cloned()
.collect::<Vec<_>>()
.into_iter()
{
let mut percentages_collected = vec![];
for percentage in percentages
.table_entries()
.cloned()
.collect::<Vec<_>>()
.into_iter()
{
percentages_collected.push(percentage.as_u64()?);
}
data_points.push(percentages_collected);
}
let mark_in = if model.labels.y.len() <= 1 {
0
} else {
(model.labels.y.len() as f64 / 2.0).floor() as usize
};
for idx in 0..model.labels.x.len() {
let mut current = 0;
loop {
let label = if current == mark_in {
model
.labels
.at(idx)
.ok_or_else(|| ShellError::untagged_runtime_error("Could not load data"))?
} else {
""
};
let percentages_collected = data_points
.get(current)
.ok_or_else(|| ShellError::untagged_runtime_error("Could not load data"))?;
data.push((
label,
*percentages_collected
.get(idx)
.ok_or_else(|| ShellError::untagged_runtime_error("Could not load data"))?,
));
current += 1;
if current == model.labels.y.len() {
break;
}
}
}
Ok(BarChart {
title: "Bar Chart",
data: (&data[..]).to_vec(),
enhanced_graphics: true,
})
}
pub fn draw<T>(&mut self, ui: &mut tui::Terminal<T>) -> std::io::Result<()>
where
T: tui::backend::Backend,
{
ui.draw(|f| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(2)
.constraints([Constraint::Percentage(100)].as_ref())
.split(f.size());
let barchart = TuiBarChart::default()
.block(Block::default().title("Chart").borders(Borders::ALL))
.data(&self.data)
.bar_width(9)
.bar_style(Style::default().fg(Color::Green))
.value_style(
Style::default()
.bg(Color::Green)
.add_modifier(Modifier::BOLD),
);
f.render_widget(barchart, chunks[0]);
})
}
pub fn on_right(&mut self) {
let one_bar = self.data.remove(0);
self.data.push(one_bar);
}
pub fn on_left(&mut self) {
if let Some(one_bar) = self.data.pop() {
self.data.insert(0, one_bar);
}
}
}

View File

@ -0,0 +1,4 @@
mod chart;
mod nu;
pub use chart::Chart;

View File

@ -0,0 +1,6 @@
use nu_plugin::serve_plugin;
use nu_plugin_chart::Chart;
fn main() {
serve_plugin(&mut Chart::new());
}

View File

@ -0,0 +1,330 @@
use nu_errors::ShellError;
use nu_plugin::Plugin;
use nu_protocol::{CallInfo, ColumnPath, Primitive, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::TaggedItem;
use nu_value_ext::ValueExt;
use crate::chart::{BarChart, Chart, Columns};
use std::{
error::Error,
io::{stdout, Write},
sync::mpsc,
thread,
time::{Duration, Instant},
};
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event as CEvent, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use tui::{backend::CrosstermBackend, Terminal};
enum Event<I> {
Input(I),
Tick,
}
fn display(model: &nu_data::utils::Model) -> Result<(), Box<dyn Error>> {
let mut app = BarChart::from_model(&model)?;
enable_raw_mode()?;
let mut stdout = stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let (tx, rx) = mpsc::channel();
let tick_rate = Duration::from_millis(250);
thread::spawn(move || {
let mut last_tick = Instant::now();
loop {
if event::poll(tick_rate - last_tick.elapsed()).is_ok() {
if let Ok(CEvent::Key(key)) = event::read() {
let _ = tx.send(Event::Input(key));
}
}
if last_tick.elapsed() >= tick_rate {
let _ = tx.send(Event::Tick);
last_tick = Instant::now();
}
}
});
terminal.clear()?;
loop {
app.draw(&mut terminal)?;
match rx.recv()? {
Event::Input(event) => match event.code {
KeyCode::Char('q') => {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
break;
}
KeyCode::Left => app.on_left(),
KeyCode::Right => app.on_right(),
_ => {}
},
Event::Tick => {}
}
}
Ok(())
}
impl Plugin for Chart {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("chart")
.desc("Displays bar charts")
.switch("acc", "accumuate values", Some('a'))
.optional(
"columns",
SyntaxShape::Any,
"the columns to chart [x-axis y-axis]",
)
.named(
"use",
SyntaxShape::ColumnPath,
"column to use for evaluation",
Some('u'),
)
.named(
"format",
SyntaxShape::String,
"Specify date and time formatting",
Some('f'),
))
}
fn sink(&mut self, call_info: CallInfo, input: Vec<Value>) {
if let Some(Value {
value: UntaggedValue::Primitive(Primitive::Boolean(true)),
..
}) = call_info.args.get("acc")
{
self.reduction = nu_data::utils::Reduction::Accumulate;
}
let _ = self.run(call_info, input);
}
}
impl Chart {
fn run(&mut self, call_info: CallInfo, input: Vec<Value>) -> Result<(), ShellError> {
let args = call_info.args;
let name = call_info.name_tag;
self.eval = if let Some(path) = args.get("use") {
Some(evaluator(path.as_column_path()?.item))
} else {
None
};
self.format = if let Some(fmt) = args.get("format") {
Some(fmt.as_string()?)
} else {
None
};
for arg in args.positional_iter() {
match arg {
Value {
value: UntaggedValue::Primitive(Primitive::String(column)),
tag,
} => {
let column = column.clone();
self.columns = Columns::One(column.tagged(tag));
}
Value {
value: UntaggedValue::Table(arguments),
tag,
} => {
if arguments.len() > 1 {
let col1 = arguments
.get(0)
.ok_or_else(|| {
ShellError::labeled_error(
"expected file and replace strings eg) [find replace]",
"missing find-replace values",
tag,
)
})?
.as_string()?
.tagged(tag);
let col2 = arguments
.get(1)
.ok_or_else(|| {
ShellError::labeled_error(
"expected file and replace strings eg) [find replace]",
"missing find-replace values",
tag,
)
})?
.as_string()?
.tagged(tag);
self.columns = Columns::Two(col1, col2);
} else {
let col1 = arguments
.get(0)
.ok_or_else(|| {
ShellError::labeled_error(
"expected file and replace strings eg) [find replace]",
"missing find-replace values",
tag,
)
})?
.as_string()?
.tagged(tag);
self.columns = Columns::One(col1);
}
}
_ => {}
}
}
let data = UntaggedValue::table(&input).into_value(&name);
match &self.columns {
Columns::Two(col1, col2) => {
let key = col1.clone();
let fmt = self.format.clone();
let grouper = Box::new(move |_: usize, row: &Value| {
let key = key.clone();
let fmt = fmt.clone();
match row.get_data_by_key(key.borrow_spanned()) {
Some(key) => {
if let Some(fmt) = fmt {
let callback = nu_data::utils::helpers::date_formatter(fmt);
callback(&key, "nothing".to_string())
} else {
nu_value_ext::as_string(&key)
}
}
None => Err(ShellError::labeled_error(
"unknown column",
"unknown column",
key.tag(),
)),
}
});
let key = col2.clone();
let splitter = Box::new(move |_: usize, row: &Value| {
let key = key.clone();
match row.get_data_by_key(key.borrow_spanned()) {
Some(key) => nu_value_ext::as_string(&key),
None => Err(ShellError::labeled_error(
"unknown column",
"unknown column",
key.tag(),
)),
}
});
let formatter = if self.format.is_some() {
let default = String::from("%b-%Y");
let string_fmt = self.format.as_ref().unwrap_or_else(|| &default);
Some(nu_data::utils::helpers::date_formatter(
string_fmt.to_string(),
))
} else {
None
};
let options = nu_data::utils::Operation {
grouper: Some(grouper),
splitter: Some(splitter),
format: &formatter,
eval: &self.eval,
reduction: &self.reduction,
};
let _ = display(&nu_data::utils::report(&data, options, &name)?);
}
Columns::One(col) => {
let key = col.clone();
let fmt = self.format.clone();
let grouper = Box::new(move |_: usize, row: &Value| {
let key = key.clone();
let fmt = fmt.clone();
match row.get_data_by_key(key.borrow_spanned()) {
Some(key) => {
if let Some(fmt) = fmt {
let callback = nu_data::utils::helpers::date_formatter(fmt);
callback(&key, "nothing".to_string())
} else {
nu_value_ext::as_string(&key)
}
}
None => Err(ShellError::labeled_error(
"unknown column",
"unknown column",
key.tag(),
)),
}
});
let formatter = if self.format.is_some() {
let default = String::from("%b-%Y");
let string_fmt = self.format.as_ref().unwrap_or_else(|| &default);
Some(nu_data::utils::helpers::date_formatter(
string_fmt.to_string(),
))
} else {
None
};
let options = nu_data::utils::Operation {
grouper: Some(grouper),
splitter: None,
format: &formatter,
eval: &self.eval,
reduction: &self.reduction,
};
let _ = display(&nu_data::utils::report(&data, options, &name)?);
}
_ => {}
}
Ok(())
}
}
pub fn evaluator(by: ColumnPath) -> Box<dyn Fn(usize, &Value) -> Result<Value, ShellError> + Send> {
Box::new(move |_: usize, value: &Value| {
let path = by.clone();
let eval = nu_value_ext::get_data_by_column_path(value, &path, move |_, _, error| error);
match eval {
Ok(with_value) => Ok(with_value),
Err(reason) => Err(reason),
}
})
}