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

use std::ffi::OsString;

@@ -148,36 +144,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::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 { ref opts } => {
-
            let profile = terminal::profile()?;
-
            let context = context::Context::new(profile, id)?.with_patches();
-

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

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

-
            let output = output
-
                .map(|o| serde_json::to_string(&o).unwrap_or_default())
-
                .unwrap_or_default();
-

-
            eprint!("{output}");
-
        }
-
    }
-

-
    Ok(())
-
}
-

#[cfg(feature = "flux")]
#[tokio::main]
pub async fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
@@ -194,13 +160,13 @@ pub async fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Resu

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

-
            let context = flux::select::Context {
+
            let context = select::Context {
                profile,
                repository,
                mode: opts.mode,
                filter: opts.filter.clone(),
            };
-
            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/patch/flux.rs
@@ -1,2 +0,0 @@
-
#[path = "flux/select.rs"]
-
pub mod select;
deleted bin/commands/patch/flux/select.rs
@@ -1,160 +0,0 @@
-
#[path = "select/ui.rs"]
-
mod ui;
-

-
use anyhow::Result;
-

-
use radicle::patch::PatchId;
-
use radicle::storage::git::Repository;
-
use radicle::Profile;
-

-
use radicle_tui as tui;
-

-
use tui::common::cob::patch::{self, Filter};
-
use tui::flux::store;
-
use tui::flux::task::{self, Interrupted};
-
use tui::flux::ui::items::PatchItem;
-
use tui::flux::ui::Frontend;
-
use tui::Exit;
-

-
use ui::ListPage;
-

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

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

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

-
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 {
-
    patches: Vec<PatchItem>,
-
    mode: Mode,
-
    search: store::StateValue<String>,
-
    ui: UIState,
-
}
-

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

-
    fn try_from(context: &Context) -> Result<Self, Self::Error> {
-
        let patches = patch::all(&context.profile, &context.repository)?;
-

-
        // Convert into UI items
-
        let mut items = vec![];
-
        for patch in patches {
-
            if let Ok(item) = PatchItem::new(&context.profile, &context.repository, patch.clone()) {
-
                items.push(item);
-
            }
-
        }
-

-
        Ok(Self {
-
            patches: items,
-
            mode: context.mode.clone(),
-
            search: store::StateValue::new(context.filter.to_string()),
-
            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/patch/flux/select/ui.rs
@@ -1,920 +0,0 @@
-
use std::collections::HashMap;
-
use std::str::FromStr;
-
use std::vec;
-

-
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::patch::{self, Status};
-

-
use radicle_tui as tui;
-

-
use tui::flux::ui::items::{PatchItem, PatchItemFilter};
-
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_patch::common::Mode;
-
use crate::tui_patch::common::PatchOperation;
-

-
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
-
    patches: Patches,
-
    /// 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),
-
            patches: Patches::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),
-
        }
-
        .move_with_state(state)
-
    }
-

-
    fn move_with_state(self, state: &State) -> Self
-
    where
-
        Self: Sized,
-
    {
-
        ListPage {
-
            patches: self.patches.move_with_state(state),
-
            search: self.search.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);
-
                }
-
                _ => {
-
                    <Patches as Widget<State, Action>>::handle_key_event(&mut self.patches, 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 {
-
                Mode::Id => vec![
-
                    Shortcut::new("enter", "select"),
-
                    Shortcut::new("/", "search"),
-
                ],
-
                Mode::Operation => vec![
-
                    Shortcut::new("enter", "show"),
-
                    Shortcut::new("c", "checkout"),
-
                    Shortcut::new("d", "diff"),
-
                    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.patches.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.patches.render::<B>(frame, layout.component, ());
-
        }
-

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

-
struct PatchesProps {
-
    mode: Mode,
-
    patches: Vec<PatchItem>,
-
    search: String,
-
    stats: HashMap<String, usize>,
-
    widths: [Constraint; 9],
-
    cutoff: usize,
-
    cutoff_after: usize,
-
    focus: bool,
-
    page_size: usize,
-
    show_search: bool,
-
}
-

-
impl From<&State> for PatchesProps {
-
    fn from(state: &State) -> Self {
-
        let mut draft = 0;
-
        let mut open = 0;
-
        let mut archived = 0;
-
        let mut merged = 0;
-

-
        let filter = PatchItemFilter::from_str(&state.search.read()).unwrap_or_default();
-
        let mut patches = state
-
            .patches
-
            .clone()
-
            .into_iter()
-
            .filter(|patch| filter.matches(patch))
-
            .collect::<Vec<_>>();
-

-
        // Apply sorting
-
        patches.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
-

-
        for patch in &patches {
-
            match patch.state {
-
                patch::State::Draft => draft += 1,
-
                patch::State::Open { conflicts: _ } => open += 1,
-
                patch::State::Archived => archived += 1,
-
                patch::State::Merged {
-
                    commit: _,
-
                    revision: _,
-
                } => merged += 1,
-
            }
-
        }
-

-
        let stats = HashMap::from([
-
            ("Draft".to_string(), draft),
-
            ("Open".to_string(), open),
-
            ("Archived".to_string(), archived),
-
            ("Merged".to_string(), merged),
-
        ]);
-

-
        Self {
-
            mode: state.mode.clone(),
-
            patches,
-
            search: state.search.read(),
-
            widths: [
-
                Constraint::Length(3),
-
                Constraint::Length(8),
-
                Constraint::Fill(1),
-
                Constraint::Length(16),
-
                Constraint::Length(16),
-
                Constraint::Length(8),
-
                Constraint::Length(6),
-
                Constraint::Length(6),
-
                Constraint::Length(16),
-
            ],
-
            cutoff: 150,
-
            cutoff_after: 5,
-
            focus: false,
-
            stats,
-
            page_size: state.ui.page_size,
-
            show_search: state.ui.show_search,
-
        }
-
    }
-
}
-

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

-
impl Widget<State, Action> for Patches {
-
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self {
-
        Self {
-
            action_tx: action_tx.clone(),
-
            props: PatchesProps::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 = PatchesProps::from(state);
-
        let mut table = self.table.move_with_state(state);
-

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

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

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

-
    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.patches.len());
-
            }
-
            Key::PageUp => {
-
                self.table.prev_page(self.props.page_size);
-
            }
-
            Key::PageDown => {
-
                self.table
-
                    .next_page(self.props.patches.len(), self.props.page_size);
-
            }
-
            Key::Home => {
-
                self.table.begin();
-
            }
-
            Key::End => {
-
                self.table.end(self.props.patches.len());
-
            }
-
            Key::Char('\n') => {
-
                let operation = match self.props.mode {
-
                    Mode::Operation => Some(PatchOperation::Show.to_string()),
-
                    Mode::Id => None,
-
                };
-

-
                self.table
-
                    .selected()
-
                    .and_then(|selected| self.props.patches.get(selected))
-
                    .and_then(|patch| {
-
                        self.action_tx
-
                            .send(Action::Exit {
-
                                selection: Some(Selection {
-
                                    operation,
-
                                    ids: vec![patch.id],
-
                                    args: vec![],
-
                                }),
-
                            })
-
                            .ok()
-
                    });
-
            }
-
            Key::Char('c') => {
-
                self.table
-
                    .selected()
-
                    .and_then(|selected| self.props.patches.get(selected))
-
                    .and_then(|patch| {
-
                        self.action_tx
-
                            .send(Action::Exit {
-
                                selection: Some(Selection {
-
                                    operation: Some(PatchOperation::Checkout.to_string()),
-
                                    ids: vec![patch.id],
-
                                    args: vec![],
-
                                }),
-
                            })
-
                            .ok()
-
                    });
-
            }
-
            Key::Char('d') => {
-
                self.table
-
                    .selected()
-
                    .and_then(|selected| self.props.patches.get(selected))
-
                    .and_then(|patch| {
-
                        self.action_tx
-
                            .send(Action::Exit {
-
                                selection: Some(Selection {
-
                                    operation: Some(PatchOperation::Diff.to_string()),
-
                                    ids: vec![patch.id],
-
                                    args: vec![],
-
                                }),
-
                            })
-
                            .ok()
-
                    });
-
            }
-
            _ => {}
-
        }
-
    }
-
}
-

-
impl Patches {
-
    fn render_header<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
-
        self.header.render::<B>(
-
            frame,
-
            area,
-
            HeaderProps {
-
                cells: [
-
                    String::from(" ● ").into(),
-
                    String::from("ID").into(),
-
                    String::from("Title").into(),
-
                    String::from("Author").into(),
-
                    String::from("").into(),
-
                    String::from("Head").into(),
-
                    String::from("+").into(),
-
                    String::from("- ").into(),
-
                    String::from("Updated").into(),
-
                ],
-
                widths: self.props.widths,
-
                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) {
-
        self.table.render::<B>(
-
            frame,
-
            area,
-
            TableProps {
-
                items: self.props.patches.to_vec(),
-
                has_header: true,
-
                has_footer: !self.props.show_search,
-
                widths: self.props.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 filter = PatchItemFilter::from_str(&self.props.search).unwrap_or_default();
-

-
        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 draft = Line::from(
-
            [
-
                span::default(self.props.stats.get("Draft").unwrap_or(&0).to_string()).dim(),
-
                span::default(" Draft".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let open = Line::from(
-
            [
-
                span::positive(self.props.stats.get("Open").unwrap_or(&0).to_string()).dim(),
-
                span::default(" Open".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let merged = Line::from(
-
            [
-
                span::default(self.props.stats.get("Merged").unwrap_or(&0).to_string())
-
                    .magenta()
-
                    .dim(),
-
                span::default(" Merged".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let archived = Line::from(
-
            [
-
                span::default(self.props.stats.get("Archived").unwrap_or(&0).to_string())
-
                    .yellow()
-
                    .dim(),
-
                span::default(" Archived".to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

-
        let sum = Line::from(
-
            [
-
                span::default("Σ ".to_string()).dim(),
-
                span::default(self.props.patches.len().to_string()).dim(),
-
            ]
-
            .to_vec(),
-
        );
-

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

-
        match filter.status() {
-
            Some(state) => {
-
                let block = match state {
-
                    Status::Draft => draft,
-
                    Status::Open => open,
-
                    Status::Merged => merged,
-
                    Status::Archived => archived,
-
                };
-

-
                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(),
-
                            draft.clone().into(),
-
                            open.clone().into(),
-
                            merged.clone().into(),
-
                            archived.clone().into(),
-
                            sum.clone().into(),
-
                            progress.clone().into(),
-
                        ],
-
                        widths: [
-
                            Constraint::Fill(1),
-
                            Constraint::Min(draft.width() as u16),
-
                            Constraint::Min(open.width() as u16),
-
                            Constraint::Min(merged.width() as u16),
-
                            Constraint::Min(archived.width() as u16),
-
                            Constraint::Min(sum.width() as u16),
-
                            Constraint::Min(4),
-
                        ],
-
                        focus: self.props.focus,
-
                        cutoff: self.props.cutoff,
-
                        cutoff_after: self.props.cutoff_after,
-
                    },
-
                );
-
            }
-
        };
-
    }
-
}
-

-
impl Render<()> for Patches {
-
    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 patch (if --mode id)").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Show patch").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "c")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Checkout patch").gray().dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "d")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("Show patch diff").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:authored | authors:[<did>, <did>] | <search>")
-
                            .gray()
-
                            .dim(),
-
                    ]
-
                    .to_vec(),
-
                ),
-
                Line::from(
-
                    [
-
                        Span::raw(format!("{key:>10}", key = "Example")).gray(),
-
                        Span::raw(" "),
-
                        Span::raw("is:open is:authored improve").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/patch/realm.rs
@@ -1,6 +0,0 @@
-
#[path = "realm/common.rs"]
-
pub mod common;
-
#[path = "realm/select.rs"]
-
pub mod select;
-
#[path = "realm/suite.rs"]
-
pub mod suite;
deleted bin/commands/patch/realm/common.rs
@@ -1,2 +0,0 @@
-
#[path = "common/ui.rs"]
-
pub mod ui;
deleted bin/commands/patch/realm/common/ui.rs
@@ -1,179 +0,0 @@
-
use radicle::cob::patch::{Patch, PatchId};
-

-
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::patch::Filter;
-
use tui::common::context::Context;
-
use tui::realm::ui::cob::PatchItem;
-
use tui::realm::ui::theme::{style, Theme};
-
use tui::realm::ui::widget::context::{ContextBar, Progress};
-
use tui::realm::ui::widget::label::{self};
-
use tui::realm::ui::widget::list::{ColumnWidth, Table};
-
use tui::realm::ui::widget::{Widget, WidgetComponent};
-

-
pub struct PatchBrowser {
-
    items: Vec<PatchItem>,
-
    table: Widget<Table<PatchItem, 8>>,
-
}
-

-
impl PatchBrowser {
-
    pub fn new(
-
        theme: &Theme,
-
        context: &Context,
-
        filter: Filter,
-
        selected: Option<(PatchId, Patch)>,
-
    ) -> Self {
-
        let header = [
-
            label::header(" ● "),
-
            label::header("ID"),
-
            label::header("Title"),
-
            label::header("Author"),
-
            label::header("Head"),
-
            label::header("+"),
-
            label::header("-"),
-
            label::header("Updated"),
-
        ];
-

-
        let widths = [
-
            ColumnWidth::Fixed(3),
-
            ColumnWidth::Fixed(7),
-
            ColumnWidth::Grow,
-
            ColumnWidth::Fixed(21),
-
            ColumnWidth::Fixed(7),
-
            ColumnWidth::Fixed(4),
-
            ColumnWidth::Fixed(4),
-
            ColumnWidth::Fixed(18),
-
        ];
-

-
        let repo = context.repository();
-
        let patches = context
-
            .patches()
-
            .as_ref()
-
            .unwrap()
-
            .iter()
-
            .filter(|(_, patch)| filter.matches(context.profile(), patch));
-

-
        let mut items = vec![];
-
        for (id, patch) in patches {
-
            if let Ok(item) = PatchItem::try_from((context.profile(), repo, *id, patch.clone())) {
-
                items.push(item);
-
            }
-
        }
-

-
        items.sort_by(|a, b| b.timestamp().cmp(a.timestamp()));
-
        items.sort_by(|a, b| a.state().cmp(b.state()));
-

-
        let selected = match selected {
-
            Some((id, patch)) => {
-
                Some(PatchItem::try_from((context.profile(), repo, id, patch)).unwrap())
-
            }
-
            _ => items.first().cloned(),
-
        };
-

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

-
        Self { items, table }
-
    }
-

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

-
impl WidgetComponent for PatchBrowser {
-
    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 fn browse_context(
-
    context: &Context,
-
    _theme: &Theme,
-
    filter: Filter,
-
    progress: Progress,
-
) -> Widget<ContextBar> {
-
    use radicle::cob::patch::State;
-

-
    let mut draft = 0;
-
    let mut open = 0;
-
    let mut archived = 0;
-
    let mut merged = 0;
-

-
    let patches = context
-
        .patches()
-
        .as_ref()
-
        .unwrap()
-
        .iter()
-
        .filter(|(_, patch)| filter.matches(context.profile(), patch));
-

-
    for (_, patch) in patches {
-
        match patch.state() {
-
            State::Draft => draft += 1,
-
            State::Open { conflicts: _ } => open += 1,
-
            State::Archived => archived += 1,
-
            State::Merged {
-
                commit: _,
-
                revision: _,
-
            } => merged += 1,
-
        }
-
    }
-

-
    let context = label::reversable("/").style(style::magenta_reversed());
-
    let filter = label::default(&filter.to_string()).style(style::magenta_dim());
-

-
    let draft_n = label::default(&format!("{draft}")).style(style::gray_dim());
-
    let draft = label::default(" Draft");
-

-
    let open_n = label::default(&format!("{open}")).style(style::green());
-
    let open = label::default(" Open");
-

-
    let archived_n = label::default(&format!("{archived}")).style(style::yellow());
-
    let archived = label::default(" Archived");
-

-
    let merged_n = label::default(&format!("{merged}")).style(style::cyan());
-
    let merged = label::default(" Merged ");
-

-
    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]),
-
        label::group(&[
-
            draft_n,
-
            draft,
-
            divider.clone(),
-
            open_n,
-
            open,
-
            divider.clone(),
-
            archived_n,
-
            archived,
-
            divider,
-
            merged_n,
-
            merged,
-
        ]),
-
        label::group(&[progress]),
-
    );
-

-
    Widget::new(context_bar).height(1)
-
}
deleted bin/commands/patch/realm/select.rs
@@ -1,173 +0,0 @@
-
#[path = "select/event.rs"]
-
mod event;
-
#[path = "select/page.rs"]
-
mod page;
-
#[path = "select/ui.rs"]
-
mod ui;
-

-
use std::hash::Hash;
-

-
use anyhow::Result;
-
use radicle::patch::PatchId;
-

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

-
use radicle_tui as tui;
-

-
use tui::common::cob::patch::Filter;
-
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<PatchId>;
-

-
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
-
pub enum ListCid {
-
    Header,
-
    PatchBrowser,
-
    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,
-
    quit: bool,
-
    mode: Mode,
-
    filter: Filter,
-
    output: Option<Selection>,
-
}
-

-
/// Creates a new application using a tui-realm-application, mounts all
-
/// components and sets focus to a default one.
-
impl App {
-
    pub fn new(context: Context, mode: Mode, filter: Filter) -> Self {
-
        Self {
-
            context,
-
            pages: PageStack::default(),
-
            theme: Theme::default(),
-
            quit: false,
-
            mode,
-
            filter,
-
            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.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(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/patch/realm/select/event.rs
@@ -1,182 +0,0 @@
-
use radicle::patch::PatchId;
-
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 crate::tui_patch::common::PatchOperation;
-

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

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

-
/// 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<radicle::cob::patch::PatchId> {
-
            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<radicle::cob::patch::PatchId> {
-
            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(PatchOperation::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(PatchOperation::Checkout.to_string()),
-
                    ids: vec![id],
-
                    args: vec![],
-
                };
-
                Message::Quit(Some(selection))
-
            }),
-
            Event::Keyboard(KeyEvent {
-
                code: Key::Char('d'),
-
                ..
-
            }) => submit().map(|id| {
-
                let selection = Selection {
-
                    operation: Some(PatchOperation::Diff.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/patch/realm/select/page.rs
@@ -1,177 +0,0 @@
-
use std::collections::HashMap;
-

-
use anyhow::Result;
-

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

-
use radicle_tui as tui;
-

-
use tui::common::cob::patch::Filter;
-
use tui::common::context::Context;
-
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::ui::{layout, subscription};
-
use tui::realm::ViewPage;
-

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

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

-
impl ListView {
-
    pub fn new(subject: Mode, filter: Filter) -> Self {
-
        Self {
-
            active_component: ListCid::PatchBrowser,
-
            subject,
-
            filter,
-
            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::PatchBrowser))?;
-
        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 = common::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 navigation = ui::list_navigation(theme);
-
        let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed();
-

-
        app.remount(Cid::List(ListCid::Header), header, vec![])?;
-

-
        match self.subject {
-
            Mode::Id => {
-
                let patch_browser =
-
                    ui::id_select(theme, context, self.filter.clone(), None).to_boxed();
-
                self.shortcuts = patch_browser.as_ref().shortcuts();
-

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

-
                app.remount(Cid::List(ListCid::PatchBrowser), patch_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::Header))?;
-
        app.umount(&Cid::List(ListCid::PatchBrowser))?;
-
        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<()> {
-
        app.subscribe(
-
            &Cid::List(ListCid::Header),
-
            Sub::new(subscription::navigation_clause(), SubClause::Always),
-
        )?;
-

-
        Ok(())
-
    }
-

-
    fn unsubscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.unsubscribe(
-
            &Cid::List(ListCid::Header),
-
            subscription::navigation_clause(),
-
        )?;
-

-
        Ok(())
-
    }
-
}
deleted bin/commands/patch/realm/select/ui.rs
@@ -1,156 +0,0 @@
-
use std::collections::HashMap;
-

-
use radicle::cob::patch::{Patch, PatchId};
-

-
use radicle_tui as tui;
-

-
use tui::common::cob::patch::Filter;
-
use tui::common::context::Context;
-
use tui::realm::ui::cob::PatchItem;
-
use tui::realm::ui::theme::{style, Theme};
-
use tui::realm::ui::widget::context::Shortcuts;
-
use tui::realm::ui::widget::{Widget, WidgetComponent};
-

-
use tui::realm::ui::widget::container::Tabs;
-
use tui::realm::ui::widget::label::{self};
-
use tuirealm::command::{Cmd, CmdResult};
-
use tuirealm::tui::layout::Rect;
-
use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State};
-

-
use super::super::common;
-
use super::ListCid;
-

-
pub struct IdSelect {
-
    theme: Theme,
-
    browser: Widget<common::ui::PatchBrowser>,
-
}
-

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

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

-
    pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::PatchBrowser,
-
            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<common::ui::PatchBrowser>,
-
}
-

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

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

-
    pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::PatchBrowser,
-
            tui::realm::ui::shortcuts(
-
                &self.theme,
-
                vec![
-
                    tui::realm::ui::shortcut(&self.theme, "enter", "show"),
-
                    tui::realm::ui::shortcut(&self.theme, "c", "checkout"),
-
                    tui::realm::ui::shortcut(&self.theme, "d", "diff"),
-
                    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 list_navigation(theme: &Theme) -> Widget<Tabs> {
-
    tui::realm::ui::tabs(
-
        theme,
-
        vec![label::reversable("Patches").style(style::cyan())],
-
    )
-
}
-

-
pub fn id_select(
-
    theme: &Theme,
-
    context: &Context,
-
    filter: Filter,
-
    selected: Option<(PatchId, Patch)>,
-
) -> Widget<IdSelect> {
-
    let browser = Widget::new(common::ui::PatchBrowser::new(
-
        theme, context, filter, selected,
-
    ));
-

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

-
pub fn operation_select(
-
    theme: &Theme,
-
    context: &Context,
-
    filter: Filter,
-
    selected: Option<(PatchId, Patch)>,
-
) -> Widget<OperationSelect> {
-
    let browser = Widget::new(common::ui::PatchBrowser::new(
-
        theme, context, filter, selected,
-
    ));
-

-
    Widget::new(OperationSelect::new(theme.clone(), browser))
-
}
deleted bin/commands/patch/realm/suite.rs
@@ -1,289 +0,0 @@
-
#[path = "suite/event.rs"]
-
mod event;
-
#[path = "suite/page.rs"]
-
mod page;
-
#[path = "suite/ui.rs"]
-
mod ui;
-

-
use std::hash::Hash;
-

-
use anyhow::Result;
-

-
use radicle::cob::patch::PatchId;
-

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

-
use radicle_tui as tui;
-

-
use tui::common::cob;
-
use tui::common::cob::patch::Filter;
-
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, PatchView};
-

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

-
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
-
pub enum PatchCid {
-
    Header,
-
    Activity,
-
    Files,
-
    Context,
-
    Shortcuts,
-
}
-

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

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum PatchMessage {
-
    Show(PatchId),
-
    Leave,
-
}
-

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum PopupMessage {
-
    Info(String),
-
    Warning(String),
-
    Error(String),
-
    Hide,
-
}
-

-
#[derive(Clone, Default, Debug, Eq, PartialEq)]
-
pub enum Message {
-
    Patch(PatchMessage),
-
    NavigationChanged(u16),
-
    FormSubmitted(String),
-
    Popup(PopupMessage),
-
    #[default]
-
    Tick,
-
    Quit,
-
    Batch(Vec<Message>),
-
}
-

-
#[allow(dead_code)]
-
pub struct App {
-
    context: Context,
-
    pages: PageStack<Cid, Message>,
-
    theme: Theme,
-
    filter: Filter,
-
    quit: bool,
-
}
-

-
/// 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, filter: Filter) -> Self {
-
        Self {
-
            context,
-
            pages: PageStack::default(),
-
            theme: Theme::default(),
-
            filter,
-
            quit: false,
-
        }
-
    }
-

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

-
        Ok(())
-
    }
-

-
    fn view_patch(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        id: PatchId,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let profile = self.context.profile();
-
        let repo = self.context.repository();
-

-
        if let Some(patch) = cob::patch::find(profile, repo, &id)? {
-
            let view = Box::new(PatchView::new(theme.clone(), (id, patch)));
-
            self.pages.push(view, app, &self.context, theme)?;
-

-
            Ok(())
-
        } else {
-
            Err(anyhow::anyhow!(
-
                "Could not mount 'page::PatchView'. Patch not found."
-
            ))
-
        }
-
    }
-

-
    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::Patch(PatchMessage::Show(id)) => {
-
                self.view_patch(app, id, &theme)?;
-
                Ok(None)
-
            }
-
            Message::Patch(PatchMessage::Leave) => {
-
                self.pages.pop(app)?;
-
                Ok(None)
-
            }
-
            Message::Popup(PopupMessage::Info(info)) => {
-
                self.show_info_popup(app, &theme, &info)?;
-
                Ok(None)
-
            }
-
            Message::Popup(PopupMessage::Warning(warning)) => {
-
                self.show_warning_popup(app, &theme, &warning)?;
-
                Ok(None)
-
            }
-
            Message::Popup(PopupMessage::Error(error)) => {
-
                self.show_error_popup(app, &theme, &error)?;
-
                Ok(None)
-
            }
-
            Message::Popup(PopupMessage::Hide) => {
-
                self.hide_popup(app)?;
-
                Ok(None)
-
            }
-
            Message::Quit => {
-
                self.quit = true;
-
                Ok(None)
-
            }
-
            _ => self
-
                .pages
-
                .peek_mut()?
-
                .update(app, &self.context, &theme, message),
-
        }
-
    }
-

-
    fn show_info_popup(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        theme: &Theme,
-
        message: &str,
-
    ) -> Result<()> {
-
        let popup = tui::realm::ui::info(theme, message);
-
        app.remount(Cid::Popup, popup.to_boxed(), vec![])?;
-
        app.active(&Cid::Popup)?;
-

-
        Ok(())
-
    }
-

-
    fn show_warning_popup(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        theme: &Theme,
-
        message: &str,
-
    ) -> Result<()> {
-
        let popup = tui::realm::ui::warning(theme, message);
-
        app.remount(Cid::Popup, popup.to_boxed(), vec![])?;
-
        app.active(&Cid::Popup)?;
-

-
        Ok(())
-
    }
-

-
    fn show_error_popup(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        theme: &Theme,
-
        message: &str,
-
    ) -> Result<()> {
-
        let popup = tui::realm::ui::error(theme, message);
-
        app.remount(Cid::Popup, popup.to_boxed(), vec![])?;
-
        app.active(&Cid::Popup)?;
-

-
        Ok(())
-
    }
-

-
    fn hide_popup(&mut self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.blur()?;
-
        app.umount(&Cid::Popup)?;
-

-
        Ok(())
-
    }
-
}
-

-
impl Tui<Cid, Message, ()> 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(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);
-
        }
-

-
        if app.mounted(&Cid::Popup) {
-
            app.view(&Cid::Popup, frame, frame.size());
-
        }
-
    }
-

-
    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<()>> {
-
        if self.quit {
-
            return Some(Exit { value: None });
-
        }
-
        None
-
    }
-
}
deleted bin/commands/patch/realm/suite/event.rs
@@ -1,140 +0,0 @@
-
use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection};
-
use tuirealm::event::{Event, Key, KeyEvent};
-
use tuirealm::{MockComponent, NoUserEvent, State, StateValue};
-

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

-
use super::super::common;
-
use super::{ui, Message, PatchMessage, PopupMessage};
-

-
/// 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,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<AppHeader> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Tab, .. }) => {
-
                match self.perform(Cmd::Move(MoveDirection::Right)) {
-
                    CmdResult::Changed(State::One(StateValue::U16(index))) => {
-
                        Some(Message::NavigationChanged(index))
-
                    }
-
                    _ => None,
-
                }
-
            }
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<common::ui::PatchBrowser> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        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, ..
-
            }) => match self.perform(Cmd::Submit) {
-
                CmdResult::Submit(state) => {
-
                    let selected = ItemState::try_from(state).ok()?.selected()?;
-
                    let item = self.items().get(selected)?;
-
                    Some(Message::Patch(PatchMessage::Show(item.id().to_owned())))
-
                }
-
                _ => None,
-
            },
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<ui::Activity> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Esc, .. }) => {
-
                Some(Message::Patch(PatchMessage::Leave))
-
            }
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<ui::Files> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Esc, .. }) => {
-
                Some(Message::Patch(PatchMessage::Leave))
-
            }
-
            _ => None,
-
        }
-
    }
