Radish alpha
r
rad:z39mP9rQAaGmERfUMPULfPUi473tY
Radicle terminal user interface
Radicle
Git
inbox: Remove legacy tui-realm commands
Merged did:key:z6MkgFq6...nBGz opened 2 years ago
11 files changed +1117 -1966 3c32e9a3 8438ada1
modified bin/commands/inbox.rs
@@ -1,11 +1,7 @@
#[path = "inbox/common.rs"]
mod common;
-
#[cfg(feature = "flux")]
-
#[path = "inbox/flux.rs"]
-
mod flux;
-
#[cfg(feature = "realm")]
-
#[path = "inbox/realm.rs"]
-
mod realm;
+
#[path = "inbox/select.rs"]
+
mod select;

use std::ffi::OsString;

@@ -142,39 +138,6 @@ impl Args for Options {
    }
}

-
#[cfg(feature = "realm")]
-
pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
-
    use tui::common::context;
-
    use tui::common::log;
-
    use tui::realm::Window;
-

-
    pub const FPS: u64 = 60;
-
    let (_, id) = radicle::rad::cwd()
-
        .map_err(|_| anyhow!("this command must be run in the context of a project"))?;
-

-
    match options.op {
-
        Operation::Select { opts } => {
-
            let profile = terminal::profile()?;
-
            let context = context::Context::new(profile, id)?;
-

-
            log::enable(context.profile(), "inbox", "select")?;
-

-
            let mut app = realm::select::App::new(
-
                context,
-
                opts.mode.clone(),
-
                opts.filter.clone(),
-
                opts.sort_by,
-
            );
-
            let output = Window::default().run(&mut app, 1000 / FPS)?;
-

-
            eprint!("{:?}", output);
-
        }
-
    }
-

-
    Ok(())
-
}
-

-
#[cfg(feature = "flux")]
#[tokio::main]
pub async fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
    use radicle::storage::ReadStorage;
@@ -190,14 +153,14 @@ pub async fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Resu

            log::enable(&profile, "inbox", "select")?;

-
            let context = flux::select::Context {
+
            let context = select::Context {
                profile,
                repository,
                mode: opts.mode,
                filter: opts.filter.clone(),
                sort_by: opts.sort_by,
            };
-
            let output = flux::select::App::new(context).run().await?;
+
            let output = select::App::new(context).run().await?;

            let output = output
                .map(|o| serde_json::to_string(&o).unwrap_or_default())
deleted bin/commands/inbox/flux.rs
@@ -1,2 +0,0 @@
-
#[path = "flux/select.rs"]
-
pub mod select;
deleted bin/commands/inbox/flux/select.rs
@@ -1,240 +0,0 @@
-
#[path = "select/ui.rs"]
-
mod ui;
-

-
use anyhow::Result;
-

-
use radicle::identity::Project;
-
use radicle::node::notifications::NotificationId;
-
use radicle::storage::ReadRepository;
-
use radicle::storage::ReadStorage;
-

-
use radicle::storage::git::Repository;
-
use radicle::Profile;
-
use radicle_tui as tui;
-

-
use tui::common::cob::inbox::{self};
-
use tui::flux::store;
-
use tui::flux::store::StateValue;
-
use tui::flux::task::{self, Interrupted};
-
use tui::flux::ui::items::NotificationItem;
-
use tui::flux::ui::Frontend;
-
use tui::Exit;
-

-
use ui::ListPage;
-

-
use super::super::common::{Mode, RepositoryMode};
-

-
type Selection = tui::Selection<NotificationId>;
-

-
pub struct Context {
-
    pub profile: Profile,
-
    pub repository: Repository,
-
    pub mode: Mode,
-
    pub filter: inbox::Filter,
-
    pub sort_by: inbox::SortBy,
-
}
-

-
pub struct App {
-
    context: Context,
-
}
-

-
#[derive(Clone, Debug)]
-
pub struct UIState {
-
    page_size: usize,
-
    show_search: bool,
-
    show_help: bool,
-
}
-

-
impl Default for UIState {
-
    fn default() -> Self {
-
        Self {
-
            page_size: 1,
-
            show_search: false,
-
            show_help: false,
-
        }
-
    }
-
}
-

-
#[derive(Clone, Debug)]
-
pub struct State {
-
    notifications: Vec<NotificationItem>,
-
    mode: Mode,
-
    project: Project,
-
    search: StateValue<String>,
-
    ui: UIState,
-
}
-

-
impl TryFrom<&Context> for State {
-
    type Error = anyhow::Error;
-

-
    fn try_from(context: &Context) -> Result<Self, Self::Error> {
-
        let doc = context.repository.identity_doc()?;
-
        let project = doc.project()?;
-

-
        let mut notifications = match &context.mode.repository() {
-
            RepositoryMode::All => {
-
                let mut repos = context.profile.storage.repositories()?;
-
                repos.sort_by_key(|r| r.rid);
-

-
                let mut notifs = vec![];
-
                for repo in repos {
-
                    let repo = context.profile.storage.repository(repo.rid)?;
-

-
                    let items = inbox::all(&repo, &context.profile)?
-
                        .iter()
-
                        .map(|notif| NotificationItem::new(&context.profile, &repo, notif))
-
                        .filter_map(|item| item.ok())
-
                        .flatten()
-
                        .collect::<Vec<_>>();
-

-
                    notifs.extend(items);
-
                }
-

-
                notifs
-
            }
-
            RepositoryMode::Contextual => {
-
                let notifs = inbox::all(&context.repository, &context.profile)?;
-

-
                notifs
-
                    .iter()
-
                    .map(|notif| {
-
                        NotificationItem::new(&context.profile, &context.repository, notif)
-
                    })
-
                    .filter_map(|item| item.ok())
-
                    .flatten()
-
                    .collect::<Vec<_>>()
-
            }
-
            RepositoryMode::ByRepo((rid, _)) => {
-
                let repo = context.profile.storage.repository(*rid)?;
-
                let notifs = inbox::all(&repo, &context.profile)?;
-

-
                notifs
-
                    .iter()
-
                    .map(|notif| NotificationItem::new(&context.profile, &repo, notif))
-
                    .filter_map(|item| item.ok())
-
                    .flatten()
-
                    .collect::<Vec<_>>()
-
            }
-
        };
-

-
        // Set project name
-
        let mode = match &context.mode.repository() {
-
            RepositoryMode::ByRepo((rid, _)) => {
-
                let project = context
-
                    .profile
-
                    .storage
-
                    .repository(*rid)?
-
                    .identity_doc()?
-
                    .project()?;
-
                let name = project.name().to_string();
-

-
                context
-
                    .mode
-
                    .clone()
-
                    .with_repository(RepositoryMode::ByRepo((*rid, Some(name))))
-
            }
-
            _ => context.mode.clone(),
-
        };
-

-
        // Apply sorting
-
        match context.sort_by.field {
-
            "timestamp" => notifications.sort_by(|a, b| a.timestamp.cmp(&b.timestamp)),
-
            "id" => notifications.sort_by(|a, b| a.id.cmp(&b.id)),
-
            _ => {}
-
        }
-
        if context.sort_by.reverse {
-
            notifications.reverse();
-
        }
-

-
        // Sort by project if all notifications are shown
-
        if let RepositoryMode::All = mode.repository() {
-
            notifications.sort_by(|a, b| a.project.cmp(&b.project));
-
        }
-

-
        Ok(Self {
-
            notifications,
-
            mode: mode.clone(),
-
            project,
-
            search: StateValue::new(String::new()),
-
            ui: UIState::default(),
-
        })
-
    }
-
}
-

-
pub enum Action {
-
    Exit { selection: Option<Selection> },
-
    PageSize(usize),
-
    OpenSearch,
-
    UpdateSearch { value: String },
-
    ApplySearch,
-
    CloseSearch,
-
    OpenHelp,
-
    CloseHelp,
-
}
-

-
impl store::State<Action, Selection> for State {
-
    fn tick(&self) {}
-

-
    fn handle_action(&mut self, action: Action) -> Option<Exit<Selection>> {
-
        match action {
-
            Action::Exit { selection } => Some(Exit { value: selection }),
-
            Action::PageSize(size) => {
-
                self.ui.page_size = size;
-
                None
-
            }
-
            Action::OpenSearch => {
-
                self.ui.show_search = true;
-
                None
-
            }
-
            Action::UpdateSearch { value } => {
-
                self.search.write(value);
-
                None
-
            }
-
            Action::ApplySearch => {
-
                self.search.apply();
-
                self.ui.show_search = false;
-
                None
-
            }
-
            Action::CloseSearch => {
-
                self.search.reset();
-
                self.ui.show_search = false;
-
                None
-
            }
-
            Action::OpenHelp => {
-
                self.ui.show_help = true;
-
                None
-
            }
-
            Action::CloseHelp => {
-
                self.ui.show_help = false;
-
                None
-
            }
-
        }
-
    }
-
}
-

-
impl App {
-
    pub fn new(context: Context) -> Self {
-
        Self { context }
-
    }
-

-
    pub async fn run(&self) -> Result<Option<Selection>> {
-
        let (terminator, mut interrupt_rx) = task::create_termination();
-
        let (store, state_rx) = store::Store::<Action, State, Selection>::new();
-
        let (frontend, action_rx) = Frontend::<Action>::new();
-
        let state = State::try_from(&self.context)?;
-

-
        tokio::try_join!(
-
            store.main_loop(state, terminator, action_rx, interrupt_rx.resubscribe()),
-
            frontend.main_loop::<State, ListPage, Selection>(state_rx, interrupt_rx.resubscribe()),
-
        )?;
-

-
        if let Ok(reason) = interrupt_rx.recv().await {
-
            match reason {
-
                Interrupted::User { payload } => Ok(payload),
-
                Interrupted::OsSignal => anyhow::bail!("exited because of an os sig int"),
-
            }
-
        } else {
-
            anyhow::bail!("exited because of an unexpected error");
-
        }
-
    }
-
}
deleted bin/commands/inbox/flux/select/ui.rs
@@ -1,873 +0,0 @@
-
use std::collections::HashMap;
-
use std::str::FromStr;
-

-
use tokio::sync::mpsc::UnboundedSender;
-

-
use termion::event::Key;
-

-
use ratatui::backend::Backend;
-
use ratatui::layout::{Constraint, Layout, Rect};
-
use ratatui::style::Stylize;
-
use ratatui::text::{Line, Span, Text};
-

-
use radicle::identity::Project;
-

-
use radicle_tui as tui;
-

-
use tui::flux::ui::items::{NotificationItem, NotificationItemFilter, NotificationState};
-
use tui::flux::ui::span;
-
use tui::flux::ui::widget::container::{Footer, FooterProps, Header, HeaderProps};
-
use tui::flux::ui::widget::input::{TextField, TextFieldProps};
-
use tui::flux::ui::widget::text::{Paragraph, ParagraphProps};
-
use tui::flux::ui::widget::{
-
    Render, Shortcut, Shortcuts, ShortcutsProps, Table, TableProps, Widget,
-
};
-
use tui::Selection;
-

-
use crate::tui_inbox::common::{InboxOperation, Mode, RepositoryMode, SelectionMode};
-

-
use super::{Action, State};
-

-
pub struct ListPageProps {
-
    mode: Mode,
-
    show_search: bool,
-
    show_help: bool,
-
}
-

-
impl From<&State> for ListPageProps {
-
    fn from(state: &State) -> Self {
-
        Self {
-
            mode: state.mode.clone(),
-
            show_search: state.ui.show_search,
-
            show_help: state.ui.show_help,
-
        }
-
    }
-
}
-

-
pub struct ListPage<'a> {
-
    /// Action sender
-
    pub action_tx: UnboundedSender<Action>,
-
    /// State mapped props
-
    props: ListPageProps,
-
    /// Notification widget
-
    notifications: Notifications,
-
    /// Search widget
-
    search: Search,
-
    /// Help widget
-
    help: Help<'a>,
-
    /// Shortcut widget
-
    shortcuts: Shortcuts<Action>,
-
}
-

