Radish alpha
r
Radicle terminal user interface
Radicle
Git (anonymous pull)
Log in to clone via SSH
patch: Initialize w/ unified command
Erik Kundt committed 2 years ago
commit 74940ca7bff851dee2aa1e1a7fe8ddb26be21ab1
parent bfc6909cfaf1ca439aabc205f08741c37b56bde5
19 files changed +1250 -1548
modified Cargo.toml
@@ -7,7 +7,7 @@ edition = "2021"
build = "build.rs"

[[bin]]
-
name = "radicle-tui"
+
name = "rad-tui"
path = "bin/main.rs"

[dependencies]
added bin/commands.rs
@@ -0,0 +1,4 @@
+
#[path = "commands/help.rs"]
+
pub mod tui_help;
+
#[path = "commands/patch.rs"]
+
pub mod tui_patch;
added bin/commands/help.rs
@@ -0,0 +1,68 @@
+
use std::ffi::OsString;
+

+
use radicle_term as term;
+

+
use crate::terminal::args::{Args, Error, Help};
+
use crate::terminal::Context;
+

+
use super::*;
+

+
pub const HELP: Help = Help {
+
    name: "help",
+
    description: "TUI help",
+
    version: env!("CARGO_PKG_VERSION"),
+
    usage: "Usage: rad-tui help [--help]",
+
};
+

+
const COMMANDS: &[Help] = &[tui_help::HELP, tui_patch::HELP];
+

+
#[derive(Default)]
+
pub struct Options {}
+

+
impl Args for Options {
+
    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
+
        let mut parser = lexopt::Parser::from_args(args);
+

+
        if let Some(arg) = parser.next()? {
+
            return Err(anyhow::anyhow!(arg.unexpected()));
+
        }
+
        Err(Error::HelpManual { name: "rad-tui" }.into())
+
    }
+
}
+

+
pub fn run(_options: Options, ctx: impl Context) -> anyhow::Result<()> {
+
    term::print("Usage: rad-tui <command> [--help]");
+

+
    if let Err(e) = ctx.profile() {
+
        term::blank();
+
        match e.downcast_ref() {
+
            Some(Error::WithHint { err, hint }) => {
+
                term::print(term::format::yellow(err));
+
                term::print(term::format::yellow(hint));
+
            }
+
            Some(e) => {
+
                term::error(e);
+
            }
+
            None => {
+
                term::error(e);
+
            }
+
        }
+
        term::blank();
+
    }
+

+
    term::print("Common `rad-tui` commands used in various situations:");
+
    term::blank();
+

+
    for help in COMMANDS {
+
        term::info!(
+
            "\t{} {}",
+
            term::format::bold(format!("{:-12}", help.name)),
+
            term::format::dim(help.description)
+
        );
+
    }
+
    term::blank();
+
    term::print("See `rad-tui <command> --help` to learn about a specific command.");
+
    term::blank();
+

+
    Ok(())
+
}
modified bin/commands/patch.rs
@@ -1,397 +1,67 @@
-
pub mod event;
-
pub mod page;
-
pub mod subscription;
+
#[path = "patch/suite.rs"]
+
mod suite;

-
use anyhow::Result;
+
use std::ffi::OsString;

-
use radicle::cob::issue::IssueId;
-
use radicle::cob::patch::PatchId;
-
use radicle::identity::{Id, Project};
-
use radicle::prelude::Signer;
-
use radicle::profile::Profile;
+
use anyhow::anyhow;

-
use radicle_tui::ui::widget;
-
use tuirealm::application::PollStrategy;
-
use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause};
+
use crate::terminal;
+
use crate::terminal::args::{Args, Error, Help};

