Lines
95.89 %
Functions
45.37 %
Branches
100 %
//! The selectable list shared by the tabs that show one plist per row.
use ratatui::layout::Constraint;
use scripting::nomiscript::Value;
use tvui::RowWindow;
use crate::tabs::fetch::Fetch;
use crate::tabs::plist::parse_rows;
use crate::tabs::seq::Seq;
/// A row type a [`SelectList`] can fetch, select by key and draw.
pub trait SelectRow: Sized {
const HEADERS: &'static [&'static str];
const WIDTHS: &'static [Constraint];
fn parse(plist: &Value) -> Result<Self, String>;
/// Identity of the row, kept selected across reloads.
fn key(&self) -> &str;
fn cells(&self) -> Vec<String>;
fn has_key(&self, key: &str) -> bool {
self.key() == key
}
/// The rows of one list reply with the selection on one of them.
pub struct SelectList<R> {
pub state: Fetch<()>,
rows: Vec<R>,
/// Key the selection moves to after the next reply.
pub follow: Option<String>,
pub selected: usize,
pub window: RowWindow,
pub seq: Seq,
impl<R: SelectRow> SelectList<R> {
#[must_use]
pub fn new() -> Self {
Self {
state: Fetch::Idle,
rows: Vec::new(),
follow: None,
selected: 0,
window: RowWindow::default(),
seq: Seq::default(),
pub fn is_idle(&self) -> bool {
self.state == Fetch::Idle
pub fn any_loading(&self) -> bool {
matches!(self.state, Fetch::Loading { .. })
pub fn set_loading(&mut self, id: i64) {
self.state = Fetch::Loading { id };
/// Back to `Idle` so the next tab switch re-fetches; the rows stay visible.
pub fn reset(&mut self) {
self.state = Fetch::Idle;
/// Parse a list reply; the selection stays on its row.
pub fn on_reply(&mut self, wire: &str) {
let target = self
.follow
.take()
.or_else(|| self.selected_key().map(str::to_string));
match parse_rows(wire, R::parse) {
Ok(listed) => {
self.rows = listed;
self.state = Fetch::Loaded(());
Err(message) => self.state = Fetch::Error(message),
let found = target.and_then(|key| self.rows.iter().position(|row| row.has_key(&key)));
self.selected = found
.unwrap_or(self.selected)
.min(self.rows.len().saturating_sub(1));
pub fn rows(&self) -> &[R] {
&self.rows
pub fn selected_row(&self) -> Option<&R> {
self.rows.get(self.selected)
pub fn selected_key(&self) -> Option<&str> {
self.selected_row().map(R::key)
pub fn select_next(&mut self) {
if self.selected + 1 < self.rows.len() {
self.selected += 1;
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
/// Move the selection a view's height down or up.
pub fn select_view(&mut self, down: bool) {
self.selected = self.window.paged(self.selected, self.rows.len(), down);
pub fn select_first(&mut self) {
self.selected = 0;
/// Selects row `index` when the list holds it.
pub fn select_row(&mut self, index: usize) {
if index < self.rows.len() {
self.selected = index;
pub fn select_last(&mut self) {
self.selected = self.rows.len().saturating_sub(1);
impl<R: SelectRow> Default for SelectList<R> {
fn default() -> Self {
Self::new()
#[cfg(test)]
mod tests;