-
impl<'a> Widget<State, Action> for ListPage<'a> {
-
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        Self {
-
            action_tx: action_tx.clone(),
-
            props: ListPageProps::from(state),
-
            notifications: Notifications::new(state, action_tx.clone()),
-
            search: Search::new(state, action_tx.clone()),
-
            help: Help::new(state, action_tx.clone()),
-
            shortcuts: Shortcuts::new(state, action_tx.clone()),
-
        }
-
        .move_with_state(state)
-
    }
-

-
    fn move_with_state(self, state: &State) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        ListPage {
-
            notifications: self.notifications.move_with_state(state),
-
            shortcuts: self.shortcuts.move_with_state(state),
-
            help: self.help.move_with_state(state),
-
            props: ListPageProps::from(state),
-
            ..self
-
        }
-
    }
-

-
    fn name(&self) -> &str {
-
        "list-page"
-
    }
-

-
    fn handle_key_event(&mut self, key: termion::event::Key) {
-
        if self.props.show_search {
-
            <Search as Widget<State, Action>>::handle_key_event(&mut self.search, key)
-
        } else if self.props.show_help {
-
            <Help as Widget<State, Action>>::handle_key_event(&mut self.help, key)
-
        } else {
-
            match key {
-
                Key::Esc | Key::Ctrl('c') => {
-
                    let _ = self.action_tx.send(Action::Exit { selection: None });
-
                }
-
                Key::Char('/') => {
-
                    let _ = self.action_tx.send(Action::OpenSearch);
-
                }
-
                Key::Char('?') => {
-
                    let _ = self.action_tx.send(Action::OpenHelp);
-
                }
-
                _ => {
-
                    <Notifications as Widget<State, Action>>::handle_key_event(
-
                        &mut self.notifications,
-
                        key,
-
                    );
-
                }
-
            }
-
        }
-
    }
-
}
-

-
impl<'a> Render<()> for ListPage<'a> {
-
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, _area: Rect, _props: ()) {
-
        let area = frame.size();
-
        let layout = tui::flux::ui::layout::default_page(area, 0u16, 1u16);
-

-
        let shortcuts = if self.props.show_search {
-
            vec![
-
                Shortcut::new("esc", "cancel"),
-
                Shortcut::new("enter", "apply"),
-
            ]
-
        } else if self.props.show_help {
-
            vec![Shortcut::new("?", "close")]
-
        } else {
-
            match self.props.mode.selection() {
-
                SelectionMode::Id => vec![
-
                    Shortcut::new("enter", "select"),
-
                    Shortcut::new("/", "search"),
-
                ],
-
                SelectionMode::Operation => vec![
-
                    Shortcut::new("enter", "show"),
-
                    Shortcut::new("c", "clear"),
-
                    Shortcut::new("/", "search"),
-
                    Shortcut::new("?", "help"),
-
                ],
-
            }
-
        };
-

-
        if self.props.show_search {
-
            let component_layout = Layout::vertical([Constraint::Min(1), Constraint::Length(2)])
-
                .split(layout.component);
-

-
            self.notifications
-
                .render::<B>(frame, component_layout[0], ());
-
            self.search
-
                .render::<B>(frame, component_layout[1], SearchProps {});
-
        } else if self.props.show_help {
-
            self.help.render::<B>(frame, layout.component, ());
-
        } else {
-
            self.notifications.render::<B>(frame, layout.component, ());
-
        }
-

-
        self.shortcuts.render::<B>(
-
            frame,
-
            layout.shortcuts,
-
            ShortcutsProps {
-
                shortcuts,
-
                divider: '∙',
-
            },
-
        );
-
    }
-
}
-

-
struct NotificationsProps {
-
    notifications: Vec<NotificationItem>,
-
    mode: Mode,
-
    project: Project,
-
    stats: HashMap<String, usize>,
-
    cutoff: usize,
-
    cutoff_after: usize,
-
    focus: bool,
-
    page_size: usize,
-
    search: String,
-
    show_search: bool,
-
}
-

-
impl From<&State> for NotificationsProps {
-
    fn from(state: &State) -> Self {
-
        let mut seen = 0;
-
        let mut unseen = 0;
-

-
        // Filter by search string
-
        let filter = NotificationItemFilter::from_str(&state.search.read()).unwrap_or_default();
-
        let notifications = state
-
            .notifications
-
            .clone()
-
            .into_iter()
-
            .filter(|issue| filter.matches(issue))
-
            .collect::<Vec<_>>();
-

-
        // Compute statistics
-
        for notification in &state.notifications {
-
            if notification.seen {
-
                seen += 1;
-
            } else {
-
                unseen += 1;
-
            }
-
        }
-

-
        let stats = HashMap::from([("Seen".to_string(), seen), ("Unseen".to_string(), unseen)]);
-

-
        Self {
-
            notifications,
-
            mode: state.mode.clone(),
-
            project: state.project.clone(),
-
            stats,
-
            cutoff: 200,
-
            cutoff_after: 5,
-
            focus: false,
-
            page_size: state.ui.page_size,
-
            show_search: state.ui.show_search,
-
            search: state.search.read(),
-
        }
-
    }
-
}
-

-
struct Notifications {
-
    /// Action sender
-
    action_tx: UnboundedSender<Action>,
-
    /// State mapped props
-
    props: NotificationsProps,
-
    /// Table header
-
    header: Header<Action>,
-
    /// Notification table
-
    table: Table<Action>,
-
    /// Table footer
-
    footer: Footer<Action>,
-
}
-

-
impl Widget<State, Action> for Notifications {
-
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self {
-
        Self {
-
            action_tx: action_tx.clone(),
-
            props: NotificationsProps::from(state),
-
            header: Header::new(state, action_tx.clone()),
-
            table: Table::new(state, action_tx.clone()),
-
            footer: Footer::new(state, action_tx),
-
        }
-
    }
-

-
    fn move_with_state(self, state: &State) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        let props = NotificationsProps::from(state);
-
        let mut table = self.table.move_with_state(state);
-

-
        if let Some(selected) = table.selected() {
-
            if selected > props.notifications.len() {
-
                table.begin();
-
            }
-
        }
-

-
        Self {
-
            props,
-
            table,
-
            header: self.header.move_with_state(state),
-
            footer: self.footer.move_with_state(state),
-
            ..self
-
        }
-
    }
-

-
    fn name(&self) -> &str {
-
        "notifications"
-
    }
-

-
    fn handle_key_event(&mut self, key: Key) {
-
        match key {
-
            Key::Up | Key::Char('k') => {
-
                self.table.prev();
-
            }
-
            Key::Down | Key::Char('j') => {
-
                self.table.next(self.props.notifications.len());
-
            }
-
            Key::PageUp => {
-
                self.table.prev_page(self.props.page_size);
-
            }
-
            Key::PageDown => {
-
                self.table
-
                    .next_page(self.props.notifications.len(), self.props.page_size);
-
            }
-
            Key::Home => {
-
                self.table.begin();
-
            }
-
            Key::End => {
-
                self.table.end(self.props.notifications.len());
-
            }
-
            Key::Char('\n') => {
-
                self.table
-
                    .selected()
-
                    .and_then(|selected| self.props.notifications.get(selected))
-
                    .and_then(|notif| {
-
                        let selection = match self.props.mode.selection() {
-
                            SelectionMode::Operation => Selection::default()
-
                                .with_operation(InboxOperation::Show.to_string())
-
                                .with_id(notif.id),
-
                            SelectionMode::Id => Selection::default().with_id(notif.id),
-
                        };
-

-
                        self.action_tx
-
                            .send(Action::Exit {
-
                                selection: Some(selection),
-
                            })
-
                            .ok()
-
                    });
-
            }
-
            Key::Char('c') => {
-
                self.table
-
                    .selected()
-
                    .and_then(|selected| self.props.notifications.get(selected))
-
                    .and_then(|notif| {
-
                        self.action_tx
-
                            .send(Action::Exit {
-
                                selection: Some(
-
                                    Selection::default()
-
                                        .with_operation(InboxOperation::Clear.to_string())
-
                                        .with_id(notif.id),
-
                                ),
-
                            })
-
                            .ok()
-
                    });
-
            }
-
            _ => {}
-
        }
-
    }
-
}
-

-
impl Notifications {
-
    fn render_header<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
-
        let title = match self.props.mode.repository() {
-
            RepositoryMode::Contextual => self.props.project.name().to_string(),
-
            RepositoryMode::All => "All repositories".to_string(),
-
            RepositoryMode::ByRepo((_, name)) => name.clone().unwrap_or_default(),
-
        };
-

-
        self.header.render::<B>(
-
            frame,
-
            area,
-
            HeaderProps {
-
                cells: [String::from("").into(), title.into()],
-
                widths: [Constraint::Length(0), Constraint::Fill(1)],
-
                focus: self.props.focus,
-
                cutoff: self.props.cutoff,
-
                cutoff_after: self.props.cutoff_after,
-
            },
-
        );
-
    }
-

-
    fn render_list<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