-
}
-

-
impl tuirealm::Component<Message, NoUserEvent> for Widget<Popup> {
-
    fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
-
        match event {
-
            Event::Keyboard(KeyEvent { code: Key::Esc, .. }) => {
-
                Some(Message::Popup(PopupMessage::Hide))
-
            }
-
            _ => 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/patch/realm/suite/page.rs
@@ -1,346 +0,0 @@
-
use std::collections::HashMap;
-

-
use anyhow::Result;
-

-
use radicle::cob::patch::{Patch, PatchId};
-

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

-
use radicle_tui as tui;
-

-
use tui::common::cob::patch::Filter;
-
use tui::common::context::Context;
-
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::ui::{layout, subscription};
-
use tui::realm::ViewPage;
-

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

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

-
impl ListView {
-
    pub fn new(theme: Theme, filter: Filter) -> Self {
-
        let shortcuts = Self::build_shortcuts(&theme);
-
        Self {
-
            active_component: ListCid::PatchBrowser,
-
            shortcuts,
-
            filter,
-
        }
-
    }
-

-
    fn build_shortcuts(theme: &Theme) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::PatchBrowser,
-
            tui::realm::ui::shortcuts(
-
                theme,
-
                vec![
-
                    tui::realm::ui::shortcut(theme, "tab", "section"),
-
                    tui::realm::ui::shortcut(theme, "↑/↓", "navigate"),
-
                    tui::realm::ui::shortcut(theme, "enter", "show"),
-
                    tui::realm::ui::shortcut(theme, "q", "quit"),
-
                ],
-
            ),
-
        )]
-
        .iter()
-
        .cloned()
-
        .collect()
-
    }
