Skip to content
This repository has been archived by the owner on Aug 6, 2023. It is now read-only.

Commit

Permalink
feat: add stateful widgets
Browse files Browse the repository at this point in the history
Most widgets can be drawn directly based on the input parameters. However, some
features may require some kind of associated state to be implemented.

For example, the `List` widget can highlight the item currently selected. This
can be translated in an offset, which is the number of elements to skip in
order to have the selected item within the viewport currently allocated to this
widget. The widget can therefore only provide the following behavior: whenever
the selected item is out of the viewport scroll to a predefined position (make
the selected item the last viewable item or the one in the middle).
Nonetheless, if the widget has access to the last computed offset then it can
implement a natural scrolling experience where the last offset is reused until
the selected item is out of the viewport.

To allow such behavior within the widgets, this commit introduces the following
changes:
- Add a `StatefulWidget` trait with an associated `State` type. Widgets that
can take advantage of having a "memory" between two draw calls needs to
implement this trait.
- Add a `render_stateful_widget` method on `Frame` where the associated
state is given as a parameter.

The chosen approach is thus to let the developers manage their widgets' states
themselves as they are already responsible for the lifecycle of the wigets
(given that the crate exposes an immediate mode api).

The following changes were also introduced:

- `Widget::render` has been deleted. Developers should use `Frame::render_widget`
instead.
- `Widget::background` has been deleted. Developers should use `Buffer::set_background`
instead.
- `SelectableList` has been deleted. Developers can directly use `List` where
`SelectableList` features have been back-ported.
  • Loading branch information
fdehau committed Feb 23, 2020
1 parent 67dd1ac commit 56aeb41
Show file tree
Hide file tree
Showing 39 changed files with 623 additions and 605 deletions.
55 changes: 28 additions & 27 deletions examples/barchart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use termion::screen::AlternateScreen;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{BarChart, Block, Borders, Widget};
use tui::widgets::{BarChart, Block, Borders};
use tui::Terminal;

use crate::util::event::{Event, Events};
Expand Down Expand Up @@ -79,36 +79,37 @@ fn main() -> Result<(), failure::Error> {
.margin(2)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(f.size());
BarChart::default()
let barchart = BarChart::default()
.block(Block::default().title("Data1").borders(Borders::ALL))
.data(&app.data)
.bar_width(9)
.style(Style::default().fg(Color::Yellow))
.value_style(Style::default().fg(Color::Black).bg(Color::Yellow))
.render(&mut f, chunks[0]);
{
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[1]);
BarChart::default()
.block(Block::default().title("Data2").borders(Borders::ALL))
.data(&app.data)
.bar_width(5)
.bar_gap(3)
.style(Style::default().fg(Color::Green))
.value_style(Style::default().bg(Color::Green).modifier(Modifier::BOLD))
.render(&mut f, chunks[0]);
BarChart::default()
.block(Block::default().title("Data3").borders(Borders::ALL))
.data(&app.data)
.style(Style::default().fg(Color::Red))
.bar_width(7)
.bar_gap(0)
.value_style(Style::default().bg(Color::Red))
.label_style(Style::default().fg(Color::Cyan).modifier(Modifier::ITALIC))
.render(&mut f, chunks[1]);
}
.value_style(Style::default().fg(Color::Black).bg(Color::Yellow));
f.render_widget(barchart, chunks[0]);

let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[1]);

let barchart = BarChart::default()
.block(Block::default().title("Data2").borders(Borders::ALL))
.data(&app.data)
.bar_width(5)
.bar_gap(3)
.style(Style::default().fg(Color::Green))
.value_style(Style::default().bg(Color::Green).modifier(Modifier::BOLD));
f.render_widget(barchart, chunks[0]);

let barchart = BarChart::default()
.block(Block::default().title("Data3").borders(Borders::ALL))
.data(&app.data)
.style(Style::default().fg(Color::Red))
.bar_width(7)
.bar_gap(0)
.value_style(Style::default().bg(Color::Red))
.label_style(Style::default().fg(Color::Cyan).modifier(Modifier::ITALIC));
f.render_widget(barchart, chunks[1]);
})?;