-
        if let RepositoryMode::All = self.props.mode.repository() {
-
            let widths = [
-
                Constraint::Length(5),
-
                Constraint::Length(3),
-
                Constraint::Length(15),
-
                Constraint::Length(25),
-
                Constraint::Fill(1),
-
                Constraint::Length(8),
-
                Constraint::Length(10),
-
                Constraint::Length(15),
-
                Constraint::Length(18),
-
            ];
-

-
            self.table.render::<B>(
-
                frame,
-
                area,
-
                TableProps {
-
                    items: self.props.notifications.to_vec(),
-
                    has_header: true,
-
                    has_footer: !self.props.show_search,
-
                    widths,
-
                    focus: self.props.focus,
-
                    cutoff: self.props.cutoff,
-
                    cutoff_after: self.props.cutoff_after.saturating_add(1),
-
                },
-
            );
-
        } else {
-
            let widths = [
-
                Constraint::Length(5),
-
                Constraint::Length(3),
-
                Constraint::Length(25),
-
                Constraint::Fill(1),
-
                Constraint::Length(8),
-
                Constraint::Length(10),
-
                Constraint::Length(15),
-
                Constraint::Length(18),
-
            ];
-

-
            self.table.render::<B>(
-
                frame,
-
                area,
-
                TableProps {
-
                    items: self.props.notifications.to_vec(),
-
                    has_header: true,
-
                    has_footer: !self.props.show_search,
-
                    widths,
-
                    focus: self.props.focus,
-
                    cutoff: self.props.cutoff,
-
                    cutoff_after: self.props.cutoff_after,
-
                },
-
            );
-
        }
-
    }
-

-
    fn render_footer<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
-
        let search = Line::from(
-
            [
-
                span::default(" Search ".to_string())
-
                    .cyan()
-
                    .dim()
-
                    .reversed(),
-
                span::default(" ".into()),
-
                span::default(self.props.search.to_string()).gray().dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let seen = Line::from(
-
            [
-
                span::positive(self.props.stats.get("Seen").unwrap_or(&0).to_string()).dim(),
-
                span::default(" Seen".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-
        let unseen = Line::from(
-
            [
-
                span::positive(self.props.stats.get("Unseen").unwrap_or(&0).to_string())
-
                    .magenta()
-
                    .dim(),
-
                span::default(" Unseen".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let progress = self
-
            .table
-
            .progress_percentage(self.props.notifications.len(), self.props.page_size);
-
        let progress = span::default(format!("{}%", progress)).dim();
-

-
        match NotificationItemFilter::from_str(&self.props.search)
-
            .unwrap_or_default()
-
            .state()
-
        {
-
            Some(state) => {
-
                let block = match state {
-
                    NotificationState::Seen => seen,
-
                    NotificationState::Unseen => unseen,
-
                };
-

-
                self.footer.render::<B>(
-
                    frame,
-
                    area,
-
                    FooterProps {
-
                        cells: [search.into(), block.clone().into(), progress.clone().into()],
-
                        widths: [
-
                            Constraint::Fill(1),
-
                            Constraint::Min(block.width() as u16),
-
                            Constraint::Min(4),
-
                        ],
-
                        focus: self.props.focus,
-
                        cutoff: self.props.cutoff,
-
                        cutoff_after: self.props.cutoff_after,
-
                    },
-
                );
-
            }
-
            None => {
-
                self.footer.render::<B>(
-
                    frame,
-
                    area,
-
                    FooterProps {
-
                        cells: [
-
                            search.into(),
-
                            seen.clone().into(),
-
                            unseen.clone().into(),
-
                            progress.clone().into(),
-
                        ],
-
                        widths: [
-
                            Constraint::Fill(1),
-
                            Constraint::Min(seen.width() as u16),
-
                            Constraint::Min(unseen.width() as u16),
-
                            Constraint::Min(4),
-
                        ],
-
                        focus: self.props.focus,
-
                        cutoff: self.props.cutoff,
-
                        cutoff_after: self.props.cutoff_after,
-
                    },
-
                );
-
            }
-
        }
-
    }
-
}
-

-
impl Render<()> for Notifications {
-
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
-
        let page_size = if self.props.show_search {
-
            let layout = Layout::vertical([Constraint::Length(3), Constraint::Min(1)]).split(area);
-

-
            self.render_header::<B>(frame, layout[0]);
-
            self.render_list::<B>(frame, layout[1]);
-

-
            layout[1].height as usize
-
        } else {
-
            let layout = Layout::vertical([
-
                Constraint::Length(3),
-
                Constraint::Min(1),
-
                Constraint::Length(3),
-
            ])
-
            .split(area);
-

-
            self.render_header::<B>(frame, layout[0]);
-
            self.render_list::<B>(frame, layout[1]);
-
            self.render_footer::<B>(frame, layout[2]);
-

-
            layout[1].height as usize
-
        };
-

-
        if page_size != self.props.page_size {
-
            let _ = self.action_tx.send(Action::PageSize(page_size));
-
        }
-
    }
-
}
-

-
pub struct SearchProps {}
-

-
pub struct Search {
-
    pub action_tx: UnboundedSender<Action>,
-
    pub input: TextField,
-
}
-

-
impl Widget<State, Action> for Search {
-
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        let mut input = TextField::new(state, action_tx.clone());
-
        input.set_text(&state.search.read().to_string());
-

-
        Self { action_tx, input }.move_with_state(state)
-
    }
-

-
    fn move_with_state(self, state: &State) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        let mut input = <TextField as Widget<State, Action>>::move_with_state(self.input, state);
-
        input.set_text(&state.search.read().to_string());
-

-
        Self { input, ..self }
-
    }
-

-
    fn name(&self) -> &str {
-
        "filter-popup"
-
    }
-

-
    fn handle_key_event(&mut self, key: termion::event::Key) {
-
        match key {
-
            Key::Esc => {
-
                let _ = self.action_tx.send(Action::CloseSearch);
-
            }
-
            Key::Char('\n') => {
-
                let _ = self.action_tx.send(Action::ApplySearch);
-
            }
-
            _ => {
-
                <TextField as Widget<State, Action>>::handle_key_event(&mut self.input, key);
-
                let _ = self.action_tx.send(Action::UpdateSearch {
-
                    value: self.input.text().to_string(),
-
                });
-
            }
-
        }
-
    }
-
}
-

-
impl Render<SearchProps> for Search {
-
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: SearchProps) {
-
        let layout = Layout::horizontal(Constraint::from_mins([0]))
-
            .horizontal_margin(1)
-
            .split(area);
-

-
        self.input.render::<B>(
-
            frame,
-
            layout[0],
-
            TextFieldProps {
-
                titles: ("Search".into(), "Search".into()),
-
                show_cursor: true,
-
                inline_label: true,
-
            },
-
        );
-
    }
-
}
-

-
pub struct HelpProps<'a> {
-
    content: Text<'a>,
-
    focus: bool,
-
    page_size: usize,
-
}
-

-
impl<'a> From<&State> for HelpProps<'a> {
-
    fn from(state: &State) -> Self {
-
        let content = Text::from(
-
            [
-
                Line::from(Span::raw("Generic keybindings").cyan()),
-
                Line::raw(""),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "↑,k")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor one line up").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "↓,j")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor one line down").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "PageUp")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor one page up").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "PageDown")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor one page down").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "Home")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor to the first line").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "End")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("move cursor to the last line").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::raw(""),
-
                Line::from(Span::raw("Specific keybindings").cyan()),
-
                Line::raw(""),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Select notification (if --mode id)").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Show notification").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "c")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Clear notifications").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "/")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Search").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "?")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Show help").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "Esc")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Quit / cancel").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::raw(""),
-
                Line::from(Span::raw("Searching").cyan()),
-
                Line::raw(""),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "Pattern")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("is:<state> | is:patch | is:issue | <search>")
-
                            .gray()
-
                            .dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "Example")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("is:unseen is:patch Print").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
            ]
-
            .to_vec(),
-
        );
-

-
        Self {
-
            content,
-
            focus: false,
-
            page_size: state.ui.page_size,
-
        }
-
    }
-
}
-

-
pub struct Help<'a> {
-
    /// Send messages
-
    pub action_tx: UnboundedSender<Action>,
-
    /// This widget's render properties
-
    pub props: HelpProps<'a>,
-
    /// Container header
-
    header: Header<Action>,
-
    /// Content widget
-
    content: Paragraph<Action>,
-
    /// Container footer
-
    footer: Footer<Action>,
-
}
-

-
impl<'a> Widget<State, Action> for Help<'a> {
-
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        Self {
-
            action_tx: action_tx.clone(),
-
            props: HelpProps::from(state),
-
            header: Header::new(state, action_tx.clone()),
-
            content: Paragraph::new(state, action_tx.clone()),
-
            footer: Footer::new(state, action_tx),
-
        }
-
        .move_with_state(state)
-
    }
-

-
    fn move_with_state(self, state: &State) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        Self {
-
            props: HelpProps::from(state),
-
            header: self.header.move_with_state(state),
-
            content: self.content.move_with_state(state),
-
            footer: self.footer.move_with_state(state),
-
            ..self
-
        }
-
    }
-

-
    fn name(&self) -> &str {
-
        "help"
-
    }
-

-
    fn handle_key_event(&mut self, key: termion::event::Key) {
-
        let len = self.props.content.lines.len() + 1;
-
        let page_size = self.props.page_size;
-
        match key {
-
            Key::Esc => {
-
                let _ = self.action_tx.send(Action::Exit { selection: None });
-
            }
-
            Key::Char('?') => {
-
                let _ = self.action_tx.send(Action::CloseHelp);
-
            }
-
            Key::Up | Key::Char('k') => {
-
                self.content.prev(len, page_size);
-
            }
-
            Key::Down | Key::Char('j') => {
-
                self.content.next(len, page_size);
-
            }
-
            Key::PageUp => {
-
                self.content.prev_page(len, page_size);
-
            }
-
            Key::PageDown => {
-
                self.content.next_page(len, page_size);
-
            }
-
            Key::Home => {
-
                self.content.begin(len, page_size);
-
            }
-
            Key::End => {
-
                self.content.end(len, page_size);
-
            }
-
            _ => {}
-
        }
-
    }
-
}
-

-
impl<'a> Render<()> for Help<'a> {
-
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
-
        let [header_area, content_area, footer_area] = Layout::vertical([
-
            Constraint::Length(3),
-
            Constraint::Min(1),
-
            Constraint::Length(3),
-
        ])
-
        .areas(area);
-

-
        self.header.render::<B>(
-
            frame,
-
            header_area,
-
            HeaderProps {
-
                cells: [String::from(" Help ").into()],
-
                widths: [Constraint::Fill(1)],
-
                focus: self.props.focus,
-
                cutoff: usize::MIN,
-
                cutoff_after: usize::MAX,
-
            },
-
        );
-

-
        self.content.render::<B>(
-
            frame,
-
            content_area,
-
            ParagraphProps {
-
                content: self.props.content.clone(),
-
                focus: self.props.focus,
-
                has_footer: true,
-
                has_header: true,
-
            },
-
        );
-

-
        let progress = span::default(format!("{}%", self.content.progress())).dim();
-

-
        self.footer.render::<B>(
-
            frame,
-
            footer_area,
-
            FooterProps {
-
                cells: [String::new().into(), progress.clone().into()],
-
                widths: [Constraint::Fill(1), Constraint::Min(4)],
-
                focus: self.props.focus,
-
                cutoff: usize::MAX,
-
                cutoff_after: usize::MAX,
-
            },
-
        );
-

-
        let page_size = content_area.height as usize;
-
        if page_size != self.props.page_size {
-
            let _ = self.action_tx.send(Action::PageSize(page_size));
-
        }
-
    }