-

-
    fn update_context(
-
        &self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let state = app.state(&Cid::List(ListCid::PatchBrowser))?;
-
        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, 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 navigation = ui::list_navigation(theme);
-
        let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed();
-
        let patch_browser = ui::patches(theme, context, self.filter.clone(), None).to_boxed();
-

-
        app.remount(Cid::List(ListCid::Header), header, vec![])?;
-
        app.remount(Cid::List(ListCid::PatchBrowser), patch_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::Header))?;
-
        app.umount(&Cid::List(ListCid::PatchBrowser))?;
-
        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::full_page(area, context_h, shortcuts_h);
-

-
        app.view(&Cid::List(ListCid::Header), frame, layout.navigation);
-
        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<()> {
-
        app.subscribe(
-
            &Cid::List(ListCid::Header),
-
            Sub::new(subscription::navigation_clause(), SubClause::Always),
-
        )?;
-

-
        Ok(())
-
    }
-

-
    fn unsubscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.unsubscribe(
-
            &Cid::List(ListCid::Header),
-
            subscription::navigation_clause(),
-
        )?;
-

-
        Ok(())
-
    }
-
}
-

-
///
-
/// Patch detail page
-
///
-
pub struct PatchView {
-
    active_component: PatchCid,
-
    patch: (PatchId, Patch),
-
    shortcuts: HashMap<PatchCid, Widget<Shortcuts>>,
-
}
-