-
use radicle_tui::ui::context::Context;
-
use radicle_tui::ui::theme::{self, Theme};
-
use radicle_tui::Tui;
-
use radicle_tui::{cob, ui};
+
pub const HELP: Help = Help {
+
    name: "patch",
+
    description: "Terminal interfaces for patches",
+
    version: env!("CARGO_PKG_VERSION"),
+
    usage: r#"
+
Usage

-
use page::{HomeView, PatchView};
+
    rad-tui patch

-
use self::page::{IssuePage, PageStack};
+
General options

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

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

-
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
-
pub enum IssueCid {
-
    Header,
-
    List,
-
    Details,
-
    Context,
-
    Form,
-
    Shortcuts,
-
}
-

-
/// All component ids known to this application.
-
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
-
pub enum Cid {
-
    Home(HomeCid),
-
    Issue(IssueCid),
-
    Patch(PatchCid),
-
    GlobalListener,
-
    Popup,
-
}
-

-
/// Messages handled by this application.
-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum HomeMessage {
-
    RefreshIssues(Option<IssueId>),
-
}
-

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum IssueCobMessage {
-
    Create {
-
        title: String,
-
        tags: String,
-
        assignees: String,
-
        description: String,
-
    },
-
}
-

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum IssueMessage {
-
    Show(Option<IssueId>),
-
    Changed(IssueId),
-
    Focus(IssueCid),
-
    Created(IssueId),
-
    Cob(IssueCobMessage),
-
    OpenForm,
-
    HideForm,
-
    Leave(Option<IssueId>),
-
}
-

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

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum PopupMessage {
-
    Info(String),
-
    Warning(String),
-
    Error(String),
-
    Hide,
+
#[allow(dead_code)]
+
pub struct Options {
+
    op: Operation,
}

-
#[derive(Clone, Debug, Eq, PartialEq)]
-
pub enum Message {
-
    Home(HomeMessage),
-
    Issue(IssueMessage),
-
    Patch(PatchMessage),
-
    NavigationChanged(u16),
-
    FormSubmitted(String),
-
    Popup(PopupMessage),
-
    Tick,
-
    Quit,
-
    Batch(Vec<Message>),
+
pub enum Operation {
+
    Suite,
}

-
#[allow(dead_code)]
-
pub struct App {
-
    context: Context,
-
    pages: PageStack,
-
    theme: Theme,
-
    quit: bool,
+
#[derive(Default, PartialEq, Eq)]
+
pub enum OperationName {
+
    #[default]
+
    Suite,
}

-
/// Creates a new application using a tui-realm-application, mounts all
-
/// components and sets focus to a default one.
-
impl App {
-
    pub fn new(profile: Profile, id: Id, project: Project, signer: Box<dyn Signer>) -> Self {
-
        Self {
-
            context: Context::new(profile, id, project, signer),
-
            pages: PageStack::default(),
-
            theme: theme::default_dark(),
-
            quit: false,
-
        }
-
    }
-

-
    fn view_home(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let home = Box::new(HomeView::new(theme.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 repo = self.context.repository();
-

-
        if let Some(patch) = cob::patch::find(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 view_issue(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        id: Option<IssueId>,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let repo = self.context.repository();
-
        match id {
-
            Some(id) => {
-
                if let Some(issue) = cob::issue::find(repo, &id)? {
-
                    let view = Box::new(IssuePage::new(&self.context, theme, Some((id, issue))));
-
                    self.pages.push(view, app, &self.context, theme)?;
-

-
                    Ok(())
-
                } else {
-
                    Err(anyhow::anyhow!(
-
                        "Could not mount 'page::IssueView'. Issue not found."
-
                    ))
-
                }
-
            }
-
            None => {
-
                let view = Box::new(IssuePage::new(&self.context, theme, None));
-
                self.pages.push(view, app, &self.context, theme)?;
-

-
                Ok(())
-
            }
-
        }
-
    }
-

-
    fn process(
-
        &mut self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        message: Message,
-
    ) -> Result<Option<Message>> {
-
        let theme = theme::default_dark();
-
        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::Issue(IssueMessage::Cob(IssueCobMessage::Create {
-
                title,
-
                tags,
-
                assignees,
-
                description,
-
            })) => match self.create_issue(title, description, tags, assignees) {
-
                Ok(id) => {
-
                    self.context.reload();
+
impl Args for Options {
+
    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
+
        use lexopt::prelude::*;

-
                    Ok(Some(Message::Batch(vec![
-
                        Message::Issue(IssueMessage::HideForm),
-
                        Message::Issue(IssueMessage::Created(id)),
-
                    ])))
-
                }
-
                Err(err) => {
-
                    let error = format!("{:?}", err);
-
                    self.show_error_popup(app, &theme, &error)?;
+
        let mut parser = lexopt::Parser::from_args(args);
+
        let op: Option<OperationName> = None;

-
                    Ok(None)
+
        #[allow(clippy::never_loop)]
+
        while let Some(arg) = parser.next()? {
+
            match arg {
+
                Long("help") | Short('h') => {
+
                    return Err(Error::Help.into());
                }
-
            },
-
            Message::Issue(IssueMessage::Show(id)) => {
-
                self.view_issue(app, id, &theme)?;
-
                Ok(None)
-
            }
-
            Message::Issue(IssueMessage::Leave(id)) => {
-
                self.pages.pop(app)?;
-
                Ok(Some(Message::Home(HomeMessage::RefreshIssues(id))))
-
            }
-
            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)
+
                _ => return Err(anyhow!(arg.unexpected())),
            }
-
            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 = widget::common::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 = widget::common::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 = widget::common::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(())
-
    }
-

-
    fn create_issue(
-
        &mut self,
-
        title: String,
-
        description: String,
-
        labels: String,
-
        assignees: String,
-
    ) -> Result<IssueId> {
-
        let repository = self.context.repository();
-
        let signer = self.context.signer();
-

-
        let labels = cob::parse_labels(labels)?;
-
        let assignees = cob::parse_assignees(assignees)?;
-

-
        cob::issue::create(
-
            repository,
-
            signer,
-
            title,
-
            description,
-
            labels.as_slice(),
-
            assignees.as_slice(),
-
        )
+
        let op = match op.unwrap_or_default() {
+
            OperationName::Suite => Operation::Suite,
+
        };
+
        Ok((Options { op }, vec![]))
    }
}

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

-
        // Add global key listener and subscribe to key events
-
        let global = ui::widget::common::global_listener().to_boxed();
-
        app.mount(
-
            Cid::GlobalListener,
-
            global,
-
            vec![Sub::new(subscription::global_clause(), 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 quit(&self) -> bool {
-
        self.quit
-
    }
+
pub fn run(_options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
+
    Ok(())
}
deleted bin/commands/patch/app.rs
@@ -1,274 +0,0 @@
-
mod event;
-
mod page;
-
mod ui;
-

-
use std::hash::Hash;
-

-
use anyhow::Result;
-

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

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

-
use radicle_tui as tui;
-

-
use radicle_tui::cob;
-
use radicle_tui::context::Context;
-
use radicle_tui::ui::subscription;
-
use radicle_tui::ui::theme::{self, Theme};
-
use radicle_tui::PageStack;
-
use radicle_tui::Tui;
-

-
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,
-
    quit: bool,
-
}
-

-
/// 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) -> Self {
-
        Self {
-
            context,
-
            pages: PageStack::default(),
-
            theme: theme::default_dark(),
-
            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.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 repo = self.context.repository();
-

-
        if let Some(patch) = cob::patch::find(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_dark();
-
        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::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::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::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::ui::global_listener().to_boxed();
-
        app.mount(
-
            Cid::GlobalListener,
-
            global,
-
            vec![Sub::new(subscription::global_clause(), 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 quit(&self) -> bool {
-
        self.quit
-
    }
-
}
deleted bin/commands/patch/app/event.rs
@@ -1,139 +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::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer, Popup};
-
use radicle_tui::ui::widget::context::{ContextBar, Shortcuts};
-
use radicle_tui::ui::widget::list::PropertyList;
-

-
use radicle_tui::ui::widget::Widget;
-

-
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<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, ..
-
            }) => {
-
                let result = self.perform(Cmd::Submit);
-
                match result {
-
                    CmdResult::Submit(State::One(StateValue::Usize(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/app/page.rs
@@ -1,326 +0,0 @@
-
use std::collections::HashMap;
-

-
use anyhow::Result;
-

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

-
use tuirealm::{Frame, NoUserEvent, State, StateValue, Sub, SubClause};
-

-
use radicle_tui as tui;
-

-
use tui::context::Context;
-
use tui::ui::theme::Theme;
-
use tui::ui::widget::context::{Progress, Shortcuts};
-
use tui::ui::widget::Widget;
-
use tui::ui::{layout, subscription};
-
use tui::ViewPage;
-

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

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

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

-
    fn build_shortcuts(theme: &Theme) -> HashMap<ListCid, Widget<Shortcuts>> {
-
        [(
-
            ListCid::PatchBrowser,
-
            tui::ui::shortcuts(
-
                theme,
-
                vec![
-
                    tui::ui::shortcut(theme, "tab", "section"),
-
                    tui::ui::shortcut(theme, "↑/↓", "navigate"),
-
                    tui::ui::shortcut(theme, "enter", "show"),
-
                    tui::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 state {
-
            State::Tup2((StateValue::Usize(step), StateValue::Usize(total))) => {
-
                Progress::Step(step.saturating_add(1), total)
-
            }
-
            _ => 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(
-
        &self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let navigation = ui::list_navigation(theme);
-
        let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed();
-
        let patch_browser = ui::patches(context, theme, 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 shortcuts_h = 1u16;
-
        let layout = layout::default_page(area, 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::ui::shortcuts(
-
                    theme,
-
                    vec![
-
                        tui::ui::shortcut(theme, "esc", "back"),
-
                        tui::ui::shortcut(theme, "tab", "section"),
-
                        tui::ui::shortcut(theme, "q", "quit"),
-
                    ],
-
                ),
-
            ),
-
            (
-
                PatchCid::Files,
-
                tui::ui::shortcuts(
-
                    theme,
-
                    vec![
-
                        tui::ui::shortcut(theme, "esc", "back"),
-
                        tui::ui::shortcut(theme, "tab", "section"),
-
                        tui::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(
-
        &self,
-
        app: &mut Application<Cid, Message, NoUserEvent>,
-
        context: &Context,
-
        theme: &Theme,
-
    ) -> Result<()> {
-
        let navigation = ui::navigation(theme);
-
        let header = tui::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 shortcuts_h = 1u16;
-
        let layout = layout::default_page(area, 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/app/ui.rs
@@ -1,242 +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::context::Context;
-
use tui::ui::cob;
-
use tui::ui::cob::PatchItem;
-
use tui::ui::layout;
-
use tui::ui::theme::Theme;
-
use tui::ui::widget::{Widget, WidgetComponent};
-

-
use tui::ui::widget::container::Tabs;
-
use tui::ui::widget::context::{ContextBar, Progress};
-
use tui::ui::widget::label::Label;
-
use tui::ui::widget::list::{ColumnWidth, Table};
-

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

-
impl PatchBrowser {
-
    pub fn new(context: &Context, theme: &Theme, selected: Option<(PatchId, Patch)>) -> Self {
-
        let header = [
-
            tui::ui::label(" ● "),
-
            tui::ui::label("ID"),
-
            tui::ui::label("Title"),
-
            tui::ui::label("Author"),
-
            tui::ui::label("Head"),
-
            tui::ui::label("+"),
-
            tui::ui::label("-"),
-
            tui::ui::label("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 mut items = vec![];
-

-
        for (id, patch) in context.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()))
-
            .highlight(theme.colors.item_list_highlighted_bg);
-

-
        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 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::ui::tabs(
-
        theme,
-
        vec![tui::ui::reversable_label("Patches").foreground(theme.colors.tabs_highlighted_fg)],
-
    )
-
}
-

-
pub fn navigation(theme: &Theme) -> Widget<Tabs> {
-
    tui::ui::tabs(
-
        theme,
-
        vec![
-
            tui::ui::reversable_label("Activity").foreground(theme.colors.tabs_highlighted_fg),
-
            tui::ui::reversable_label("Files").foreground(theme.colors.tabs_highlighted_fg),
-
        ],
-
    )
-
}
-

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

-
pub fn activity(theme: &Theme) -> Widget<Activity> {
-
    let not_implemented = tui::ui::label("not implemented").foreground(theme.colors.default_fg);
-
    let activity = Activity::new(not_implemented);
-

-
    Widget::new(activity)
-
}
-

-
pub fn files(theme: &Theme) -> Widget<Files> {
-
    let not_implemented = tui::ui::label("not implemented").foreground(theme.colors.default_fg);
-
    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 = cob::format_author(patch.author().id(), is_you);
-
    let comments = rev.discussion().len();
-

-
    tui::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 patches = context.patches();
-
    let mut draft = 0;
-
    let mut open = 0;
-
    let mut archived = 0;
-
    let mut merged = 0;
-

-
    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::ui::widget::context::bar(
-
        theme,
-
        "Browse",
-
        "",
-
        "",
-
        &format!("{draft} draft | {open} open | {archived} archived | {merged} merged"),
-
        &progress.to_string(),
-
    )
-
}
deleted bin/commands/patch/main.rs
@@ -1,87 +0,0 @@
-
mod app;
-

-
use std::process;
-

-
use anyhow::anyhow;
-

-
use radicle::profile;
-

-
use log::info;
-
use log::LevelFilter;
-

-
use radicle_term as term;
-
use radicle_tui as tui;
-

-
use tui::context;
-
use tui::Window;
-

-
pub const NAME: &str = "rad-patch-tui";
-
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
-
pub const GIT_HEAD: &str = env!("GIT_HEAD");
-
pub const FPS: u64 = 60;
-

-
pub const HELP: &str = r#"
-
Usage
-

-
    rad-patch-tui [<option>...]
-

-
Options
-

-
    --version       Print version
-
    --help          Print help
-

-
"#;
-

-
struct Options;
-

-
impl Options {
-
    #[allow(clippy::never_loop)]
-
    fn from_env() -> Result<Self, anyhow::Error> {
-
        use lexopt::prelude::*;
-

-
        let mut parser = lexopt::Parser::from_env();
-

-
        while let Some(arg) = parser.next()? {
-
            match arg {
-
                Long("version") => {
-
                    println!("{NAME} {VERSION}+{GIT_HEAD}");
-
                    process::exit(0);
-
                }
-
                Long("help") | Short('h') => {
-
                    println!("{HELP}");
-
                    process::exit(0);
-
                }
-
                _ => anyhow::bail!(arg.unexpected()),
-
            }
-
        }
-

-
        Ok(Self {})
-
    }
-
}
-

-
fn execute() -> anyhow::Result<()> {
-
    let _ = Options::from_env()?;
-

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

-
    let logfile = format!(
-
        "{}/rad-patch-tui.log",
-
        profile::home()?.path().to_string_lossy()
-
    );
-
    simple_logging::log_to_file(logfile, LevelFilter::Info)?;
-
    info!("Launching window...");
-

-
    let mut window = Window::default();
-
    window.run(&mut app::App::new(context), 1000 / FPS)?;
-

-
    Ok(())
-
}
-

-
fn main() {
-
    if let Err(err) = execute() {
-
        term::error(format!("Error: rad-patch-tui: {err}"));
-
        process::exit(1);
-
    }
-
}
added bin/commands/patch/suite.rs
@@ -0,0 +1,278 @@
+
#[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::{Application, Frame, NoUserEvent, Sub, SubClause};
+

+
use radicle_tui as tui;
+

+
use radicle_tui::cob;
+
use radicle_tui::context::Context;
+
use radicle_tui::ui::subscription;
+
use radicle_tui::ui::theme::{self, Theme};
+
use radicle_tui::PageStack;
+
use radicle_tui::Tui;
+

+
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,
+
    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) -> Self {
+
        Self {
+
            context,
+
            pages: PageStack::default(),
+
            theme: theme::default_dark(),
+
            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.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 repo = self.context.repository();
+

+
        if let Some(patch) = cob::patch::find(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_dark();
+
        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::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::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::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::ui::global_listener().to_boxed();
+
        app.mount(
+
            Cid::GlobalListener,
+
            global,
+
            vec![Sub::new(subscription::global_clause(), 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 quit(&self) -> bool {
+
        self.quit
+
    }
+
}
added bin/commands/patch/suite/event.rs
@@ -0,0 +1,139 @@
+
use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection};
+
use tuirealm::event::{Event, Key, KeyEvent};
+
use tuirealm::{MockComponent, NoUserEvent, State, StateValue};
+

+
use radicle_tui::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer, Popup};
+
use radicle_tui::ui::widget::context::{ContextBar, Shortcuts};
+
use radicle_tui::ui::widget::list::PropertyList;
+

+
use radicle_tui::ui::widget::Widget;
+

+
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<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, ..
+
            }) => {
+
                let result = self.perform(Cmd::Submit);
+
                match result {
+
                    CmdResult::Submit(State::One(StateValue::Usize(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
+
    }
+
}
added bin/commands/patch/suite/page.rs
@@ -0,0 +1,326 @@
+
use std::collections::HashMap;
+

+
use anyhow::Result;
+

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

+
use tuirealm::{Frame, NoUserEvent, State, StateValue, Sub, SubClause};
+

+
use radicle_tui as tui;
+

+
use tui::context::Context;
+
use tui::ui::theme::Theme;
+
use tui::ui::widget::context::{Progress, Shortcuts};
+
use tui::ui::widget::Widget;
+
use tui::ui::{layout, subscription};
+
use tui::ViewPage;
+

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

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

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

+
    fn build_shortcuts(theme: &Theme) -> HashMap<ListCid, Widget<Shortcuts>> {
+
        [(
+
            ListCid::PatchBrowser,
+
            tui::ui::shortcuts(
+
                theme,
+
                vec![
+
                    tui::ui::shortcut(theme, "tab", "section"),
+
                    tui::ui::shortcut(theme, "↑/↓", "navigate"),
+
                    tui::ui::shortcut(theme, "enter", "show"),
+
                    tui::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 state {
+
            State::Tup2((StateValue::Usize(step), StateValue::Usize(total))) => {
+
                Progress::Step(step.saturating_add(1), total)
+
            }
+
            _ => 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(
+
        &self,
+
        app: &mut Application<Cid, Message, NoUserEvent>,
+
        context: &Context,
+
        theme: &Theme,
+
    ) -> Result<()> {
+
        let navigation = ui::list_navigation(theme);
+
        let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed();
+
        let patch_browser = ui::patches(context, theme, 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 shortcuts_h = 1u16;
+
        let layout = layout::default_page(area, 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::ui::shortcuts(
+
                    theme,
+
                    vec![
+
                        tui::ui::shortcut(theme, "esc", "back"),
+
                        tui::ui::shortcut(theme, "tab", "section"),
+
                        tui::ui::shortcut(theme, "q", "quit"),
+
                    ],
+
                ),
+
            ),
+
            (
+
                PatchCid::Files,
+
                tui::ui::shortcuts(
+
                    theme,
+
                    vec![
+
                        tui::ui::shortcut(theme, "esc", "back"),
+
                        tui::ui::shortcut(theme, "tab", "section"),
+
                        tui::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(
+
        &self,
+
        app: &mut Application<Cid, Message, NoUserEvent>,
+
        context: &Context,
+
        theme: &Theme,
+
    ) -> Result<()> {
+
        let navigation = ui::navigation(theme);
+
        let header = tui::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 shortcuts_h = 1u16;
+
        let layout = layout::default_page(area, 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,
+
        }
+
    }
+
}
added bin/commands/patch/suite/ui.rs
@@ -0,0 +1,242 @@
+
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::context::Context;
+
use tui::ui::cob;
+
use tui::ui::cob::PatchItem;
+
use tui::ui::layout;
+
use tui::ui::theme::Theme;
+
use tui::ui::widget::{Widget, WidgetComponent};
+

+
use tui::ui::widget::container::Tabs;
+
use tui::ui::widget::context::{ContextBar, Progress};
+
use tui::ui::widget::label::Label;
+
use tui::ui::widget::list::{ColumnWidth, Table};
+

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

+
impl PatchBrowser {
+
    pub fn new(context: &Context, theme: &Theme, selected: Option<(PatchId, Patch)>) -> Self {
+
        let header = [
+
            tui::ui::label(" ● "),
+
            tui::ui::label("ID"),
+
            tui::ui::label("Title"),
+
            tui::ui::label("Author"),
+
            tui::ui::label("Head"),
+
            tui::ui::label("+"),
+
            tui::ui::label("-"),
+
            tui::ui::label("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 mut items = vec![];
+

+
        for (id, patch) in context.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()))
+
            .highlight(theme.colors.item_list_highlighted_bg);
+

+
        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 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::ui::tabs(
+
        theme,
+
        vec![tui::ui::reversable_label("Patches").foreground(theme.colors.tabs_highlighted_fg)],
+
    )
+
}
+

+
pub fn navigation(theme: &Theme) -> Widget<Tabs> {
+
    tui::ui::tabs(
+
        theme,
+
        vec![
+
            tui::ui::reversable_label("Activity").foreground(theme.colors.tabs_highlighted_fg),
+
            tui::ui::reversable_label("Files").foreground(theme.colors.tabs_highlighted_fg),
+
        ],
+
    )
+
}
+

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

+
pub fn activity(theme: &Theme) -> Widget<Activity> {
+
    let not_implemented = tui::ui::label("not implemented").foreground(theme.colors.default_fg);
+
    let activity = Activity::new(not_implemented);
+

+
    Widget::new(activity)
+
}
+

+
pub fn files(theme: &Theme) -> Widget<Files> {
+
    let not_implemented = tui::ui::label("not implemented").foreground(theme.colors.default_fg);
+
    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 = cob::format_author(patch.author().id(), is_you);
+
    let comments = rev.discussion().len();
+

+
    tui::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 patches = context.patches();
+
    let mut draft = 0;
+
    let mut open = 0;
+
    let mut archived = 0;
+
    let mut merged = 0;
+

+
    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::ui::widget::context::bar(
+
        theme,
+
        "Browse",
+
        "",
+
        "",
+
        &format!("{draft} draft | {open} open | {archived} archived | {merged} merged"),
+
        &progress.to_string(),
+
    )
+
}
modified bin/main.rs
@@ -1,7 +1,115 @@
-
// use radicle::profile;
-

+
mod commands;
mod terminal;

+
use std::ffi::OsString;
+
use std::io;
+
use std::{iter, process};
+

+
use anyhow::anyhow;
+

+
use radicle::version;
+
use radicle_term as term;
+

+
use commands::*;
+

+
pub const NAME: &str = "rad-tui";
+
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+
pub const DESCRIPTION: &str = "Radicle terminal interfaces";
+
pub const GIT_HEAD: &str = env!("GIT_HEAD");
+

+
#[derive(Debug)]
+
enum Command {
+
    Other(Vec<OsString>),
+
    Help,
+
    Version,
+
}
+

fn main() {
+
    match parse_args().map_err(Some).and_then(run) {
+
        Ok(_) => process::exit(0),
+
        Err(err) => {
+
            if let Some(err) = err {
+
                term::error(format!("rad: {err}"));
+
            }
+
            process::exit(1);
+
        }
+
    }
+
}
+

+
fn parse_args() -> anyhow::Result<Command> {
+
    use lexopt::prelude::*;
+

+
    let mut parser = lexopt::Parser::from_env();
+
    let mut command = None;
+

+
    while let Some(arg) = parser.next()? {
+
        match arg {
+
            Long("help") | Short('h') => {
+
                command = Some(Command::Help);
+
            }
+
            Long("version") => {
+
                command = Some(Command::Version);
+
            }
+
            Value(val) if command.is_none() => {
+
                if val == *"." {
+
                    command = Some(Command::Other(vec![OsString::from("inspect")]));
+
                } else {
+
                    let args = iter::once(val)
+
                        .chain(iter::from_fn(|| parser.value().ok()))
+
                        .collect();
+

+
                    command = Some(Command::Other(args))
+
                }
+
            }
+
            _ => return Err(anyhow::anyhow!(arg.unexpected())),
+
        }
+
    }
+

+
    Ok(command.unwrap_or_else(|| Command::Other(vec![])))
+
}
+

+
fn print_help() -> anyhow::Result<()> {
+
    version::print(&mut io::stdout(), NAME, VERSION, GIT_HEAD)?;
+
    println!("{DESCRIPTION}");
+
    println!();
+

+
    tui_help::run(Default::default(), terminal::profile)
+
}
+

+
fn run(command: Command) -> Result<(), Option<anyhow::Error>> {
+
    match command {
+
        Command::Version => {
+
            version::print(&mut io::stdout(), NAME, VERSION, GIT_HEAD)
+
                .map_err(|e| Some(e.into()))?;
+
        }
+
        Command::Help => {
+
            print_help()?;
+
        }
+
        Command::Other(args) => {
+
            let exe = args.first();
+

+
            if let Some(Some(exe)) = exe.map(|s| s.to_str()) {
+
                run_other(exe, &args[1..])?;
+
            } else {
+
                print_help()?;
+
            }
+
        }
+
    }
+

+
    Ok(())
+
}

-
}

\ No newline at end of file
+
fn run_other(exe: &str, args: &[OsString]) -> Result<(), Option<anyhow::Error>> {
+
    match exe {
+
        "patch" => {
+
            terminal::run_command_args::<tui_patch::Options, _>(
+
                tui_patch::HELP,
+
                tui_patch::run,
+
                args.to_vec(),
+
            );
+
        }
+
        other => Err(Some(anyhow!(
+
            "`{other}` is not a command. See `rad-tui --help` for a list of commands.",
+
        ))),
+
    }
+
}
modified bin/terminal.rs
@@ -1,10 +1,11 @@
pub mod args;
-
pub use args::{Args, Error, Help};
pub mod io;

use std::ffi::OsString;
use std::process;

+
pub use args::{Args, Error, Help};
+

use radicle_term as term;

use radicle::profile::Profile;
@@ -45,15 +46,15 @@ where
    }
}

-
pub fn run_command<A, C>(help: Help, cmd: C) -> !
-
where
-
    A: Args,
-
    C: Command<A, fn() -> anyhow::Result<Profile>>,
-
{
-
    let args = std::env::args_os().skip(1).collect();
+
// pub fn run_command<A, C>(help: Help, cmd: C) -> !
+
// where
+
//     A: Args,
+
//     C: Command<A, fn() -> anyhow::Result<Profile>>,
+
// {
+
//     let args = std::env::args_os().skip(1).collect();

-
    run_command_args(help, cmd, args)
-
}
+
//     run_command_args(help, cmd, args)
+
// }

pub fn run_command_args<A, C>(help: Help, cmd: C, args: Vec<OsString>) -> !
where
@@ -91,7 +92,7 @@ where
            term::error(format!("rad {}: {err}", help.name));

            if let Some(hint) = hint {
-
            term::hint(hint);
+
                term::hint(hint);
            }
            process::exit(1);
        }
@@ -129,6 +130,6 @@ pub fn fail(_name: &str, error: &anyhow::Error) {
    }

    if let Some(Error::WithHint { hint, .. }) = error.downcast_ref::<Error>() {
-
    term::hint(hint);
+
        term::hint(hint);
    }
}
modified bin/terminal/args.rs
@@ -1,14 +1,9 @@
use std::ffi::OsString;
use std::str::FromStr;
-
use std::time;

use anyhow::anyhow;

-
use radicle::cob::{self, issue, patch};
-
use radicle::crypto;
-
use radicle::git::RefString;
-
use radicle::node::{Address, Alias};
-
use radicle::prelude::{Did, Id, NodeId};
+
use radicle::cob::{issue, patch};

/// Git revision parameter. Supports extended SHA-1 syntax.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -21,6 +16,7 @@ impl From<String> for Rev {
}

#[derive(thiserror::Error, Debug)]
+
#[allow(dead_code)]
pub enum Error {
    /// If this error is returned from argument parsing, help is displayed.
    #[error("help invoked")]
@@ -63,6 +59,7 @@ pub trait Args: Sized {
    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)>;
}

+
#[allow(dead_code)]
pub fn parse_value<T: FromStr>(flag: &str, value: OsString) -> anyhow::Result<T>
where
    <T as FromStr>::Err: std::error::Error,
@@ -74,6 +71,7 @@ where
        .map_err(|e| anyhow!("invalid value specified for '--{}' ({})", flag, e))
}

+
#[allow(dead_code)]
pub fn format(arg: lexopt::Arg) -> OsString {
    match arg {
        lexopt::Arg::Long(flag) => format!("--{flag}").into(),
@@ -82,6 +80,7 @@ pub fn format(arg: lexopt::Arg) -> OsString {
    }
}

+
#[allow(dead_code)]
pub fn finish(unparsed: Vec<OsString>) -> anyhow::Result<()> {
    if let Some(arg) = unparsed.first() {
        return Err(anyhow::anyhow!(
@@ -92,103 +91,20 @@ pub fn finish(unparsed: Vec<OsString>) -> anyhow::Result<()> {
    Ok(())
}

-
pub fn refstring(flag: &str, value: OsString) -> anyhow::Result<RefString> {
-
    RefString::try_from(
-
        value
-
            .into_string()
-
            .map_err(|_| anyhow!("the value specified for '--{}' is not valid UTF-8", flag))?,
-
    )
-
    .map_err(|_| {
-
        anyhow!(
-
            "the value specified for '--{}' is not a valid ref string",
-
            flag
-
        )
-
    })
-
}
-

-
pub fn did(val: &OsString) -> anyhow::Result<Did> {
-
    let val = val.to_string_lossy();
-
    let Ok(peer) = Did::from_str(&val) else {
-
        if crypto::PublicKey::from_str(&val).is_ok() {
-
            return Err(anyhow!("expected DID, did you mean 'did:key:{val}'?"));
-
        } else {
-
            return Err(anyhow!("invalid DID '{}', expected 'did:key'", val));
-
        }
-
    };
-
    Ok(peer)
-
}
-

-
pub fn nid(val: &OsString) -> anyhow::Result<NodeId> {
-
    let val = val.to_string_lossy();
-
    NodeId::from_str(&val).map_err(|_| anyhow!("invalid Node ID '{}'", val))
-
}
-

-
pub fn rid(val: &OsString) -> anyhow::Result<Id> {
-
    let val = val.to_string_lossy();
-
    Id::from_str(&val).map_err(|_| anyhow!("invalid Repository ID '{}'", val))
-
}
-

-
pub fn pubkey(val: &OsString) -> anyhow::Result<NodeId> {
-
    let Ok(did) = did(val) else {
-
        let nid = nid(val)?;
-
        return Ok(nid);
-
    };
-
    Ok(did.as_key().to_owned())
-
}
-

-
pub fn addr(val: &OsString) -> anyhow::Result<Address> {
-
    let val = val.to_string_lossy();
-
    Address::from_str(&val).map_err(|_| anyhow!("invalid address '{}'", val))
-
}
-

-
pub fn number(val: &OsString) -> anyhow::Result<usize> {
-
    let val = val.to_string_lossy();
-
    usize::from_str(&val).map_err(|_| anyhow!("invalid number '{}'", val))
-
}
-

-
pub fn seconds(val: &OsString) -> anyhow::Result<time::Duration> {
-
    let val = val.to_string_lossy();
-
    let secs = u64::from_str(&val).map_err(|_| anyhow!("invalid number of seconds '{}'", val))?;
-

-
    Ok(time::Duration::from_secs(secs))
-
}
-

-
pub fn string(val: &OsString) -> String {
-
    val.to_string_lossy().to_string()
-
}
-

+
#[allow(dead_code)]
pub fn rev(val: &OsString) -> anyhow::Result<Rev> {
    let s = val.to_str().ok_or(anyhow!("invalid git rev {val:?}"))?;
    Ok(Rev::from(s.to_owned()))
}

-
pub fn oid(val: &OsString) -> anyhow::Result<Rev> {
-
    let s = string(val);
-
    let _ = radicle::git::Oid::from_str(&s).map_err(|_| anyhow!("invalid git oid '{s}'"))?;
-

-
    Ok(Rev::from(s))
-
}
-

-
pub fn alias(val: &OsString) -> anyhow::Result<Alias> {
-
    let val = val.as_os_str();
-
    let val = val
-
        .to_str()
-
        .ok_or_else(|| anyhow!("alias must be valid UTF-8"))?;
-

-
    Alias::from_str(val).map_err(|e| e.into())
-
}
-

+
#[allow(dead_code)]
pub fn issue(val: &OsString) -> anyhow::Result<issue::IssueId> {
    let val = val.to_string_lossy();
    issue::IssueId::from_str(&val).map_err(|_| anyhow!("invalid Issue ID '{}'", val))
}

+
#[allow(dead_code)]
pub fn patch(val: &OsString) -> anyhow::Result<patch::PatchId> {
    let val = val.to_string_lossy();
    patch::PatchId::from_str(&val).map_err(|_| anyhow!("invalid Patch ID '{}'", val))
}
-

-
pub fn cob(val: &OsString) -> anyhow::Result<cob::ObjectId> {
-
    let val = val.to_string_lossy();
-
    cob::ObjectId::from_str(&val).map_err(|_| anyhow!("invalid Object ID '{}'", val))
-
}
modified bin/terminal/io.rs
@@ -14,6 +14,7 @@ pub struct PassphraseValidator {
    keystore: Keystore,
}

+
#[allow(dead_code)]
impl PassphraseValidator {
    /// Create a new validator.
    pub fn new(keystore: Keystore) -> Self {
@@ -39,6 +40,7 @@ impl inquire::validator::StringValidator for PassphraseValidator {

/// Get the signer. First we try getting it from ssh-agent, otherwise we prompt the user,
/// if we're connected to a TTY.
+
#[allow(dead_code)]
pub fn signer(profile: &Profile) -> anyhow::Result<Box<dyn Signer>> {
    if let Ok(signer) = profile.signer() {
        return Ok(signer);
modified src/lib.rs
@@ -10,6 +10,7 @@ use tuirealm::{Application, EventListenerCfg, NoUserEvent};

pub mod cob;
pub mod context;
+
pub mod log;
pub mod ui;

use context::Context;
added src/log.rs
@@ -0,0 +1,15 @@
+
use log::LevelFilter;
+

+
use radicle::profile::Profile;
+

+
pub fn enable(cmd: &str, op: &str, profile: &Profile) -> Result<(), anyhow::Error> {
+
    let logfile = format!(
+
        "{}/rad-tui-{}-{}.log",  
+
        profile.home().path().to_string_lossy(),
+
        cmd,
+
        op,
+
    );
+
    simple_logging::log_to_file(logfile, LevelFilter::Info)?;
+

+
    Ok(())
+
}