-
}
deleted bin/commands/inbox/realm.rs
@@ -1,2 +0,0 @@
-
#[path = "realm/select.rs"]
-
pub mod select;
deleted bin/commands/inbox/realm/select.rs
@@ -1,201 +0,0 @@
-
#[path = "select/event.rs"]
-
mod event;
-
#[path = "select/page.rs"]
-
mod page;
-
#[path = "select/ui.rs"]
-
mod ui;
-

-
use std::fmt::Display;
-
use std::hash::Hash;
-

-
use anyhow::Result;
-

-
use radicle::node::notifications::NotificationId;
-
use serde::Serialize;
-

-
use tuirealm::application::PollStrategy;
-
use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause};
-

-
use radicle_tui as tui;
-

-
use tui::common::cob::inbox::{Filter, SortBy};
-
use tui::common::context::Context;
-
use tui::realm::ui::subscription;
-
use tui::realm::ui::theme::Theme;
-
use tui::realm::{PageStack, Tui};
-
use tui::Exit;
-

-
use page::ListView;
-

-
use super::super::common::Mode;
-

-
type Selection = tui::Selection<NotificationId>;
-

-
/// The selected issue operation returned by the operation
-
/// selection widget.
-
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
-
pub enum InboxOperation {
-
    Show,
-
    Clear,
-
}
-

-
impl Display for InboxOperation {
-
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-
        match self {
-
            InboxOperation::Show => {
-
                write!(f, "show")
-
            }
-
            InboxOperation::Clear => {
-
                write!(f, "clear")
-
            }
-
        }
-
    }
-
}
-

-
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
-
pub enum ListCid {
-
    NotificationBrowser,
-
    Context,
-
    Shortcuts,
-
}
-

-
/// All component ids known to this application.
-
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
-
pub enum Cid {
-
    List(ListCid),
-
    #[default]
-
    GlobalListener,
-
}
-

-
#[derive(Clone, Default, Debug, Eq, PartialEq)]
-
pub enum Message {
-
    #[default]
-
    Tick,
-
    Quit(Option<Selection>),
-
    Batch(Vec<Message>),
-
}
-

-
pub struct App {
-
    context: Context,
-
    pages: PageStack<Cid, Message>,
-
    theme: Theme,
-
    mode: Mode,
-
    filter: Filter,
-
    sort_by: SortBy,
-
    quit: bool,
-
    output: Option<Selection>,
-
}
-

-
/// Creates a new application using a tui-realm-application, mounts all
-
/// components and sets focus to a default one.
-
#[allow(dead_code)]
-
impl App {
-
    pub fn new(context: Context, mode: Mode, filter: Filter, sort_by: SortBy) -> Self {
-
        Self {
-
            context,
-
            pages: PageStack::default(),
-
            theme: Theme::default(),
-
            mode,
-
            filter,
-
            sort_by,
-
            quit: false,
-
            output: None,
-
        }
-
    }
-

-
    fn view_list(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let home = Box::new(ListView::new(
-
            self.mode.clone(),
-
            self.filter.clone(),
-
            self.sort_by,
-
        ));
-
        self.pages.push(home, app, &self.context, theme)?;
-

-
        Ok(())
-
    }
-

-
    fn process(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        message: Message,
-
    ) -> Result<Option<Message>> {
-
        let theme = Theme::default();
-
        match message {
-
            Message::Batch(messages) => {
-
                let mut results = vec![];
-
                for message in messages {
-
                    if let Some(result) = self.process(app, message)? {
-
                        results.push(result);
-
                    }
-
                }
-
                match results.len() {
-
                    0 => Ok(None),
-
                    1 => Ok(Some(results[0].to_owned())),
-
                    _ => Ok(Some(Message::Batch(results))),
-
                }
-
            }
-
            Message::Quit(output) => {
-
                self.quit = true;
-
                self.output = output;
-
                Ok(None)
-
            }
-
            _ => self
-
                .pages
-
                .peek_mut()?
-
                .update(app, &self.context, &theme, message),
-
        }
-
    }
-
}
-

-
impl Tui<Cid, Message, Selection> for App {
-
    fn init(&mut self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        self.view_list(app, &self.theme.clone())?;
-

-
        // Add global key listener and subscribe to key events
-
        let global = tui::realm::ui::global_listener().to_boxed();
-
        app.mount(
-
            Cid::GlobalListener,
-
            global,
-
            vec![Sub::new(
-
                subscription::quit_clause(tuirealm::event::Key::Char('q')),
-
                SubClause::Always,
-
            )],
-
        )?;
-

-
        Ok(())
-
    }
-

-
    fn view(&mut self, app: &mut Application<Cid, Message, NoUserEvent>, frame: &mut Frame) {
-
        if let Ok(page) = self.pages.peek_mut() {
-
            page.view(app, frame);
-
        }
-
    }
-

-
    fn update(&mut self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<bool> {
-
        match app.tick(PollStrategy::Once) {
-
            Ok(messages) if !messages.is_empty() => {
-
                for message in messages {
-
                    let mut msg = Some(message);
-
                    while msg.is_some() {
-
                        msg = self.process(app, msg.unwrap())?;
-
                    }
-
                }
-
                Ok(true)
-
            }
-
            _ => Ok(false),
-
        }
-
    }
-

-
    fn exit(&self) -> Option<Exit<Selection>> {
-
        if self.quit {
-
            return Some(Exit {
-
                value: self.output.clone(),
-
            });
-
        }
-
        None
-
    }
-
}
deleted bin/commands/inbox/realm/select/event.rs
@@ -1,170 +0,0 @@
-
use radicle::node::notifications::NotificationId;
-

-
use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection};
-
use tuirealm::event::{Event, Key, KeyEvent};
-
use tuirealm::{MockComponent, NoUserEvent};
-

-
use radicle_tui as tui;
-

-
use tui::realm::ui::state::ItemState;
-
use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer};
-
use tui::realm::ui::widget::context::{ContextBar, Shortcuts};
-
use tui::realm::ui::widget::list::PropertyList;
-
use tui::realm::ui::widget::Widget;
-

-
use super::ui::{IdSelect, OperationSelect};
-
use super::{InboxOperation, Message};
-

-
type Selection = tui::Selection<NotificationId>;
-

-
/// Since the framework does not know the type of messages that are being
-
/// passed around in the app, the following handlers need to be implemented for
-
/// each component used.
-
///
-
/// TODO: should handle `Event::WindowResize`, which is not emitted by `termion`.
-
impl tuirealm::Component<Message, NoUserEvent> for Widget<GlobalListener> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        match event {
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Char('q'),
-
                ..
-
            }) => Some(Message::Quit(None)),
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<IdSelect> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        let mut submit = || -> Option<NotificationId> {
-
            match self.perform(Cmd::Submit) {
-
                CmdResult::Submit(state) => {
-
                    let selected = ItemState::try_from(state).ok()?.selected()?;
-
                    let item = self.items().get(selected)?;
-
                    Some(item.id().to_owned())
-
                }
-
                _ => None,
-
            }
-
        };
-

-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Up, .. })
-
            | Event::Keyboard(KeyEvent {
-
                code: Key::Char('k'),
-
                ..
-
            }) => {
-
                self.perform(Cmd::Move(MoveDirection::Up));
-
                Some(Message::Tick)
-
            }
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Down, ..
-
            })
-
            | Event::Keyboard(KeyEvent {
-
                code: Key::Char('j'),
-
                ..
-
            }) => {
-
                self.perform(Cmd::Move(MoveDirection::Down));
-
                Some(Message::Tick)
-
            }
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Enter, ..
-
            }) => submit().map(|id| {
-
                let selection = Selection {
-
                    operation: None,
-
                    ids: vec![id],
-
                    args: vec![],
-
                };
-
                Message::Quit(Some(selection))
-
            }),
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<OperationSelect> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        let mut submit = || -> Option<NotificationId> {
-
            match self.perform(Cmd::Submit) {
-
                CmdResult::Submit(state) => {
-
                    let selected = ItemState::try_from(state).ok()?.selected()?;
-
                    let item = self.items().get(selected)?;
-
                    Some(item.id().to_owned())
-
                }
-
                _ => None,
-
            }
-
        };
-

-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Up, .. })
-
            | Event::Keyboard(KeyEvent {
-
                code: Key::Char('k'),
-
                ..
-
            }) => {
-
                self.perform(Cmd::Move(MoveDirection::Up));
-
                Some(Message::Tick)
-
            }
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Down, ..
-
            })
-
            | Event::Keyboard(KeyEvent {
-
                code: Key::Char('j'),
-
                ..
-
            }) => {
-
                self.perform(Cmd::Move(MoveDirection::Down));
-
                Some(Message::Tick)
-
            }
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Enter, ..
-
            }) => submit().map(|id| {
-
                let selection = Selection {
-
                    operation: Some(InboxOperation::Show.to_string()),
-
                    ids: vec![id],
-
                    args: vec![],
-
                };
-
                Message::Quit(Some(selection))
-
            }),
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Char('c'),
-
                ..