-
impl PatchView {
-
    pub fn new(theme: Theme, patch: (PatchId, Patch)) -> Self {
-
        let shortcuts = Self::build_shortcuts(&theme);
-
        PatchView {
-
            active_component: PatchCid::Activity,
-
            patch,
-
            shortcuts,
-
        }
-
    }
-

-
    fn build_shortcuts(theme: &Theme) -> HashMap<PatchCid, Widget<Shortcuts>> {
-
        [
-
            (
-
                PatchCid::Activity,
-
                tui::realm::ui::shortcuts(
-
                    theme,
-
                    vec![
-
                        tui::realm::ui::shortcut(theme, "esc", "back"),
-
                        tui::realm::ui::shortcut(theme, "tab", "section"),
-
                        tui::realm::ui::shortcut(theme, "q", "quit"),
-
                    ],
-
                ),
-
            ),
-
            (
-
                PatchCid::Files,
-
                tui::realm::ui::shortcuts(
-
                    theme,
-
                    vec![
-
                        tui::realm::ui::shortcut(theme, "esc", "back"),
-
                        tui::realm::ui::shortcut(theme, "tab", "section"),
-
                        tui::realm::ui::shortcut(theme, "q", "quit"),
-
                    ],
-
                ),
-
            ),
-
        ]
-
        .iter()
-
        .cloned()
-
        .collect()
-
    }
-

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

-
impl ViewPage<Cid, Message> for PatchView {
-
    fn mount(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let navigation = ui::navigation(theme);
-
        let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed();
-
        let activity = ui::activity(theme).to_boxed();
-
        let files = ui::files(theme).to_boxed();
-
        let context = ui::context(context, theme, self.patch.clone()).to_boxed();
-

-
        app.remount(Cid::Patch(PatchCid::Header), header, vec![])?;
-
        app.remount(Cid::Patch(PatchCid::Activity), activity, vec![])?;
-
        app.remount(Cid::Patch(PatchCid::Files), files, vec![])?;
-
        app.remount(Cid::Patch(PatchCid::Context), context, vec![])?;
-

-
        let active_component = Cid::Patch(self.active_component.clone());
-
        app.active(&active_component)?;
-
        self.update_shortcuts(app, self.active_component.clone())?;
-

-
        Ok(())
-
    }
-

-
    fn unmount(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.umount(&Cid::Patch(PatchCid::Header))?;
-
        app.umount(&Cid::Patch(PatchCid::Activity))?;
-
        app.umount(&Cid::Patch(PatchCid::Files))?;
-
        app.umount(&Cid::Patch(PatchCid::Context))?;
-
        app.umount(&Cid::Patch(PatchCid::Shortcuts))?;
-
        Ok(())
-
    }
-

-
    fn update(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        _context: &Context,
-
        _theme: &Theme,
-
        message: Message,
-
    ) -> Result<Option<Message>> {
-
        if let Message::NavigationChanged(index) = message {
-
            self.active_component = PatchCid::from(index as usize);
-

-
            let active_component = Cid::Patch(self.active_component.clone());
-
            app.active(&active_component)?;
-
            self.update_shortcuts(app, self.active_component.clone())?;
-
        }
-

-
        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::full_page(area, context_h, shortcuts_h);
-

-
        app.view(&Cid::Patch(PatchCid::Header), frame, layout.navigation);
-
        app.view(
-
            &Cid::Patch(self.active_component.clone()),
-
            frame,
-
            layout.component,
-
        );
-
        app.view(&Cid::Patch(PatchCid::Context), frame, layout.context);
-
        app.view(&Cid::Patch(PatchCid::Shortcuts), frame, layout.shortcuts);
-
    }
-

-
    fn subscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.subscribe(
-
            &Cid::Patch(PatchCid::Header),
-
            Sub::new(subscription::navigation_clause(), SubClause::Always),
-
        )?;
-

-
        Ok(())
-
    }
-

-
    fn unsubscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
-
        app.unsubscribe(
-
            &Cid::Patch(PatchCid::Header),
-
            subscription::navigation_clause(),
-
        )?;
-

-
        Ok(())
-
    }