match events.next()? {
Expand Down
43 changes: 20 additions & 23 deletions examples/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use termion::screen::AlternateScreen;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Block, BorderType, Borders, Widget};
use tui::widgets::{Block, BorderType, Borders};
use tui::Terminal;

use crate::util::event::{Event, Events};
Expand All @@ -32,11 +32,11 @@ fn main() -> Result<(), failure::Error> {
// Just draw the block and the group on the same area and build the group
// with at least a margin of 1
let size = f.size();
Block::default()
let block = Block::default()
.borders(Borders::ALL)
.title("Main block with round corners")
.border_type(BorderType::Rounded)
.render(&mut f, size);
.border_type(BorderType::Rounded);
f.render_widget(block, size);
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(4)
Expand All @@ -47,36 +47,33 @@ fn main() -> Result<(), failure::Error> {
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[0]);
Block::default()
let block = Block::default()
.title("With background")
.title_style(Style::default().fg(Color::Yellow))
.style(Style::default().bg(Color::Green))
.render(&mut f, chunks[0]);
Block::default()
.style(Style::default().bg(Color::Green));
f.render_widget(block, chunks[0]);
let title_style = Style::default()
.fg(Color::White)
.bg(Color::Red)
.modifier(Modifier::BOLD);
let block = Block::default()
.title("Styled title")
.title_style(
Style::default()
.fg(Color::White)
.bg(Color::Red)
.modifier(Modifier::BOLD),
)
.render(&mut f, chunks[1]);
.title_style(title_style);
f.render_widget(block, chunks[1]);
}
{
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[1]);
Block::default()
.title("With borders")
.borders(Borders::ALL)
.render(&mut f, chunks[0]);
Block::default()
.title("With styled and double borders")
let block = Block::default().title("With borders").borders(Borders::ALL);
f.render_widget(block, chunks[0]);
let block = Block::default()
.title("With styled borders and doubled borders")
.border_style(Style::default().fg(Color::Cyan))
.borders(Borders::LEFT | Borders::RIGHT)
.border_type(BorderType::Double)
.render(&mut f, chunks[1]);
.border_type(BorderType::Double);
f.render_widget(block, chunks[1]);
}
})?;

Expand Down
14 changes: 7 additions & 7 deletions examples/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout, Rect};
use tui::style::Color;
use tui::widgets::canvas::{Canvas, Map, MapResolution, Rectangle};
use tui::widgets::{Block, Borders, Widget};
use tui::widgets::{Block, Borders};
use tui::Terminal;