-
            }) => submit().map(|id| {
-
                let selection = Selection {
-
                    operation: Some(InboxOperation::Clear.to_string()),
-
                    ids: vec![id],
-
                    args: vec![],
-
                };
-
                Message::Quit(Some(selection))
-
            }),
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<AppHeader> {
-
    fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
-
        None
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<LabeledContainer> {
-
    fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
-
        None
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<PropertyList> {
-
    fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
-
        None
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<ContextBar> {
-
    fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
-
        None
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<Shortcuts> {
-
    fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
-
        None
-
    }
-
}
deleted bin/commands/inbox/realm/select/page.rs
@@ -1,170 +0,0 @@
-
use std::collections::HashMap;
-

-
use anyhow::Result;
-

-
use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent};
-

-
use radicle_tui as tui;
-

-
use tui::common::cob::inbox::{Filter, SortBy};
-
use tui::common::context::Context;
-
use tui::realm::ui::layout;
-
use tui::realm::ui::state::ItemState;
-
use tui::realm::ui::theme::Theme;
-
use tui::realm::ui::widget::context::{Progress, Shortcuts};
-
use tui::realm::ui::widget::Widget;
-
use tui::realm::ViewPage;
-

-
use crate::tui_inbox::common::SelectionMode;
-

-
use super::{ui, Application, Cid, ListCid, Message, Mode};
-

-
///
-
/// Home
-
///
-
pub struct ListView {
-
    active_component: ListCid,
-
    mode: Mode,
-
    filter: Filter,
-
    sort_by: SortBy,
-
    shortcuts: HashMap<ListCid, Widget<Shortcuts>>,
-
}
-

-
impl ListView {
-
    pub fn new(mode: Mode, filter: Filter, sort_by: SortBy) -> Self {
-
        Self {
-
            active_component: ListCid::NotificationBrowser,
-
            mode,
-
            filter,
-
            sort_by,
-
            shortcuts: HashMap::default(),
-
        }
-
    }
-

-
    fn update_context(
-
        &self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let state = app.state(&Cid::List(ListCid::NotificationBrowser))?;
-
        let progress = match ItemState::try_from(state) {
-
            Ok(state) => Progress::Step(
-
                state
-
                    .selected()
-
                    .map(|s| s.saturating_add(1))
-
                    .unwrap_or_default(),
-
                state.len(),
-
            ),
-
            Err(_) => Progress::None,
-
        };
-

-
        let context = ui::browse_context(context, theme, self.filter.clone(), progress);
-

-
        app.remount(Cid::List(ListCid::Context), context.to_boxed(), vec![])?;
-

-
        Ok(())
-
    }
-

-
    fn update_shortcuts(
-
        &self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        cid: ListCid,
-
    ) -> Result<()> {
-
        if let Some(shortcuts) = self.shortcuts.get(&cid) {
-
            app.remount(
-
                Cid::List(ListCid::Shortcuts),
-
                shortcuts.clone().to_boxed(),
-
                vec![],
-
            )?;
-
        }
-

-
        Ok(())
-
    }
-
}
-

-
impl ViewPage<Cid, Message> for ListView {
-
    fn mount(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let browser = ui::operation_select(theme, context, self.filter.clone(), self.sort_by, None)
-
            .to_boxed();
-
        self.shortcuts = browser.as_ref().shortcuts();
-

-
        match self.mode.selection() {
-
            SelectionMode::Id => {
-
                let notif_browser =
-
                    ui::id_select(theme, context, self.filter.clone(), self.sort_by, None)
-
                        .to_boxed();
-
                self.shortcuts = notif_browser.as_ref().shortcuts();
-

-
                app.remount(Cid::List(ListCid::NotificationBrowser), browser, vec![])?;
-
            }
-
            SelectionMode::Operation => {
-
                let notif_browser =
-
                    ui::operation_select(theme, context, self.filter.clone(), self.sort_by, None)
-
                        .to_boxed();
-
                self.shortcuts = notif_browser.as_ref().shortcuts();
-

-
                app.remount(Cid::List(ListCid::NotificationBrowser), browser, vec![])?;
-
            }
-
        };
-

-
        app.active(&Cid::List(self.active_component.clone()))?;
-
        self.update_shortcuts(app, self.active_component.clone())?;
-
        self.update_context(app, context, theme)?;
-

-
        Ok(())
-
    }
-

-
    fn unmount(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.umount(&Cid::List(ListCid::NotificationBrowser))?;
-
        app.umount(&Cid::List(ListCid::Context))?;
-
        app.umount(&Cid::List(ListCid::Shortcuts))?;
-
        Ok(())
-
    }
-

-
    fn update(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
        _message: Message,
-
    ) -> Result<Option<Message>> {
-
        self.update_context(app, context, theme)?;
-

-
        Ok(None)
-
    }
-

-
    fn view(&mut self, app: &mut Application<Cid, Message, NoUserEvent>, frame: &mut Frame) {
-
        let area = frame.size();
-
        let context_h = app
-
            .query(&Cid::List(ListCid::Context), Attribute::Height)
-
            .unwrap_or_default()
-
            .unwrap_or(AttrValue::Size(0))
-
            .unwrap_size();
-
        let shortcuts_h = 1u16;
-

-
        let layout = layout::default_page(area, context_h, shortcuts_h);
-

-
        app.view(
-
            &Cid::List(self.active_component.clone()),
-
            frame,
-
            layout.component,
-
        );
-

-
        app.view(&Cid::List(ListCid::Context), frame, layout.context);
-
        app.view(&Cid::List(ListCid::Shortcuts), frame, layout.shortcuts);
-
    }
-

-
    fn subscribe(&self, _app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        Ok(())
-
    }
-

-
    fn unsubscribe(&self, _app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        Ok(())
-
    }
-
}
deleted bin/commands/inbox/realm/select/ui.rs
@@ -1,267 +0,0 @@
-
use std::collections::HashMap;
-

-
use radicle::node::notifications::Notification;
-

-
use tuirealm::command::{Cmd, CmdResult};
-
use tuirealm::tui::layout::Rect;
-
use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State};
-

-
use radicle_tui as tui;
-

-
use tui::common::cob::inbox::{Filter, SortBy};
-
use tui::common::context::Context;
-
use tui::realm::ui::cob::NotificationItem;
-
use tui::realm::ui::theme::{style, Theme};
-
use tui::realm::ui::widget::context::{ContextBar, Progress, Shortcuts};
-
use tui::realm::ui::widget::label::{self};
-
use tui::realm::ui::widget::list::{ColumnWidth, Table};
-
use tui::realm::ui::widget::{Widget, WidgetComponent};
-

-
use super::ListCid;
-

-
pub struct NotificationBrowser {
-
    items: Vec<NotificationItem>,
-
    table: Widget<Table<NotificationItem, 7>>,
-
}
-

-
impl NotificationBrowser {
-
    pub fn new(
-
        theme: &Theme,
-
        context: &Context,
-
        sort_by: SortBy,
-
        selected: Option<Notification>,
-
    ) -> Self {
-
        let header = [
-
            label::header(""),
-
            label::header(" ● "),
-
            label::header("Type"),
-
            label::header("Summary"),
-
            label::header("ID"),
-
            label::header("Status"),
-
            label::header("Updated"),
-
        ];
-
        let widths = [
-
            ColumnWidth::Fixed(5),
-
            ColumnWidth::Fixed(3),
-
            ColumnWidth::Fixed(6),
-
            ColumnWidth::Grow,
-
            ColumnWidth::Fixed(15),
-
            ColumnWidth::Fixed(10),
-
            ColumnWidth::Fixed(18),
-
        ];
-

-
        let mut items = vec![];
-
        for notification in context.notifications() {
-
            if let Ok(item) =
-
                NotificationItem::try_from((context.repository(), notification.clone()))
-
            {
-
                items.push(item);
-
            }
-
        }
-

-
        match sort_by.field {
-
            "timestamp" => items.sort_by(|a, b| b.timestamp().cmp(a.timestamp())),
-
            "id" => items.sort_by(|a, b| b.id().cmp(a.id())),
-
            _ => {}
-
        }
-
        if sort_by.reverse {
-
            items.reverse();
-
        }
-

-
        let selected = match selected {
-
            Some(notif) => {
-
                Some(NotificationItem::try_from((context.repository(), notif.clone())).unwrap())
-
            }
-
            _ => items.first().cloned(),
-
        };
-

-
        let table = Widget::new(Table::new(&items, selected, header, widths, theme.clone()));
-

-
        Self { items, table }
-
    }
-

-
    pub fn items(&self) -> &Vec<NotificationItem> {
-
        &self.items
-
    }
-
}
-

-
impl WidgetComponent for NotificationBrowser {
-
    fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
-
        let focus = properties
-
            .get_or(Attribute::Focus, AttrValue::Flag(false))
-
            .unwrap_flag();
-

-
        self.table.attr(Attribute::Focus, AttrValue::Flag(focus));
-
        self.table.view(frame, area);
-
    }
-

-
    fn state(&self) -> State {
-
        self.table.state()
-
    }
-

-
    fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
-
        self.table.perform(cmd)
-
    }
-
}
-

-
pub struct IdSelect {
-
    theme: Theme,
-
    browser: Widget<NotificationBrowser>,
-
}
-

-
impl IdSelect {
-
    pub fn new(theme: Theme, browser: Widget<NotificationBrowser>) -> Self {
-
        Self { theme, browser }
-
    }
-

-
    pub fn items(&self) -> &Vec<NotificationItem> {
-
        self.browser.items()
-
    }
-

-
    pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::NotificationBrowser,
-
            tui::realm::ui::shortcuts(
-
                &self.theme,
-
                vec![
-
                    tui::realm::ui::shortcut(&self.theme, "enter", "select"),
-
                    tui::realm::ui::shortcut(&self.theme, "q", "quit"),
-
                ],
-
            ),
-
        )]
-
        .iter()
-
        .cloned()
-
        .collect()
-
    }
-
}
-

-
impl WidgetComponent for IdSelect {
-
    fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
-
        let focus = properties
-
            .get_or(Attribute::Focus, AttrValue::Flag(false))
-
            .unwrap_flag();
-

-
        self.browser.attr(Attribute::Focus, AttrValue::Flag(focus));
-
        self.browser.view(frame, area);
-
    }
-

-
    fn state(&self) -> State {
-
        self.browser.state()
-
    }
-

-
    fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
-
        self.browser.perform(cmd)
-
    }
-
}
-

-
pub struct OperationSelect {
-
    theme: Theme,
-
    browser: Widget<NotificationBrowser>,
-
}
-

-
impl OperationSelect {
-
    pub fn new(theme: Theme, browser: Widget<NotificationBrowser>) -> Self {
-
        Self { theme, browser }
-
    }
-

-
    pub fn items(&self) -> &Vec<NotificationItem> {
-
        self.browser.items()
-
    }
-

-
    pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::NotificationBrowser,
-
            tui::realm::ui::shortcuts(
-
                &self.theme,
-
                vec![
-
                    tui::realm::ui::shortcut(&self.theme, "enter", "show"),
-
                    tui::realm::ui::shortcut(&self.theme, "c", "clear"),
-
                    tui::realm::ui::shortcut(&self.theme, "q", "quit"),
-
                ],
-
            ),
-
        )]
-
        .iter()
-
        .cloned()
-
        .collect()
-
    }
-
}
-

-
impl WidgetComponent for OperationSelect {
-
    fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
-
        let focus = properties
-
            .get_or(Attribute::Focus, AttrValue::Flag(false))
-
            .unwrap_flag();
-

-
        self.browser.attr(Attribute::Focus, AttrValue::Flag(focus));
-
        self.browser.view(frame, area);
-
    }
