Radish alpha
r
Radicle terminal user interface
Radicle
Git (anonymous pull)
Log in to clone via SSH
inbox: Add empty app skeleton
Erik Kundt committed 2 years ago
commit e0ddf6906ac6ab3a7918b62b6069d1b6cc5b098d
parent 442f29f725b074814f5a5e3b922fdf0b68ab9183
7 files changed +672 -4
modified bin/commands/inbox.rs
@@ -1,10 +1,19 @@
+
#[path = "inbox/select.rs"]
+
mod select;
+

use std::ffi::OsString;

use anyhow::anyhow;

+
use radicle_tui as tui;
+

+
use tui::cob::inbox::{self};
+
use tui::{context, log, Window};
+

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

+
pub const FPS: u64 = 60;
pub const HELP: Help = Help {
    name: "inbox",
    description: "Terminal interfaces for notifications",
@@ -25,7 +34,7 @@ pub struct Options {
}

pub enum Operation {
-
    Select,
+
    Select { opts: SelectOptions },
}

#[derive(PartialEq, Eq)]
@@ -33,12 +42,18 @@ pub enum OperationName {
    Select,
}

+
#[derive(Debug, Default, Clone, PartialEq, Eq)]
+
pub struct SelectOptions {
+
    filter: inbox::Filter,
+
}
+

impl Args for Options {
    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
        use lexopt::prelude::*;

        let mut parser = lexopt::Parser::from_args(args);
        let mut op: Option<OperationName> = None;
+
        let select_opts = SelectOptions::default();

        while let Some(arg) = parser.next()? {
            match arg {
@@ -55,18 +70,32 @@ impl Args for Options {
        }

        let op = match op.ok_or_else(|| anyhow!("an operation must be provided"))? {
-
            OperationName::Select => Operation::Select,
+
            OperationName::Select => Operation::Select { opts: select_opts },
        };
        Ok((Options { op }, vec![]))
    }
}

pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
-
    let (_, _) = radicle::rad::cwd()
+
    let (_, id) = radicle::rad::cwd()
        .map_err(|_| anyhow!("this command must be run in the context of a project"))?;

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

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

+
            let mut app = select::App::new(context, 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(())
added bin/commands/inbox/select.rs
@@ -0,0 +1,232 @@
+
#[path = "select/event.rs"]
+
mod event;
+
#[path = "select/page.rs"]
+
mod page;
+
#[path = "select/ui.rs"]
+
mod ui;
+

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

+
use anyhow::Result;
+
use serde::{Serialize, Serializer};
+

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

+
use radicle_tui as tui;
+

+
use tui::cob::inbox::Filter;
+
use tui::context::Context;
+

+
use tui::ui::subscription;
+
use tui::ui::theme::Theme;
+
use tui::{Exit, PageStack, SelectionExit, Tui};
+

+
use page::ListView;
+

+
/// Wrapper around radicle's `PatchId` that serializes
+
/// to a human-readable string.
+
#[derive(Clone, Debug, Eq, PartialEq)]
+
pub struct PatchId(radicle::cob::patch::PatchId);
+

+
impl From<radicle::cob::patch::PatchId> for PatchId {
+
    fn from(value: radicle::cob::patch::PatchId) -> Self {
+
        PatchId(value)
+
    }
+
}
+

+
impl Display for PatchId {
+
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+
        write!(f, "{}", self.0)
+
    }
+
}
+

+
impl Serialize for PatchId {
+
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+
    where
+
        S: Serializer,
+
    {
+
        serializer.serialize_str(&format!("{}", *self.0))
+
    }
+
}
+

+
/// The application's subject. It tells the application
+
/// which widgets to render and which output to produce.
+
///
+
/// Depends on CLI arguments given by the user.
+
#[derive(Clone, Default, Debug, Eq, PartialEq)]
+
pub enum Mode {
+
    #[default]
+
    Operation,
+
    Id,
+
}
+

+
/// The selected issue operation returned by the operation
+
/// selection widget.
+
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
+
pub enum IssueOperation {
+
    Show,
+
    Delete,
+
    Edit,
+
    Comment,
+
}
+

+
impl Display for IssueOperation {
+
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+
        match self {
+
            IssueOperation::Show => {
+
                write!(f, "show")
+
            }
+
            IssueOperation::Delete => {
+
                write!(f, "delete")
+
            }
+
            IssueOperation::Edit => {
+
                write!(f, "edit")
+
            }
+
            IssueOperation::Comment => {
+
                write!(f, "comment")
+
            }
+
        }
+
    }
+
}
+

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

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

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

+
pub struct App {
+
    context: Context,
+
    pages: PageStack<Cid, Message>,
+
    theme: Theme,
+
    quit: bool,
+
    filter: Filter,
+
    output: Option<SelectionExit>,
+
}
+

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

+
    fn view_list(
+
        &mut self,
+
        app: &mut Application<Cid, Message, NoUserEvent>,
+
        theme: &Theme,
+
    ) -> Result<()> {
+
        let home = Box::new(ListView::new(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, SelectionExit> 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::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<SelectionExit>> {
+
        if self.quit {
+
            return Some(Exit {
+
                value: self.output.clone(),
+
            });
+
        }
+
        None
+
    }
+
}
added bin/commands/inbox/select/event.rs
@@ -0,0 +1,131 @@
+
use radicle::issue::IssueId;
+

+
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::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer};
+
use tui::ui::widget::context::{ContextBar, Shortcuts};
+
use tui::ui::widget::list::PropertyList;
+
use tui::ui::widget::Widget;
+
use tui::SelectionExit;
+

+
use super::ui::OperationSelect;
+
use super::{IssueOperation, Message};
+

+
/// 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<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) => None,
+
                _ => 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 exit = SelectionExit::default()
+
                    .with_operation(IssueOperation::Show.to_string())
+
                    .with_id(IssueId::from(id));
+
                Message::Quit(Some(exit))
+
            }),