use crate::util::event::{Config, Event, Events};
Expand Down Expand Up @@ -91,7 +91,7 @@ fn main() -> Result<(), failure::Error> {
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(f.size());
Canvas::default()
let canvas = Canvas::default()
.block(Block::default().borders(Borders::ALL).title("World"))
.paint(|ctx| {
ctx.draw(&Map {
Expand All @@ -101,9 +101,9 @@ fn main() -> Result<(), failure::Error> {
ctx.print(app.x, -app.y, "You are here", Color::Yellow);
})
.x_bounds([-180.0, 180.0])
.y_bounds([-90.0, 90.0])
.render(&mut f, chunks[0]);
Canvas::default()
.y_bounds([-90.0, 90.0]);
f.render_widget(canvas, chunks[0]);
let canvas = Canvas::default()
.block(Block::default().borders(Borders::ALL).title("Pong"))
.paint(|ctx| {
ctx.draw(&Rectangle {
Expand All @@ -112,8 +112,8 @@ fn main() -> Result<(), failure::Error> {
});
})
.x_bounds([10.0, 110.0])
.y_bounds([10.0, 110.0])
.render(&mut f, chunks[1]);
.y_bounds([10.0, 110.0]);
f.render_widget(canvas, chunks[1]);
})?;

match events.next()? {
Expand Down
42 changes: 22 additions & 20 deletions examples/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use termion::raw::IntoRawMode;
use termion::screen::AlternateScreen;
use tui::backend::TermionBackend;
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Axis, Block, Borders, Chart, Dataset, Marker, Widget};
use tui::widgets::{Axis, Block, Borders, Chart, Dataset, Marker};
use tui::Terminal;

use crate::util::event::{Event, Events};
Expand Down Expand Up @@ -69,7 +69,24 @@ fn main() -> Result<(), failure::Error> {
loop {
terminal.draw(|mut f| {
let size = f.size();
Chart::default()
let x_labels = [
format!("{}", app.window[0]),
format!("{}", (app.window[0] + app.window[1]) / 2.0),
format!("{}", app.window[1]),
];
let datasets = [
Dataset::default()
.name("data2")
.marker(Marker::Dot)
.style(Style::default().fg(Color::Cyan))
.data(&app.data1),
Dataset::default()
.name("data3")
.marker(Marker::Braille)
.style(Style::default().fg(Color::Yellow))
.data(&app.data2),
];
let chart = Chart::default()
.block(
Block::default()
.title("Chart")
Expand All @@ -82,11 +99,7 @@ fn main() -> Result<(), failure::Error> {
.style(Style::default().fg(Color::Gray))
.labels_style(Style::default().modifier(Modifier::ITALIC))
.bounds(app.window)
.labels(&[
&format!("{}", app.window[0]),
&format!("{}", (app.window[0] + app.window[1]) / 2.0),
&format!("{}", app.window[1]),
]),
.labels(&x_labels),
)
.y_axis(
Axis::default()
Expand All @@ -96,19 +109,8 @@ fn main() -> Result<(), failure::Error> {
.bounds([-20.0, 20.0])
.labels(&["-20", "0", "20"]),
)
.datasets(&[
Dataset::default()
.name("data2")
.marker(Marker::Dot)
.style(Style::default().fg(Color::Cyan))
.data(&app.data1),
Dataset::default()
.name("data3")
.marker(Marker::Braille)
.style(Style::default().fg(Color::Yellow))
.data(&app.data2),
])
.render(&mut f, size);
.datasets(&datasets);
f.render_widget(chart, size);
})?;

match events.next()? {
Expand Down
18 changes: 7 additions & 11 deletions examples/crossterm_demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,21 @@ mod demo;
#[allow(dead_code)]
mod util;

use crate::demo::{ui, App};
use crossterm::{
event::{self, Event as CEvent, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{
io::{stdout, Write},
sync::mpsc,
thread,
time::Duration,
};

use crossterm::{
event::{self, Event as CEvent, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen},
};

use structopt::StructOpt;
use tui::{backend::CrosstermBackend, Terminal};

use crate::demo::{ui, App};
use crossterm::terminal::LeaveAlternateScreen;

enum Event<I> {
Input(I),
Tick,
Expand Down Expand Up @@ -70,7 +66,7 @@ fn main() -> Result<(), failure::Error> {
terminal.clear()?;

loop {
ui::draw(&mut terminal, &app)?;
terminal.draw(|mut f| ui::draw(&mut f, &mut app))?;
match rx.recv()? {
Event::Input(event) => match event.code {
KeyCode::Char('q') => {
Expand Down
2 changes: 1 addition & 1 deletion examples/curses_demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() -> Result<(), failure::Error> {
let mut last_tick = Instant::now();
let tick_rate = Duration::from_millis(cli.tick_rate);
loop {
ui::draw(&mut terminal, &app)?;
terminal.draw(|mut f| ui::draw(&mut f, &mut app))?;
match terminal.backend_mut().get_curses_mut().get_input() {
Some(input) => {
match input {
Expand Down
7 changes: 4 additions & 3 deletions examples/custom_widget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ impl<'a> Default for Label<'a> {
}

impl<'a> Widget for Label<'a> {
fn draw(&mut self, area: Rect, buf: &mut Buffer) {
fn render(self, area: Rect, buf: &mut Buffer) {
buf.set_string(area.left(), area.top(), self.text, Style::default());
}
}

impl<'a> Label<'a> {
fn text(&mut self, text: &'a str) -> &mut Label<'a> {
fn text(mut self, text: &'a str) -> Label<'a> {
self.text = text;
self
}
Expand All @@ -52,7 +52,8 @@ fn main() -> Result<(), failure::Error> {
loop {
terminal.draw(|mut f| {
let size = f.size();
Label::default().text("Test").render(&mut f, size);
let label = Label::default().text("Test");
f.render_widget(label, size);
})?;

match events.next()? {
Expand Down
Loading

0 comments on commit 56aeb41

Please sign in to comment.