Files
radicle-tui/src/ui/widget.rs
T

448 lines
12 KiB
Rust

pub mod container;
pub mod input;
pub mod text;
use std::cmp;
use std::fmt::Debug;
use tokio::sync::mpsc::UnboundedSender;
use termion::event::Key;
use ratatui::prelude::*;
use ratatui::widgets::{Block, BorderType, Borders, Cell, Row, TableState};
use self::container::Header;
use super::theme::style;
use super::{layout, span};
pub trait View<S, A> {
fn new(state: &S, action_tx: UnboundedSender<A>) -> Self
where
Self: Sized;
fn move_with_state(self, state: &S) -> Self
where
Self: Sized;
fn handle_key_event(&mut self, key: Key);
}
pub trait Render<B: Backend, P> {
fn render(&self, frame: &mut Frame, area: Rect, props: P);
}
pub trait Widget<S, A, B: Backend>: View<S, A> + Render<B, ()> {}
pub trait ToRow {
fn to_row(&self) -> Vec<Cell>;
}
pub struct ShortcutsProps {
pub shortcuts: Vec<(String, String)>,
pub divider: char,
}
impl Default for ShortcutsProps {
fn default() -> Self {
Self {
shortcuts: vec![],
divider: '∙',
}
}
}
pub struct Shortcuts<A> {
/// Message sender
pub action_tx: UnboundedSender<A>,
/// Internal properties
props: ShortcutsProps,
}
impl<A> Shortcuts<A> {
pub fn divider(mut self, divider: char) -> Self {
self.props.divider = divider;
self
}
pub fn shortcuts(mut self, shortcuts: &[(&str, &str)]) -> Self {
self.props.shortcuts.clear();
for (short, long) in shortcuts {
self.props
.shortcuts
.push((short.to_string(), long.to_string()));
}
self
}
}
impl<S, A> View<S, A> for Shortcuts<A> {
fn new(state: &S, action_tx: UnboundedSender<A>) -> Self {
Self {
action_tx: action_tx.clone(),
props: ShortcutsProps::default(),
}
.move_with_state(state)
}
fn move_with_state(self, _state: &S) -> Self {
Self { ..self }
}
fn handle_key_event(&mut self, _key: termion::event::Key) {}
}
impl<A, B: Backend> Render<B, ()> for Shortcuts<A> {
fn render(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
use ratatui::widgets::Table;
let mut shortcuts = self.props.shortcuts.iter().peekable();
let mut row = vec![];
while let Some(shortcut) = shortcuts.next() {
let short = Text::from(shortcut.0.clone()).style(style::gray());
let long = Text::from(shortcut.1.clone()).style(style::gray().dim());
let spacer = Text::from(String::new());
let divider =
Text::from(format!(" {} ", self.props.divider)).style(style::gray().dim());
row.push((shortcut.0.chars().count(), short));
row.push((1, spacer));
row.push((shortcut.1.chars().count(), long));
if shortcuts.peek().is_some() {
row.push((3, divider));
}
}
let row_copy = row.clone();
let row: Vec<Text<'_>> = row_copy
.clone()
.iter()
.map(|(_, text)| text.clone())
.collect();
let widths: Vec<Constraint> = row_copy
.clone()
.iter()
.map(|(width, _)| Constraint::Length(*width as u16))
.collect();
let table = Table::new([Row::new(row)], widths).column_spacing(0);
frame.render_widget(table, area);
}
}
impl<S, A, B: Backend> Widget<S, A, B> for Shortcuts<A> {}
#[derive(Clone, Debug)]
pub struct Column<'a> {
pub text: Text<'a>,
pub width: Constraint,
pub skip: bool,
}
impl<'a> Column<'a> {
pub fn new(text: impl Into<Text<'a>>, width: Constraint) -> Self {
Self {
text: text.into(),
width,
skip: false,
}
}
pub fn skip(mut self, skip: bool) -> Self {
self.skip = skip;
self
}
}
#[derive(Debug)]
pub struct TableProps<'a, R: ToRow> {
pub items: Vec<R>,
pub focus: bool,
pub columns: Vec<Column<'a>>,
pub has_footer: bool,
pub cutoff: usize,
pub cutoff_after: usize,
pub page_size: usize,
}
impl<'a, R: ToRow> Default for TableProps<'a, R> {
fn default() -> Self {
Self {
items: vec![],
focus: false,
columns: vec![],
has_footer: false,
cutoff: usize::MAX,
cutoff_after: usize::MAX,
page_size: 1,
}
}
}
pub struct Table<'a, A, R: ToRow> {
/// Sending actions to the state store
pub action_tx: UnboundedSender<A>,
/// Internal table properties
pub props: TableProps<'a, R>,
/// Internal selection state
state: TableState,
/// Table header widget
header: Option<Header<'a, A>>,
}
impl<'a, A, R: ToRow> Table<'a, A, R> {
pub fn items(mut self, items: Vec<R>) -> Self {
self.props.items = items;
self
}
pub fn columns(mut self, columns: Vec<Column<'a>>) -> Self {
self.props.columns = columns;
self
}
pub fn footer(mut self, has_footer: bool) -> Self {
self.props.has_footer = has_footer;
self
}
pub fn cutoff(mut self, cutoff: usize, cutoff_after: usize) -> Self {
self.props.cutoff = cutoff;
self.props.cutoff_after = cutoff_after;
self
}
pub fn page_size(mut self, page_size: usize) -> Self {
self.props.page_size = page_size;
self
}
pub fn header(mut self, header: Header<'a, A>) -> Self {
self.header = Some(header);
self
}
fn prev(&mut self) -> Option<usize> {
let selected = self.selected().map(|current| current.saturating_sub(1));
self.state.select(selected);
selected
}
fn next(&mut self, len: usize) -> Option<usize> {
let selected = self.selected().map(|current| {
if current < len.saturating_sub(1) {
current.saturating_add(1)
} else {
current
}
});
self.state.select(selected);
selected
}
fn prev_page(&mut self, page_size: usize) -> Option<usize> {
let selected = self
.selected()
.map(|current| current.saturating_sub(page_size));
self.state.select(selected);
selected
}
fn next_page(&mut self, len: usize, page_size: usize) -> Option<usize> {
let selected = self.selected().map(|current| {
if current < len.saturating_sub(1) {
cmp::min(current.saturating_add(page_size), len.saturating_sub(1))
} else {
current
}
});
self.state.select(selected);
selected
}
fn begin(&mut self) -> Option<usize> {
self.state.select(Some(0));
self.state.selected()
}
fn end(&mut self, len: usize) -> Option<usize> {
self.state.select(Some(len.saturating_sub(1)));
self.state.selected()
}
pub fn selected(&self) -> Option<usize> {
self.state.selected()
}
pub fn progress(selected: usize, len: usize, page_size: usize) -> usize {
let step = selected;
let page_size = page_size as f64;
let len = len as f64;
let lines = page_size + step.saturating_sub(page_size as usize) as f64;
let progress = (lines / len * 100.0).ceil();
if progress > 97.0 {
Self::map_range((0.0, progress), (0.0, 100.0), progress) as usize
} else {
progress as usize
}
}
fn map_range(from: (f64, f64), to: (f64, f64), value: f64) -> f64 {
to.0 + (value - from.0) * (to.1 - to.0) / (from.1 - from.0)
}
}
impl<'a, S, A, R> View<S, A> for Table<'a, A, R>
where
R: ToRow,
{
fn new(state: &S, action_tx: UnboundedSender<A>) -> Self {
Self {
action_tx: action_tx.clone(),
props: TableProps::default(),
state: TableState::default().with_selected(Some(0)),
header: None,
}
.move_with_state(state)
}
fn move_with_state(self, _state: &S) -> Self {
let mut me = self;
if let Some(selected) = me.selected() {
if selected > me.props.items.len() {
me.begin();
}
}
me
}
fn handle_key_event(&mut self, key: Key) {
match key {
Key::Up | Key::Char('k') => {
self.prev();
}
Key::Down | Key::Char('j') => {
self.next(self.props.items.len());
}
Key::PageUp => {
self.prev_page(self.props.page_size);
}
Key::PageDown => {
self.next_page(self.props.items.len(), self.props.page_size);
}
Key::Home => {
self.begin();
}
Key::End => {
self.end(self.props.items.len());
}
_ => {}
}
}
}
impl<'a, A, B, R> Render<B, ()> for Table<'a, A, R>
where
B: Backend,
R: ToRow + Debug,
{
fn render(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
let header_height = if self.header.is_some() { 3 } else { 0 };
let [header_area, table_area] =
Layout::vertical([Constraint::Length(header_height), Constraint::Min(1)]).areas(area);
let widths: Vec<Constraint> = self
.props
.columns
.iter()
.filter_map(|c| if !c.skip { Some(c.width) } else { None })
.collect();
let widths = if area.width < self.props.cutoff as u16 {
widths
.iter()
.take(self.props.cutoff_after)
.collect::<Vec<_>>()
} else {
widths.iter().collect::<Vec<_>>()
};
let borders = match (self.header.is_some(), self.props.has_footer) {
(false, false) => Borders::ALL,
(true, false) => Borders::BOTTOM | Borders::LEFT | Borders::RIGHT,
(false, true) => Borders::TOP | Borders::LEFT | Borders::RIGHT,
(true, true) => Borders::LEFT | Borders::RIGHT,
};
if !self.props.items.is_empty() {
let rows = self
.props
.items
.iter()
.map(|item| {
let mut cells = vec![];
let mut it = self.props.columns.iter();
for cell in item.to_row() {
if let Some(col) = it.next() {
if !col.skip {
cells.push(cell.clone());
}
} else {
continue;
}
}
Row::new(cells)
})
.collect::<Vec<_>>();
let rows = ratatui::widgets::Table::default()
.rows(rows)
.widths(widths)
.column_spacing(1)
.block(
Block::default()
.border_style(style::border(self.props.focus))
.border_type(BorderType::Rounded)
.borders(borders),
)
.highlight_style(style::highlight());
if let Some(header) = &self.header {
<Header<'_, _> as Render<B, ()>>::render(header, frame, header_area, ());
}
frame.render_stateful_widget(rows, table_area, &mut self.state.clone());
} else {
let block = Block::default()
.border_style(style::border(self.props.focus))
.border_type(BorderType::Rounded)
.borders(borders);
if let Some(header) = &self.header {
<Header<'_, _> as Render<B, ()>>::render(header, frame, header_area, ());
}
frame.render_widget(block, table_area);
let center = layout::centered_rect(table_area, 50, 10);
let hint = Text::from(span::default("Nothing to show".to_string()))
.centered()
.light_magenta()
.dim();
frame.render_widget(hint, center);
}
}
}
impl<'a, S, A, B, R> Widget<S, A, B> for Table<'a, A, R>
where
B: Backend,
R: ToRow + Debug,
{
}