+
            Event::Keyboard(KeyEvent {
+
                code: Key::Char('d'),
+
                ..
+
            }) => submit().map(|id| {
+
                let exit = SelectionExit::default()
+
                    .with_operation(IssueOperation::Delete.to_string())
+
                    .with_id(IssueId::from(id));
+
                Message::Quit(Some(exit))
+
            }),
+
            Event::Keyboard(KeyEvent {
+
                code: Key::Char('e'),
+
                ..
+
            }) => submit().map(|id| {
+
                let exit = SelectionExit::default()
+
                    .with_operation(IssueOperation::Edit.to_string())
+
                    .with_id(IssueId::from(id));
+
                Message::Quit(Some(exit))
+
            }),
+
            Event::Keyboard(KeyEvent {
+
                code: Key::Char('m'),
+
                ..
+
            }) => submit().map(|id| {
+
                let exit = SelectionExit::default()
+
                    .with_operation(IssueOperation::Comment.to_string())
+
                    .with_id(IssueId::from(id));
+
                Message::Quit(Some(exit))
+
            }),
+
            _ => 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
+
    }
+
}
added bin/commands/inbox/select/page.rs
@@ -0,0 +1,146 @@
+
use std::collections::HashMap;
+

+
use anyhow::Result;
+

+
use tui::ui::state::ItemState;
+
use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent, Sub, SubClause};
+

+
use radicle_tui as tui;
+

+
use tui::cob::inbox::Filter;
+
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};
+

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

+
impl ListView {
+
    pub fn new(filter: Filter) -> Self {
+
        Self {
+
            active_component: ListCid::NotificationBrowser,
+
            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::NotificationBrowser))?;
+
        let progress = match ItemState::try_from(state) {
+
            Ok(state) => Progress::Step(
+
                state
+
                    .selected()
+
                    .map(|s| s.saturating_add(1))
+
                    .unwrap_or_default(),
+
                state.len(),
+
            ),
+
            Err(_) => Progress::None,
+
        };
+

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

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

+
        Ok(())
+
    }
+

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

+
        Ok(())
+
    }
+
}
+

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

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

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

+
        Ok(())
+
    }
+

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

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

+
        Ok(None)
+
    }
+

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

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

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

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

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

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

+
use radicle::issue::{Issue, IssueId};
+

+
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::cob::inbox::Filter;
+
use tui::context::Context;
+
use tui::ui::theme::{style, Theme};
+
use tui::ui::widget::context::{ContextBar, Progress, Shortcuts};
+
use tui::ui::widget::label::{self};
+
use tui::ui::widget::{Widget, WidgetComponent};
+

+
use super::ListCid;
+

+
pub struct NotificationBrowser {}
+

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

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

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

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

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

+
    pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
+
        [(
+
            ListCid::NotificationBrowser,
+
            tui::ui::shortcuts(
+
                &self.theme,
+
                vec![tui::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 operation_select(
+
    theme: &Theme,
+
    context: &Context,
+
    filter: Filter,
+
    selected: Option<(IssueId, Issue)>,
+
) -> Widget<OperationSelect> {
+
    let browser = Widget::new(NotificationBrowser {});
+

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

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

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

+
    let spacer = label::default("");
+
    let divider = label::default(" | ");
+

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

+
    Widget::new(context_bar).height(1)
+
}
modified src/cob.rs
@@ -6,6 +6,7 @@ use radicle::cob::Label;
use radicle::prelude::Did;

pub mod format;
+
pub mod inbox;
pub mod issue;
pub mod patch;

added src/cob/inbox.rs
@@ -0,0 +1,2 @@
+
#[derive(Clone, Default, Debug, Eq, PartialEq)]
+
pub struct Filter {}