docs(widgets): add example for sparkline (#1556)

related #1512

Also removes the sparkline example from ratatui crate since this example
is a simplified and easier to understand version of that
This commit is contained in:
Orhun Parmaksız
2024-12-07 18:35:45 +03:00
committed by GitHub
parent ff729b7607
commit 452366aa9e
3 changed files with 100 additions and 157 deletions

View File

@@ -0,0 +1,100 @@
//! # [Ratatui] `Sparkline` example
//!
//! The latest version of this example is available in the [widget examples] folder in the
//! repository.
//!
//! Please note that the examples are designed to be run against the `main` branch of the Github
//! repository. This means that you may not be able to compile with the latest release version on
//! crates.io, or the one that you have installed locally.
//!
//! See the [examples readme] for more information on finding examples that match the version of the
//! library you are using.
//!
//! [Ratatui]: https://github.com/ratatui/ratatui
//! [widget examples]: https://github.com/ratatui/ratatui/blob/main/ratatui-widgets/examples
//! [examples readme]: https://github.com/ratatui/ratatui/blob/main/examples/README.md
use std::time::Duration;
use color_eyre::Result;
use ratatui::{
crossterm::event::{self, Event},
layout::{Constraint, Layout, Rect},
style::{Color, Style, Stylize},
symbols,
text::{Line, Span},
widgets::{RenderDirection, Sparkline},
DefaultTerminal, Frame,
};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let result = run(terminal);
ratatui::restore();
result
}
/// Run the application.
fn run(mut terminal: DefaultTerminal) -> Result<()> {
loop {
terminal.draw(draw)?;
if event::poll(Duration::from_millis(16))? && matches!(event::read()?, Event::Key(_)) {
break Ok(());
}
}
}
/// Draw the UI with various sparklines.
fn draw(frame: &mut Frame) {
let vertical = Layout::vertical([
Constraint::Length(1),
Constraint::Max(2),
Constraint::Fill(1),
Constraint::Fill(1),
])
.spacing(1);
let [top, first, second, _] = vertical.areas(frame.area());
let title = Line::from_iter([
Span::from("Sparkline Widget").bold(),
Span::from(" (Press 'q' to quit)"),
]);
frame.render_widget(title.centered(), top);
render_sparkline(frame, first);
render_sin_wave(frame, second);
}
/// Render a sparkline with some sample data.
pub fn render_sparkline(frame: &mut Frame, area: Rect) {
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].repeat(area.width.into());
let sparkline = Sparkline::default()
.data(&data)
.max(10)
.direction(RenderDirection::LeftToRight)
.style(Color::Cyan);
frame.render_widget(sparkline, area);
}
/// Render a sin wave based on the current frame count.
pub fn render_sin_wave(frame: &mut Frame, area: Rect) {
let phase_shift = frame.count() as f64 * 0.2;
let data: Vec<u64> = (0..area.width)
.map(|v| {
let angle = f64::from(v) * 0.5 + phase_shift;
((angle.sin() * 3.0 + 3.0) * 10.0).round() as u64
})
.collect();
let sparkline = Sparkline::default()
.data(&data)
.max(100)
.direction(RenderDirection::RightToLeft)
.style(Style::default().magenta().on_black())
.absent_value_style(Color::Red)
.absent_value_symbol(symbols::shade::FULL);
frame.render_widget(sparkline, area);
}

View File

@@ -271,11 +271,6 @@ name = "scrollbar"
required-features = ["crossterm"]
doc-scrape-examples = true
[[example]]
name = "sparkline"
required-features = ["crossterm"]
doc-scrape-examples = true
[[example]]
name = "table"
required-features = ["crossterm"]

View File

@@ -1,152 +0,0 @@
//! # [Ratatui] Sparkline example
//!
//! The latest version of this example is available in the [examples] folder in the repository.
//!
//! Please note that the examples are designed to be run against the `main` branch of the Github
//! repository. This means that you may not be able to compile with the latest release version on
//! crates.io, or the one that you have installed locally.
//!
//! See the [examples readme] for more information on finding examples that match the version of the
//! library you are using.
//!
//! [Ratatui]: https://github.com/ratatui/ratatui
//! [examples]: https://github.com/ratatui/ratatui/blob/main/examples
//! [examples readme]: https://github.com/ratatui/ratatui/blob/main/examples/README.md
use std::time::{Duration, Instant};
use color_eyre::Result;
use rand::{
distributions::{Distribution, Uniform},
rngs::ThreadRng,
};
use ratatui::{
crossterm::event::{self, Event, KeyCode},
layout::{Constraint, Layout},
style::{Color, Style},
widgets::{Block, Borders, Sparkline},
DefaultTerminal, Frame,
};
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let app_result = App::new().run(terminal);
ratatui::restore();
app_result
}
struct App {
signal: RandomSignal,
data1: Vec<u64>,
data2: Vec<u64>,
data3: Vec<u64>,
}
#[derive(Clone)]
struct RandomSignal {
distribution: Uniform<u64>,
rng: ThreadRng,
}
impl RandomSignal {
fn new(lower: u64, upper: u64) -> Self {
Self {
distribution: Uniform::new(lower, upper),
rng: rand::thread_rng(),
}
}
}
impl Iterator for RandomSignal {
type Item = u64;
fn next(&mut self) -> Option<u64> {
Some(self.distribution.sample(&mut self.rng))
}
}
impl App {
fn new() -> Self {
let mut signal = RandomSignal::new(0, 100);
let data1 = signal.by_ref().take(200).collect::<Vec<u64>>();
let data2 = signal.by_ref().take(200).collect::<Vec<u64>>();
let data3 = signal.by_ref().take(200).collect::<Vec<u64>>();
Self {
signal,
data1,
data2,
data3,
}
}
fn on_tick(&mut self) {
let value = self.signal.next().unwrap();
self.data1.pop();
self.data1.insert(0, value);
let value = self.signal.next().unwrap();
self.data2.pop();
self.data2.insert(0, value);
let value = self.signal.next().unwrap();
self.data3.pop();
self.data3.insert(0, value);
}
fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> {
let tick_rate = Duration::from_millis(250);
let mut last_tick = Instant::now();
loop {
terminal.draw(|frame| self.draw(frame))?;
let timeout = tick_rate.saturating_sub(last_tick.elapsed());
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
return Ok(());
}
}
}
if last_tick.elapsed() >= tick_rate {
self.on_tick();
last_tick = Instant::now();
}
}
}
fn draw(&self, frame: &mut Frame) {
let chunks = Layout::vertical([
Constraint::Length(3),
Constraint::Length(3),
Constraint::Min(0),
])
.split(frame.area());
let sparkline = Sparkline::default()
.block(
Block::new()
.borders(Borders::LEFT | Borders::RIGHT)
.title("Data1"),
)
.data(&self.data1)
.style(Style::default().fg(Color::Yellow));
frame.render_widget(sparkline, chunks[0]);
let sparkline = Sparkline::default()
.block(
Block::new()
.borders(Borders::LEFT | Borders::RIGHT)
.title("Data2"),
)
.data(&self.data2)
.style(Style::default().bg(Color::Green));
frame.render_widget(sparkline, chunks[1]);
// Multiline
let sparkline = Sparkline::default()
.block(
Block::new()
.borders(Borders::LEFT | Borders::RIGHT)
.title("Data3"),
)
.data(&self.data3)
.style(Style::default().fg(Color::Red));
frame.render_widget(sparkline, chunks[2]);
}
}