-
}
-

-
impl From<usize> for PatchCid {
-
    fn from(index: usize) -> Self {
-
        match index {
-
            0 => PatchCid::Activity,
-
            1 => PatchCid::Files,
-
            _ => PatchCid::Activity,
-
        }
-
    }
-
}
deleted bin/commands/patch/realm/suite/ui.rs
@@ -1,171 +0,0 @@
-
use radicle::cob::patch::{Patch, PatchId};
-
use radicle::node::AliasStore;
-

-
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::patch::Filter;
-
use tui::common::context::Context;
-
use tui::realm::ui::cob;
-
use tui::realm::ui::layout;
-
use tui::realm::ui::theme::{style, Theme};
-
use tui::realm::ui::widget::{Widget, WidgetComponent};
-

-
use tui::realm::ui::widget::container::Tabs;
-
use tui::realm::ui::widget::context::{ContextBar, Progress};
-
use tui::realm::ui::widget::label::{self, Label};
-

-
use super::super::common;
-

-
pub struct Activity {
-
    label: Widget<Label>,
-
}
-

-
impl Activity {
-
    pub fn new(label: Widget<Label>) -> Self {
-
        Self { label }
-
    }
-
}
-

-
impl WidgetComponent for Activity {
-
    fn view(&mut self, _properties: &Props, frame: &mut Frame, area: Rect) {
-
        let label_w = self
-
            .label
-
            .query(Attribute::Width)
-
            .unwrap_or(AttrValue::Size(1))
-
            .unwrap_size();
-

-
        self.label
-
            .view(frame, layout::centered_label(label_w, area));
-
    }
-

-
    fn state(&self) -> State {
-
        State::None
-
    }
-

-
    fn perform(&mut self, _properties: &Props, _cmd: Cmd) -> CmdResult {
-
        CmdResult::None
-
    }
-
}
-