-

-
    fn state(&self) -> State {
-
        self.browser.state()
-
    }
-

-
    fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
-
        self.browser.perform(cmd)
-
    }
-
}
-

-
pub fn id_select(
-
    theme: &Theme,
-
    context: &Context,
-
    _filter: Filter,
-
    sort_by: SortBy,
-
    selected: Option<Notification>,
-
) -> Widget<IdSelect> {
-
    let browser = Widget::new(NotificationBrowser::new(theme, context, sort_by, selected));
-

-
    Widget::new(IdSelect::new(theme.clone(), browser))
-
}
-

-
pub fn operation_select(
-
    theme: &Theme,
-
    context: &Context,
-
    _filter: Filter,
-
    sort_by: SortBy,
-
    selected: Option<Notification>,
-
) -> Widget<OperationSelect> {
-
    let browser = Widget::new(NotificationBrowser::new(theme, context, sort_by, selected));
-

-
    Widget::new(OperationSelect::new(theme.clone(), browser))
-
}
-

-
pub fn browse_context(
-
    _context: &Context,
-
    _theme: &Theme,
-
    _filter: Filter,
-
    progress: Progress,
-
) -> Widget<ContextBar> {
-
    let context = label::reversable("/").style(style::magenta_reversed());
-
    let filter = label::default("").style(style::magenta_dim());
-

-
    let progress = label::reversable(&progress.to_string()).style(style::magenta_reversed());
-

-
    let spacer = label::default("");
-
    let _divider = label::default(" | ");
-

-
    let context_bar = ContextBar::new(
-
        label::group(&[context]),
-
        label::group(&[filter]),
-
        label::group(&[spacer.clone()]),
-
        label::group(&[
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
            spacer.clone(),
-
        ]),
-
        label::group(&[progress]),
-
    );
-

-
    Widget::new(context_bar).height(1)
-
}
added bin/commands/inbox/select.rs
@@ -0,0 +1,240 @@
+
#[path = "select/ui.rs"]
+
mod ui;
+

+
use anyhow::Result;
+

+
use radicle::identity::Project;
+
use radicle::node::notifications::NotificationId;
+
use radicle::storage::ReadRepository;
+
use radicle::storage::ReadStorage;
+

+
use radicle::storage::git::Repository;
+
use radicle::Profile;
+
use radicle_tui as tui;
+

+
use tui::common::cob::inbox::{self};
+
use tui::flux::store;
+
use tui::flux::store::StateValue;
+
use tui::flux::task::{self, Interrupted};
+
use tui::flux::ui::items::NotificationItem;
+
use tui::flux::ui::Frontend;
+
use tui::Exit;
+

+
use ui::ListPage;
+

+
use super::common::{Mode, RepositoryMode};
+

+
type Selection = tui::Selection<NotificationId>;
+

+
pub struct Context {
+
    pub profile: Profile,
+
    pub repository: Repository,
+
    pub mode: Mode,
+
    pub filter: inbox::Filter,
+
    pub sort_by: inbox::SortBy,
+
}
+

+
pub struct App {
+
    context: Context,
+
}
+

+
#[derive(Clone, Debug)]
+
pub struct UIState {
+
    page_size: usize,
+
    show_search: bool,
+
    show_help: bool,
+
}
+

+
impl Default for UIState {
+
    fn default() -> Self {
+
        Self {
+
            page_size: 1,
+
            show_search: false,
+
            show_help: false,
+
        }
+
    }
+
}
+

+
#[derive(Clone, Debug)]
+
pub struct State {
+
    notifications: Vec<NotificationItem>,
+
    mode: Mode,
+
    project: Project,
+
    search: StateValue<String>,
+
    ui: UIState,
+
}
+

+
impl TryFrom<&Context> for State {
+
    type Error = anyhow::Error;
+

+
    fn try_from(context: &Context) -> Result<Self, Self::Error> {
+
        let doc = context.repository.identity_doc()?;
+
        let project = doc.project()?;
+

+
        let mut notifications = match &context.mode.repository() {
+
            RepositoryMode::All => {
+
                let mut repos = context.profile.storage.repositories()?;
+
                repos.sort_by_key(|r| r.rid);
+

+
                let mut notifs = vec![];
+
                for repo in repos {
+
                    let repo = context.profile.storage.repository(repo.rid)?;
+

+
                    let items = inbox::all(&repo, &context.profile)?
+
                        .iter()
+
                        .map(|notif| NotificationItem::new(&context.profile, &repo, notif))
+
                        .filter_map(|item| item.ok())
+
                        .flatten()
+
                        .collect::<Vec<_>>();
+

+
                    notifs.extend(items);
+
                }
+

+
                notifs
+
            }
+
            RepositoryMode::Contextual => {
+
                let notifs = inbox::all(&context.repository, &context.profile)?;
+

+
                notifs
+
                    .iter()
+
                    .map(|notif| {
+
                        NotificationItem::new(&context.profile, &context.repository, notif)
+
                    })
+
                    .filter_map(|item| item.ok())
+
                    .flatten()
+
                    .collect::<Vec<_>>()
+
            }
+
            RepositoryMode::ByRepo((rid, _)) => {
+
                let repo = context.profile.storage.repository(*rid)?;
+
                let notifs = inbox::all(&repo, &context.profile)?;
+

+
                notifs
+
                    .iter()
+
                    .map(|notif| NotificationItem::new(&context.profile, &repo, notif))
+
                    .filter_map(|item| item.ok())
+
                    .flatten()
+
                    .collect::<Vec<_>>()
+
            }
+
        };
+

+
        // Set project name
+
        let mode = match &context.mode.repository() {
+
            RepositoryMode::ByRepo((rid, _)) => {
+
                let project = context
+
                    .profile
+
                    .storage
+
                    .repository(*rid)?
+
                    .identity_doc()?
+
                    .project()?;
+
                let name = project.name().to_string();
+

+
                context
+
                    .mode
+
                    .clone()
+
                    .with_repository(RepositoryMode::ByRepo((*rid, Some(name))))
+
            }
+
            _ => context.mode.clone(),
+
        };
+

+
        // Apply sorting
+
        match context.sort_by.field {
+
            "timestamp" => notifications.sort_by(|a, b| a.timestamp.cmp(&b.timestamp)),
+
            "id" => notifications.sort_by(|a, b| a.id.cmp(&b.id)),
+
            _ => {}
+
        }
+
        if context.sort_by.reverse {
+
            notifications.reverse();
+
        }
+

+
        // Sort by project if all notifications are shown
+
        if let RepositoryMode::All = mode.repository() {
+
            notifications.sort_by(|a, b| a.project.cmp(&b.project));
+
        }
+

+
        Ok(Self {
+
            notifications,
+
            mode: mode.clone(),
+
            project,
+
            search: StateValue::new(String::new()),
+
            ui: UIState::default(),
+
        })
+
    }
+
}
+

+
pub enum Action {
+
    Exit { selection: Option<Selection> },
+
    PageSize(usize),
+
    OpenSearch,
+
    UpdateSearch { value: String },
+
    ApplySearch,
+
    CloseSearch,
+
    OpenHelp,
+
    CloseHelp,
+
}
+

+
impl store::State<Action, Selection> for State {
+
    fn tick(&self) {}
+

+
    fn handle_action(&mut self, action: Action) -> Option<Exit<Selection>> {
+
        match action {
+
            Action::Exit { selection } => Some(Exit { value: selection }),
+
            Action::PageSize(size) => {
+
                self.ui.page_size = size;
+
                None
+
            }
+
            Action::OpenSearch => {
+
                self.ui.show_search = true;
+
                None
+
            }
+
            Action::UpdateSearch { value } => {
+
                self.search.write(value);
+
                None
+
            }
+
            Action::ApplySearch => {
+
                self.search.apply();
+
                self.ui.show_search = false;
+
                None
+
            }
+
            Action::CloseSearch => {
+
                self.search.reset();
+
                self.ui.show_search = false;
+
                None
+
            }
+
            Action::OpenHelp => {
+
                self.ui.show_help = true;
+
                None
+
            }
+
            Action::CloseHelp => {
+
                self.ui.show_help = false;
+
                None
+
            }
+
        }
+
    }
+
}
+

+
impl App {
+
    pub fn new(context: Context) -> Self {
+
        Self { context }
+
    }
+

+
    pub async fn run(&self) -> Result<Option<Selection>> {
+
        let (terminator, mut interrupt_rx) = task::create_termination();
+
        let (store, state_rx) = store::Store::<Action, State, Selection>::new();
+
        let (frontend, action_rx) = Frontend::<Action>::new();
+
        let state = State::try_from(&self.context)?;
+

+
        tokio::try_join!(
+
            store.main_loop(state, terminator, action_rx, interrupt_rx.resubscribe()),
+
            frontend.main_loop::<State, ListPage, Selection>(state_rx, interrupt_rx.resubscribe()),
+
        )?;
+

+
        if let Ok(reason) = interrupt_rx.recv().await {
+
            match reason {
+
                Interrupted::User { payload } => Ok(payload),
+
                Interrupted::OsSignal => anyhow::bail!("exited because of an os sig int"),
+
            }
+
        } else {
+
            anyhow::bail!("exited because of an unexpected error");
+
        }
+
    }
+
}
added bin/commands/inbox/select/ui.rs
@@ -0,0 +1,873 @@
+
use std::collections::HashMap;
+
use std::str::FromStr;
+

+
use tokio::sync::mpsc::UnboundedSender;
+

+
use termion::event::Key;
+

+
use ratatui::backend::Backend;
+
use ratatui::layout::{Constraint, Layout, Rect};
+
use ratatui::style::Stylize;
+
use ratatui::text::{Line, Span, Text};
+

+
use radicle::identity::Project;
+

+
use radicle_tui as tui;
+

+
use tui::flux::ui::items::{NotificationItem, NotificationItemFilter, NotificationState};
+
use tui::flux::ui::span;
+
use tui::flux::ui::widget::container::{Footer, FooterProps, Header, HeaderProps};
+
use tui::flux::ui::widget::input::{TextField, TextFieldProps};
+
use tui::flux::ui::widget::text::{Paragraph, ParagraphProps};
+
use tui::flux::ui::widget::{
+
    Render, Shortcut, Shortcuts, ShortcutsProps, Table, TableProps, Widget,
+
};
+
use tui::Selection;
+

+
use crate::tui_inbox::common::{InboxOperation, Mode, RepositoryMode, SelectionMode};
+

+
use super::{Action, State};
+

+
pub struct ListPageProps {
+
    mode: Mode,
+
    show_search: bool,
+
    show_help: bool,
+
}
+