-
pub struct Files {
-
    label: Widget<Label>,
-
}
-

-
impl Files {
-
    pub fn new(label: Widget<Label>) -> Self {
-
        Self { label }
-
    }
-
}
-

-
impl WidgetComponent for Files {
-
    fn view(&mut self, _properties: &Props, frame: &mut Frame, area: Rect) {
-
        let label_w = self
-
            .label
-
            .query(Attribute::Width)
-
            .unwrap_or(AttrValue::Size(1))
-
            .unwrap_size();
-

-
        self.label
-
            .view(frame, layout::centered_label(label_w, area));
-
    }
-

-
    fn state(&self) -> State {
-
        State::None
-
    }
-

-
    fn perform(&mut self, _properties: &Props, _cmd: Cmd) -> CmdResult {
-
        CmdResult::None
-
    }
-
}
-

-
pub fn list_navigation(theme: &Theme) -> Widget<Tabs> {
-
    tui::realm::ui::tabs(
-
        theme,
-
        vec![label::reversable("Patches").style(style::magenta())],
-
    )
-
}
-

-
pub fn navigation(theme: &Theme) -> Widget<Tabs> {
-
    tui::realm::ui::tabs(
-
        theme,
-
        vec![
-
            label::reversable("Activity").style(style::magenta()),
-
            label::reversable("Files").style(style::magenta()),
-
        ],
-
    )
-
}
-

-
pub fn patches(
-
    theme: &Theme,
-
    context: &Context,
-
    filter: Filter,
-
    selected: Option<(PatchId, Patch)>,
-
) -> Widget<common::ui::PatchBrowser> {
-
    Widget::new(common::ui::PatchBrowser::new(
-
        theme, context, filter, selected,
-
    ))
-
}
-

-
pub fn activity(_theme: &Theme) -> Widget<Activity> {
-
    let not_implemented = label::default("not implemented").style(style::reset());
-
    let activity = Activity::new(not_implemented);
-

-
    Widget::new(activity)
-
}
-

-
pub fn files(_theme: &Theme) -> Widget<Files> {
-
    let not_implemented = label::default("not implemented").style(style::reset());
-
    let files = Files::new(not_implemented);
-

-
    Widget::new(files)
-
}
-

-
pub fn context(context: &Context, theme: &Theme, patch: (PatchId, Patch)) -> Widget<ContextBar> {
-
    let (id, patch) = patch;
-
    let (_, rev) = patch.latest();
-
    let is_you = *patch.author().id() == context.profile().did();
-

-
    let id = cob::format::cob(&id);
-
    let title = patch.title();
-
    let author = patch.author().id();
-
    let alias = context.profile().aliases().alias(author);
-
    let author = cob::format_author(author, &alias, is_you);
-
    let comments = rev.discussion().len();
-

-
    tui::realm::ui::widget::context::bar(theme, "Patch", &id, title, &author, &comments.to_string())
-
}
-

-
pub fn browse_context(context: &Context, theme: &Theme, progress: Progress) -> Widget<ContextBar> {
-
    use radicle::cob::patch::State;
-

-
    let mut draft = 0;
-
    let mut open = 0;
-
    let mut archived = 0;
-
    let mut merged = 0;
-

-
    let patches = context.patches().as_ref().unwrap();
-
    for (_, patch) in patches {
-
        match patch.state() {
-
            State::Draft => draft += 1,
-
            State::Open { conflicts: _ } => open += 1,
-
            State::Archived => archived += 1,
-
            State::Merged {
-
                commit: _,
-
                revision: _,
-
            } => merged += 1,
-
        }
-
    }
-

-
    tui::realm::ui::widget::context::bar(
-
        theme,
-
        "Browse",
-
        "",
-
        "",
-
        &format!("{draft} draft | {open} open | {archived} archived | {merged} merged"),
-
        &progress.to_string(),
-
    )
-
}
added bin/commands/patch/select.rs
@@ -0,0 +1,160 @@
+
#[path = "select/ui.rs"]
+
mod ui;
+

+
use anyhow::Result;
+

+
use radicle::patch::PatchId;
+
use radicle::storage::git::Repository;
+
use radicle::Profile;
+

+
use radicle_tui as tui;
+

+
use tui::common::cob::patch::{self, Filter};
+
use tui::flux::store;
+
use tui::flux::task::{self, Interrupted};
+
use tui::flux::ui::items::PatchItem;
+
use tui::flux::ui::Frontend;
+
use tui::Exit;
+

+
use ui::ListPage;
+

+
use super::common::Mode;
+

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

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

+
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 {
+
    patches: Vec<PatchItem>,
+
    mode: Mode,
+
    search: store::StateValue<String>,
+
    ui: UIState,
+
}
+

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

+
    fn try_from(context: &Context) -> Result<Self, Self::Error> {
+
        let patches = patch::all(&context.profile, &context.repository)?;
+

+
        // Convert into UI items
+
        let mut items = vec![];
+
        for patch in patches {
+
            if let Ok(item) = PatchItem::new(&context.profile, &context.repository, patch.clone()) {
+
                items.push(item);
+
            }
+
        }
+

+
        Ok(Self {
+
            patches: items,
+
            mode: context.mode.clone(),
+
            search: store::StateValue::new(context.filter.to_string()),
+
            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/patch/select/ui.rs
@@ -0,0 +1,920 @@
+
use std::collections::HashMap;
+
use std::str::FromStr;
+
use std::vec;
+

+
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::patch::{self, Status};
+

+
use radicle_tui as tui;
+

+
use tui::flux::ui::items::{PatchItem, PatchItemFilter};
+
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_patch::common::Mode;
+
use crate::tui_patch::common::PatchOperation;
+

+
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
+
    patches: Patches,
+
    /// 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),
+
            patches: Patches::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),
+
        }
+
        .move_with_state(state)
+
    }
+

+
    fn move_with_state(self, state: &State) -> Self
+
    where
+
        Self: Sized,
+
    {
+
        ListPage {
+
            patches: self.patches.move_with_state(state),
+
            search: self.search.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);
+
                }