+
impl From<&State> for ListPageProps {
+
    fn from(state: &State) -> Self {
+
        Self {
+
            mode: state.mode.clone(),
+
            show_search: state.ui.show_search,
+
            show_help: state.ui.show_help,
+
        }
+
    }
+
}
+

+
pub struct ListPage<'a> {
+
    /// Action sender
+
    pub action_tx: UnboundedSender<Action>,
+
    /// State mapped props
+
    props: ListPageProps,
+
    /// Notification widget
+
    notifications: Notifications,
+
    /// Search widget
+
    search: Search,
+
    /// Help widget
+
    help: Help<'a>,
+
    /// Shortcut widget
+
    shortcuts: Shortcuts<Action>,
+
}
+

+
impl<'a> Widget<State, Action> for ListPage<'a> {
+
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        Self {
+
            action_tx: action_tx.clone(),
+
            props: ListPageProps::from(state),
+
            notifications: Notifications::new(state, action_tx.clone()),
+
            search: Search::new(state, action_tx.clone()),
+
            help: Help::new(state, action_tx.clone()),
+
            shortcuts: Shortcuts::new(state, action_tx.clone()),
+
        }
+
        .move_with_state(state)
+
    }
+

+
    fn move_with_state(self, state: &State) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        ListPage {
+
            notifications: self.notifications.move_with_state(state),
+
            shortcuts: self.shortcuts.move_with_state(state),
+
            help: self.help.move_with_state(state),
+
            props: ListPageProps::from(state),
+
            ..self
+
        }
+
    }
+

+
    fn name(&self) -> &str {
+
        "list-page"
+
    }
+

+
    fn handle_key_event(&mut self, key: termion::event::Key) {
+
        if self.props.show_search {
+
            <Search as Widget<State, Action>>::handle_key_event(&mut self.search, key)
+
        } else if self.props.show_help {
+
            <Help as Widget<State, Action>>::handle_key_event(&mut self.help, key)
+
        } else {
+
            match key {
+
                Key::Esc | Key::Ctrl('c') => {
+
                    let _ = self.action_tx.send(Action::Exit { selection: None });
+
                }
+
                Key::Char('/') => {
+
                    let _ = self.action_tx.send(Action::OpenSearch);
+
                }
+
                Key::Char('?') => {
+
                    let _ = self.action_tx.send(Action::OpenHelp);
+
                }
+
                _ => {
+
                    <Notifications as Widget<State, Action>>::handle_key_event(
+
                        &mut self.notifications,
+
                        key,
+
                    );
+
                }
+
            }
+
        }
+
    }
+
}
+

+
impl<'a> Render<()> for ListPage<'a> {
+
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, _area: Rect, _props: ()) {
+
        let area = frame.size();
+
        let layout = tui::flux::ui::layout::default_page(area, 0u16, 1u16);
+

+
        let shortcuts = if self.props.show_search {
+
            vec![
+
                Shortcut::new("esc", "cancel"),
+
                Shortcut::new("enter", "apply"),
+
            ]
+
        } else if self.props.show_help {
+
            vec![Shortcut::new("?", "close")]
+
        } else {
+
            match self.props.mode.selection() {
+
                SelectionMode::Id => vec![
+
                    Shortcut::new("enter", "select"),
+
                    Shortcut::new("/", "search"),
+
                ],
+
                SelectionMode::Operation => vec![
+
                    Shortcut::new("enter", "show"),
+
                    Shortcut::new("c", "clear"),
+
                    Shortcut::new("/", "search"),
+
                    Shortcut::new("?", "help"),
+
                ],
+
            }
+
        };
+

+
        if self.props.show_search {
+
            let component_layout = Layout::vertical([Constraint::Min(1), Constraint::Length(2)])
+
                .split(layout.component);
+

+
            self.notifications
+
                .render::<B>(frame, component_layout[0], ());
+
            self.search
+
                .render::<B>(frame, component_layout[1], SearchProps {});
+
        } else if self.props.show_help {
+
            self.help.render::<B>(frame, layout.component, ());
+
        } else {
+
            self.notifications.render::<B>(frame, layout.component, ());
+
        }
+

+
        self.shortcuts.render::<B>(
+
            frame,
+
            layout.shortcuts,
+
            ShortcutsProps {
+
                shortcuts,
+
                divider: '∙',
+
            },
+
        );
+
    }
+
}
+

+
struct NotificationsProps {
+
    notifications: Vec<NotificationItem>,
+
    mode: Mode,
+
    project: Project,
+
    stats: HashMap<String, usize>,
+
    cutoff: usize,
+
    cutoff_after: usize,
+
    focus: bool,
+
    page_size: usize,
+
    search: String,
+
    show_search: bool,
+
}
+

+
impl From<&State> for NotificationsProps {
+
    fn from(state: &State) -> Self {
+
        let mut seen = 0;
+
        let mut unseen = 0;
+

+
        // Filter by search string
+
        let filter = NotificationItemFilter::from_str(&state.search.read()).unwrap_or_default();
+
        let notifications = state
+
            .notifications
+
            .clone()
+
            .into_iter()
+
            .filter(|issue| filter.matches(issue))
+
            .collect::<Vec<_>>();
+

+
        // Compute statistics
+
        for notification in &state.notifications {
+
            if notification.seen {
+
                seen += 1;
+
            } else {
+
                unseen += 1;
+
            }
+
        }
+

+
        let stats = HashMap::from([("Seen".to_string(), seen), ("Unseen".to_string(), unseen)]);
+

+
        Self {
+
            notifications,
+
            mode: state.mode.clone(),
+
            project: state.project.clone(),
+
            stats,
+
            cutoff: 200,
+
            cutoff_after: 5,
+
            focus: false,
+
            page_size: state.ui.page_size,
+
            show_search: state.ui.show_search,
+
            search: state.search.read(),
+
        }
+
    }
+
}
+

+
struct Notifications {
+
    /// Action sender
+
    action_tx: UnboundedSender<Action>,
+
    /// State mapped props
+
    props: NotificationsProps,
+
    /// Table header
+
    header: Header<Action>,
+
    /// Notification table
+
    table: Table<Action>,
+
    /// Table footer
+
    footer: Footer<Action>,
+
}
+

+
impl Widget<State, Action> for Notifications {
+
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self {
+
        Self {
+
            action_tx: action_tx.clone(),
+
            props: NotificationsProps::from(state),
+
            header: Header::new(state, action_tx.clone()),
+
            table: Table::new(state, action_tx.clone()),
+
            footer: Footer::new(state, action_tx),
+
        }
+
    }
+

+
    fn move_with_state(self, state: &State) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        let props = NotificationsProps::from(state);
+
        let mut table = self.table.move_with_state(state);
+

+
        if let Some(selected) = table.selected() {
+
            if selected > props.notifications.len() {
+
                table.begin();
+
            }
+
        }
+

+
        Self {
+
            props,
+
            table,
+
            header: self.header.move_with_state(state),
+
            footer: self.footer.move_with_state(state),
+
            ..self
+
        }
+
    }
+

+
    fn name(&self) -> &str {
+
        "notifications"
+
    }
+

+
    fn handle_key_event(&mut self, key: Key) {
+
        match key {
+
            Key::Up | Key::Char('k') => {
+
                self.table.prev();
+
            }
+
            Key::Down | Key::Char('j') => {
+
                self.table.next(self.props.notifications.len());
+
            }
+
            Key::PageUp => {
+
                self.table.prev_page(self.props.page_size);
+
            }
+
            Key::PageDown => {
+
                self.table
+
                    .next_page(self.props.notifications.len(), self.props.page_size);
+
            }
+
            Key::Home => {
+
                self.table.begin();
+
            }
+
            Key::End => {
+
                self.table.end(self.props.notifications.len());
+
            }
+
            Key::Char('\n') => {
+
                self.table
+
                    .selected()
+
                    .and_then(|selected| self.props.notifications.get(selected))
+
                    .and_then(|notif| {
+
                        let selection = match self.props.mode.selection() {
+
                            SelectionMode::Operation => Selection::default()
+
                                .with_operation(InboxOperation::Show.to_string())
+
                                .with_id(notif.id),
+
                            SelectionMode::Id => Selection::default().with_id(notif.id),
+
                        };
+

+
                        self.action_tx
+
                            .send(Action::Exit {
+
                                selection: Some(selection),
+
                            })
+
                            .ok()
+
                    });
+
            }
+
            Key::Char('c') => {
+
                self.table
+
                    .selected()
+
                    .and_then(|selected| self.props.notifications.get(selected))
+
                    .and_then(|notif| {
+
                        self.action_tx
+
                            .send(Action::Exit {
+
                                selection: Some(
+
                                    Selection::default()
+
                                        .with_operation(InboxOperation::Clear.to_string())
+
                                        .with_id(notif.id),
+
                                ),
+
                            })
+
                            .ok()
+
                    });
+
            }
+
            _ => {}
+
        }
+
    }
+
}
+

+
impl Notifications {
+
    fn render_header<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
+
        let title = match self.props.mode.repository() {
+
            RepositoryMode::Contextual => self.props.project.name().to_string(),
+
            RepositoryMode::All => "All repositories".to_string(),
+
            RepositoryMode::ByRepo((_, name)) => name.clone().unwrap_or_default(),
+
        };
+

+
        self.header.render::<B>(
+
            frame,
+
            area,
+
            HeaderProps {
+
                cells: [String::from("").into(), title.into()],
+
                widths: [Constraint::Length(0), Constraint::Fill(1)],
+
                focus: self.props.focus,
+
                cutoff: self.props.cutoff,
+
                cutoff_after: self.props.cutoff_after,
+
            },
+
        );
+
    }
+

+
    fn render_list<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
+
        if let RepositoryMode::All = self.props.mode.repository() {
+
            let widths = [
+
                Constraint::Length(5),
+
                Constraint::Length(3),
+
                Constraint::Length(15),
+
                Constraint::Length(25),
+
                Constraint::Fill(1),
+
                Constraint::Length(8),
+
                Constraint::Length(10),
+
                Constraint::Length(15),
+
                Constraint::Length(18),
+
            ];
+

+
            self.table.render::<B>(
+
                frame,
+
                area,
+
                TableProps {
+
                    items: self.props.notifications.to_vec(),
+
                    has_header: true,
+
                    has_footer: !self.props.show_search,
+
                    widths,
+
                    focus: self.props.focus,
+
                    cutoff: self.props.cutoff,
+
                    cutoff_after: self.props.cutoff_after.saturating_add(1),
+
                },
+
            );
+
        } else {
+
            let widths = [
+
                Constraint::Length(5),
+
                Constraint::Length(3),
+
                Constraint::Length(25),
+
                Constraint::Fill(1),
+
                Constraint::Length(8),
+
                Constraint::Length(10),
+
                Constraint::Length(15),
+
                Constraint::Length(18),
+
            ];
+

+
            self.table.render::<B>(
+
                frame,
+
                area,
+
                TableProps {
+
                    items: self.props.notifications.to_vec(),
+
                    has_header: true,
+
                    has_footer: !self.props.show_search,
+
                    widths,
+
                    focus: self.props.focus,
+
                    cutoff: self.props.cutoff,
+
                    cutoff_after: self.props.cutoff_after,
+
                },
+
            );
+
        }
+
    }
+

+
    fn render_footer<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
+
        let search = Line::from(
+
            [
+
                span::default(" Search ".to_string())
+
                    .cyan()
+
                    .dim()
+
                    .reversed(),
+
                span::default(" ".into()),
+
                span::default(self.props.search.to_string()).gray().dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let seen = Line::from(
+
            [
+
                span::positive(self.props.stats.get("Seen").unwrap_or(&0).to_string()).dim(),
+
                span::default(" Seen".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+
        let unseen = Line::from(
+
            [
+
                span::positive(self.props.stats.get("Unseen").unwrap_or(&0).to_string())
+
                    .magenta()
+
                    .dim(),
+
                span::default(" Unseen".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let progress = self
+
            .table
+
            .progress_percentage(self.props.notifications.len(), self.props.page_size);
+
        let progress = span::default(format!("{}%", progress)).dim();
+

+
        match NotificationItemFilter::from_str(&self.props.search)
+
            .unwrap_or_default()
+
            .state()
+
        {
+
            Some(state) => {
+
                let block = match state {
+
                    NotificationState::Seen => seen,
+
                    NotificationState::Unseen => unseen,
+
                };
+

+
                self.footer.render::<B>(
+
                    frame,
+
                    area,
+
                    FooterProps {
+
                        cells: [search.into(), block.clone().into(), progress.clone().into()],
+
                        widths: [
+
                            Constraint::Fill(1),
+
                            Constraint::Min(block.width() as u16),
+
                            Constraint::Min(4),
+
                        ],
+
                        focus: self.props.focus,
+
                        cutoff: self.props.cutoff,
+
                        cutoff_after: self.props.cutoff_after,
+
                    },
+
                );
+
            }
+
            None => {
+
                self.footer.render::<B>(
+
                    frame,
+
                    area,
+
                    FooterProps {
+
                        cells: [
+
                            search.into(),
+
                            seen.clone().into(),
+
                            unseen.clone().into(),
+
                            progress.clone().into(),
+
                        ],
+
                        widths: [
+
                            Constraint::Fill(1),
+
                            Constraint::Min(seen.width() as u16),
+
                            Constraint::Min(unseen.width() as u16),
+
                            Constraint::Min(4),
+
                        ],
+
                        focus: self.props.focus,
+
                        cutoff: self.props.cutoff,
+
                        cutoff_after: self.props.cutoff_after,
+
                    },
+
                );
+
            }
+
        }
+
    }
+
}
+

+
impl Render<()> for Notifications {
+
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
+
        let page_size = if self.props.show_search {
+
            let layout = Layout::vertical([Constraint::Length(3), Constraint::Min(1)]).split(area);
+

+
            self.render_header::<B>(frame, layout[0]);
+
            self.render_list::<B>(frame, layout[1]);
+

+
            layout[1].height as usize
+
        } else {
+
            let layout = Layout::vertical([
+
                Constraint::Length(3),
+
                Constraint::Min(1),
+
                Constraint::Length(3),
+
            ])
+
            .split(area);
+

+
            self.render_header::<B>(frame, layout[0]);
+
            self.render_list::<B>(frame, layout[1]);
+
            self.render_footer::<B>(frame, layout[2]);
+

+
            layout[1].height as usize
+
        };
+

+
        if page_size != self.props.page_size {
+
            let _ = self.action_tx.send(Action::PageSize(page_size));
+
        }
+
    }
+
}
+

+
pub struct SearchProps {}
+

+
pub struct Search {
+
    pub action_tx: UnboundedSender<Action>,
+
    pub input: TextField,
+
}
+

+
impl Widget<State, Action> for Search {
+
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        let mut input = TextField::new(state, action_tx.clone());
+
        input.set_text(&state.search.read().to_string());
+

+
        Self { action_tx, input }.move_with_state(state)
+
    }
+

+
    fn move_with_state(self, state: &State) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        let mut input = <TextField as Widget<State, Action>>::move_with_state(self.input, state);
+
        input.set_text(&state.search.read().to_string());
+

+
        Self { input, ..self }
+
    }
+

+
    fn name(&self) -> &str {
+
        "filter-popup"
+
    }
+

+
    fn handle_key_event(&mut self, key: termion::event::Key) {
+
        match key {
+
            Key::Esc => {
+
                let _ = self.action_tx.send(Action::CloseSearch);
+
            }
+
            Key::Char('\n') => {
+
                let _ = self.action_tx.send(Action::ApplySearch);
+
            }
+
            _ => {
+
                <TextField as Widget<State, Action>>::handle_key_event(&mut self.input, key);
+
                let _ = self.action_tx.send(Action::UpdateSearch {
+
                    value: self.input.text().to_string(),
+
                });
+
            }
+
        }
+
    }
+
}
+

+
impl Render<SearchProps> for Search {
+
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: SearchProps) {
+
        let layout = Layout::horizontal(Constraint::from_mins([0]))
+
            .horizontal_margin(1)
+
            .split(area);
+

+
        self.input.render::<B>(
+
            frame,
+
            layout[0],
+
            TextFieldProps {
+
                titles: ("Search".into(), "Search".into()),
+
                show_cursor: true,
+
                inline_label: true,
+
            },
+
        );
+
    }
+
}
+

+
pub struct HelpProps<'a> {
+
    content: Text<'a>,
+
    focus: bool,
+
    page_size: usize,
+
}
+

+
impl<'a> From<&State> for HelpProps<'a> {
+
    fn from(state: &State) -> Self {
+
        let content = Text::from(
+
            [
+
                Line::from(Span::raw("Generic keybindings").cyan()),
+
                Line::raw(""),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "↑,k")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor one line up").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "↓,j")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor one line down").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "PageUp")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor one page up").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "PageDown")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor one page down").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "Home")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor to the first line").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "End")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("move cursor to the last line").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::raw(""),
+
                Line::from(Span::raw("Specific keybindings").cyan()),
+
                Line::raw(""),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Select notification (if --mode id)").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Show notification").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "c")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Clear notifications").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "/")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Search").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "?")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Show help").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "Esc")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Quit / cancel").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::raw(""),
+
                Line::from(Span::raw("Searching").cyan()),
+
                Line::raw(""),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "Pattern")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("is:<state> | is:patch | is:issue | <search>")
+
                            .gray()
+
                            .dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "Example")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("is:unseen is:patch Print").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
            ]
+
            .to_vec(),
+
        );
+

+
        Self {
+
            content,
+
            focus: false,
+
            page_size: state.ui.page_size,
+
        }
+
    }
+
}
+

+
pub struct Help<'a> {
+
    /// Send messages
+
    pub action_tx: UnboundedSender<Action>,
+
    /// This widget's render properties
+
    pub props: HelpProps<'a>,
+
    /// Container header
+
    header: Header<Action>,
+
    /// Content widget
+
    content: Paragraph<Action>,
+
    /// Container footer
+
    footer: Footer<Action>,
+
}
+

+
impl<'a> Widget<State, Action> for Help<'a> {
+
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        Self {
+
            action_tx: action_tx.clone(),
+
            props: HelpProps::from(state),
+
            header: Header::new(state, action_tx.clone()),
+
            content: Paragraph::new(state, action_tx.clone()),
+
            footer: Footer::new(state, action_tx),
+
        }
+
        .move_with_state(state)
+
    }
+

+
    fn move_with_state(self, state: &State) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        Self {
+
            props: HelpProps::from(state),
+
            header: self.header.move_with_state(state),
+
            content: self.content.move_with_state(state),
+
            footer: self.footer.move_with_state(state),
+
            ..self
+
        }
+
    }
+

+
    fn name(&self) -> &str {
+
        "help"
+
    }
+

+
    fn handle_key_event(&mut self, key: termion::event::Key) {
+
        let len = self.props.content.lines.len() + 1;
+
        let page_size = self.props.page_size;
+
        match key {
+
            Key::Esc => {
+
                let _ = self.action_tx.send(Action::Exit { selection: None });
+
            }
+
            Key::Char('?') => {
+
                let _ = self.action_tx.send(Action::CloseHelp);
+
            }
+
            Key::Up | Key::Char('k') => {
+
                self.content.prev(len, page_size);
+
            }
+
            Key::Down | Key::Char('j') => {
+
                self.content.next(len, page_size);
+
            }
+
            Key::PageUp => {
+
                self.content.prev_page(len, page_size);
+
            }
+
            Key::PageDown => {
+
                self.content.next_page(len, page_size);
+
            }
+
            Key::Home => {
+
                self.content.begin(len, page_size);
+
            }
+
            Key::End => {
+
                self.content.end(len, page_size);
+
            }
+
            _ => {}
+
        }
+
    }
+
}
+

+
impl<'a> Render<()> for Help<'a> {
+
    fn render<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect, _props: ()) {
+
        let [header_area, content_area, footer_area] = Layout::vertical([
+
            Constraint::Length(3),
+
            Constraint::Min(1),
+
            Constraint::Length(3),
+
        ])
+
        .areas(area);
+

+
        self.header.render::<B>(
+
            frame,
+
            header_area,
+
            HeaderProps {
+
                cells: [String::from(" Help ").into()],
+
                widths: [Constraint::Fill(1)],
+
                focus: self.props.focus,
+
                cutoff: usize::MIN,
+
                cutoff_after: usize::MAX,
+
            },
+
        );
+

+
        self.content.render::<B>(
+
            frame,
+
            content_area,
+
            ParagraphProps {
+
                content: self.props.content.clone(),
+
                focus: self.props.focus,
+
                has_footer: true,
+
                has_header: true,
+
            },
+
        );
+

+
        let progress = span::default(format!("{}%", self.content.progress())).dim();
+

+
        self.footer.render::<B>(
+
            frame,
+
            footer_area,
+
            FooterProps {
+
                cells: [String::new().into(), progress.clone().into()],
+
                widths: [Constraint::Fill(1), Constraint::Min(4)],
+
                focus: self.props.focus,
+
                cutoff: usize::MAX,
+
                cutoff_after: usize::MAX,
+
            },
+
        );
+

+
        let page_size = content_area.height as usize;
+
        if page_size != self.props.page_size {
+
            let _ = self.action_tx.send(Action::PageSize(page_size));
+
        }
+
    }
+
}