+
                _ => {
+
                    <Patches as Widget<State, Action>>::handle_key_event(&mut self.patches, 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 {
+
                Mode::Id => vec![
+
                    Shortcut::new("enter", "select"),
+
                    Shortcut::new("/", "search"),
+
                ],
+
                Mode::Operation => vec![
+
                    Shortcut::new("enter", "show"),
+
                    Shortcut::new("c", "checkout"),
+
                    Shortcut::new("d", "diff"),
+
                    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.patches.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.patches.render::<B>(frame, layout.component, ());
+
        }
+

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

+
struct PatchesProps {
+
    mode: Mode,
+
    patches: Vec<PatchItem>,
+
    search: String,
+
    stats: HashMap<String, usize>,
+
    widths: [Constraint; 9],
+
    cutoff: usize,
+
    cutoff_after: usize,
+
    focus: bool,
+
    page_size: usize,
+
    show_search: bool,
+
}
+

+
impl From<&State> for PatchesProps {
+
    fn from(state: &State) -> Self {
+
        let mut draft = 0;
+
        let mut open = 0;
+
        let mut archived = 0;
+
        let mut merged = 0;
+

+
        let filter = PatchItemFilter::from_str(&state.search.read()).unwrap_or_default();
+
        let mut patches = state
+
            .patches
+
            .clone()
+
            .into_iter()
+
            .filter(|patch| filter.matches(patch))
+
            .collect::<Vec<_>>();
+

+
        // Apply sorting
+
        patches.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
+

+
        for patch in &patches {
+
            match patch.state {
+
                patch::State::Draft => draft += 1,
+
                patch::State::Open { conflicts: _ } => open += 1,
+
                patch::State::Archived => archived += 1,
+
                patch::State::Merged {
+
                    commit: _,
+
                    revision: _,
+
                } => merged += 1,
+
            }
+
        }
+

+
        let stats = HashMap::from([
+
            ("Draft".to_string(), draft),
+
            ("Open".to_string(), open),
+
            ("Archived".to_string(), archived),
+
            ("Merged".to_string(), merged),
+
        ]);
+

+
        Self {
+
            mode: state.mode.clone(),
+
            patches,
+
            search: state.search.read(),
+
            widths: [
+
                Constraint::Length(3),
+
                Constraint::Length(8),
+
                Constraint::Fill(1),
+
                Constraint::Length(16),
+
                Constraint::Length(16),
+
                Constraint::Length(8),
+
                Constraint::Length(6),
+
                Constraint::Length(6),
+
                Constraint::Length(16),
+
            ],
+
            cutoff: 150,
+
            cutoff_after: 5,
+
            focus: false,
+
            stats,
+
            page_size: state.ui.page_size,
+
            show_search: state.ui.show_search,
+
        }
+
    }
+
}
+

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

+
impl Widget<State, Action> for Patches {
+
    fn new(state: &State, action_tx: UnboundedSender<Action>) -> Self {
+
        Self {
+
            action_tx: action_tx.clone(),
+
            props: PatchesProps::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 = PatchesProps::from(state);
+
        let mut table = self.table.move_with_state(state);
+

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

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

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

+
    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.patches.len());
+
            }
+
            Key::PageUp => {
+
                self.table.prev_page(self.props.page_size);
+
            }
+
            Key::PageDown => {
+
                self.table
+
                    .next_page(self.props.patches.len(), self.props.page_size);
+
            }
+
            Key::Home => {
+
                self.table.begin();
+
            }
+
            Key::End => {
+
                self.table.end(self.props.patches.len());
+
            }
+
            Key::Char('\n') => {
+
                let operation = match self.props.mode {
+
                    Mode::Operation => Some(PatchOperation::Show.to_string()),
+
                    Mode::Id => None,
+
                };
+

+
                self.table
+
                    .selected()
+
                    .and_then(|selected| self.props.patches.get(selected))
+
                    .and_then(|patch| {
+
                        self.action_tx
+
                            .send(Action::Exit {
+
                                selection: Some(Selection {
+
                                    operation,
+
                                    ids: vec![patch.id],
+
                                    args: vec![],
+
                                }),
+
                            })
+
                            .ok()
+
                    });
+
            }
+
            Key::Char('c') => {
+
                self.table
+
                    .selected()
+
                    .and_then(|selected| self.props.patches.get(selected))
+
                    .and_then(|patch| {
+
                        self.action_tx
+
                            .send(Action::Exit {
+
                                selection: Some(Selection {
+
                                    operation: Some(PatchOperation::Checkout.to_string()),
+
                                    ids: vec![patch.id],
+
                                    args: vec![],
+
                                }),
+
                            })
+
                            .ok()
+
                    });
+
            }
+
            Key::Char('d') => {
+
                self.table
+
                    .selected()
+
                    .and_then(|selected| self.props.patches.get(selected))
+
                    .and_then(|patch| {
+
                        self.action_tx
+
                            .send(Action::Exit {
+
                                selection: Some(Selection {
+
                                    operation: Some(PatchOperation::Diff.to_string()),
+
                                    ids: vec![patch.id],
+
                                    args: vec![],
+
                                }),
+
                            })
+
                            .ok()
+
                    });
+
            }
+
            _ => {}
+
        }
+
    }
+
}
+

+
impl Patches {
+
    fn render_header<B: Backend>(&self, frame: &mut ratatui::Frame, area: Rect) {
+
        self.header.render::<B>(
+
            frame,
+
            area,
+
            HeaderProps {
+
                cells: [
+
                    String::from(" ● ").into(),
+
                    String::from("ID").into(),
+
                    String::from("Title").into(),
+
                    String::from("Author").into(),
+
                    String::from("").into(),
+
                    String::from("Head").into(),
+
                    String::from("+").into(),
+
                    String::from("- ").into(),
+
                    String::from("Updated").into(),
+
                ],
+
                widths: self.props.widths,
+
                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) {
+
        self.table.render::<B>(
+
            frame,
+
            area,
+
            TableProps {
+
                items: self.props.patches.to_vec(),
+
                has_header: true,
+
                has_footer: !self.props.show_search,
+
                widths: self.props.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 filter = PatchItemFilter::from_str(&self.props.search).unwrap_or_default();
+

+
        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 draft = Line::from(
+
            [
+
                span::default(self.props.stats.get("Draft").unwrap_or(&0).to_string()).dim(),
+
                span::default(" Draft".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let open = Line::from(
+
            [
+
                span::positive(self.props.stats.get("Open").unwrap_or(&0).to_string()).dim(),
+
                span::default(" Open".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let merged = Line::from(
+
            [
+
                span::default(self.props.stats.get("Merged").unwrap_or(&0).to_string())
+
                    .magenta()
+
                    .dim(),
+
                span::default(" Merged".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let archived = Line::from(
+
            [
+
                span::default(self.props.stats.get("Archived").unwrap_or(&0).to_string())
+
                    .yellow()
+
                    .dim(),
+
                span::default(" Archived".to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

+
        let sum = Line::from(
+
            [
+
                span::default("Σ ".to_string()).dim(),
+
                span::default(self.props.patches.len().to_string()).dim(),
+
            ]
+
            .to_vec(),
+
        );
+

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

+
        match filter.status() {
+
            Some(state) => {
+
                let block = match state {
+
                    Status::Draft => draft,
+
                    Status::Open => open,
+
                    Status::Merged => merged,
+
                    Status::Archived => archived,
+
                };
+

+
                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(),
+
                            draft.clone().into(),
+
                            open.clone().into(),
+
                            merged.clone().into(),
+
                            archived.clone().into(),
+
                            sum.clone().into(),
+
                            progress.clone().into(),
+
                        ],
+
                        widths: [
+
                            Constraint::Fill(1),
+
                            Constraint::Min(draft.width() as u16),
+
                            Constraint::Min(open.width() as u16),
+
                            Constraint::Min(merged.width() as u16),
+
                            Constraint::Min(archived.width() as u16),
+
                            Constraint::Min(sum.width() as u16),
+
                            Constraint::Min(4),
+
                        ],
+
                        focus: self.props.focus,
+
                        cutoff: self.props.cutoff,
+
                        cutoff_after: self.props.cutoff_after,
+
                    },
+
                );
+
            }
+
        };
+
    }
+
}
+

+
impl Render<()> for Patches {
+
    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 patch (if --mode id)").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "enter")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Show patch").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "c")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Checkout patch").gray().dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "d")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("Show patch diff").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:authored | authors:[<did>, <did>] | <search>")
+
                            .gray()
+
                            .dim(),
+
                    ]
+
                    .to_vec(),
+
                ),
+
                Line::from(
+
                    [
+
                        Span::raw(format!("{key:>10}", key = "Example")).gray(),
+
                        Span::raw(" "),
+
                        Span::raw("is:open is:authored improve").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));
+
        }
+
    }
+
}