From c864888d48aa65865535e9693b261d5bbf1ccf24 Mon Sep 17 00:00:00 2001 From: Erik Kundt Date: Tue, 20 Feb 2024 10:18:02 +0100 Subject: [PATCH] lib: Introduce features 'realm' and 'flux' --- Cargo.toml | 13 +- bin/commands/inbox.rs | 51 +++- bin/commands/inbox/common.rs | 10 + bin/commands/inbox/flux.rs | 2 + bin/commands/inbox/flux/select.rs | 102 +++++++ bin/commands/inbox/flux/select/ui.rs | 228 +++++++++++++++ bin/commands/inbox/realm.rs | 2 + bin/commands/inbox/{ => realm}/select.rs | 37 +-- bin/commands/inbox/realm/select/event.rs | 161 +++++++++++ bin/commands/inbox/realm/select/page.rs | 168 +++++++++++ bin/commands/inbox/realm/select/ui.rs | 267 ++++++++++++++++++ bin/commands/inbox/select/event.rs | 10 +- bin/commands/inbox/select/page.rs | 16 +- bin/commands/inbox/select/ui.rs | 30 +- bin/commands/issue.rs | 35 ++- bin/commands/issue/common.rs | 11 +- bin/commands/issue/realm.rs | 6 + bin/commands/issue/realm/common.rs | 2 + bin/commands/issue/{ => realm}/common/ui.rs | 17 +- bin/commands/issue/{ => realm}/select.rs | 26 +- .../issue/{ => realm}/select/event.rs | 10 +- .../{patch => issue/realm}/select/page.rs | 18 +- bin/commands/issue/{ => realm}/select/ui.rs | 36 +-- bin/commands/issue/{ => realm}/suite.rs | 19 +- bin/commands/issue/{ => realm}/suite/event.rs | 14 +- bin/commands/issue/{ => realm}/suite/page.rs | 60 ++-- bin/commands/issue/{ => realm}/suite/ui.rs | 39 ++- bin/commands/patch.rs | 35 ++- bin/commands/patch/common.rs | 12 +- bin/commands/patch/realm.rs | 6 + bin/commands/patch/realm/common.rs | 2 + bin/commands/patch/{ => realm}/common/ui.rs | 17 +- bin/commands/patch/{ => realm}/select.rs | 23 +- .../patch/{ => realm}/select/event.rs | 10 +- .../{issue => patch/realm}/select/page.rs | 18 +- bin/commands/patch/{ => realm}/select/ui.rs | 38 +-- bin/commands/patch/{ => realm}/suite.rs | 21 +- bin/commands/patch/{ => realm}/suite/event.rs | 13 +- bin/commands/patch/{ => realm}/suite/page.rs | 46 +-- bin/commands/patch/{ => realm}/suite/ui.rs | 26 +- src/common.rs | 3 + src/{ => common}/cob.rs | 0 src/{ => common}/cob/format.rs | 0 src/{ => common}/cob/inbox.rs | 0 src/{ => common}/cob/issue.rs | 0 src/{ => common}/cob/patch.rs | 0 src/{ => common}/context.rs | 10 +- src/{ => common}/log.rs | 0 src/lib.rs | 215 +------------- src/realm.rs | 211 ++++++++++++++ src/{ => realm}/ui.rs | 2 +- src/{ => realm}/ui/cob.rs | 4 +- src/{ => realm}/ui/cob/format.rs | 0 src/{ => realm}/ui/ext.rs | 0 src/{ => realm}/ui/layout.rs | 0 src/{ => realm}/ui/state.rs | 0 src/{ => realm}/ui/subscription.rs | 0 src/{ => realm}/ui/theme.rs | 0 src/{ => realm}/ui/widget.rs | 0 src/{ => realm}/ui/widget/common.rs | 0 src/{ => realm}/ui/widget/container.rs | 10 +- src/{ => realm}/ui/widget/context.rs | 6 +- src/{ => realm}/ui/widget/form.rs | 10 +- src/{ => realm}/ui/widget/label.rs | 6 +- src/{ => realm}/ui/widget/list.rs | 8 +- src/{ => realm}/ui/widget/utils.rs | 0 66 files changed, 1581 insertions(+), 561 deletions(-) create mode 100644 bin/commands/inbox/common.rs create mode 100644 bin/commands/inbox/flux.rs create mode 100644 bin/commands/inbox/flux/select.rs create mode 100644 bin/commands/inbox/flux/select/ui.rs create mode 100644 bin/commands/inbox/realm.rs rename bin/commands/inbox/{ => realm}/select.rs (89%) create mode 100644 bin/commands/inbox/realm/select/event.rs create mode 100644 bin/commands/inbox/realm/select/page.rs create mode 100644 bin/commands/inbox/realm/select/ui.rs create mode 100644 bin/commands/issue/realm.rs create mode 100644 bin/commands/issue/realm/common.rs rename bin/commands/issue/{ => realm}/common/ui.rs (91%) rename bin/commands/issue/{ => realm}/select.rs (91%) rename bin/commands/issue/{ => realm}/select/event.rs (95%) rename bin/commands/{patch => issue/realm}/select/page.rs (92%) rename bin/commands/issue/{ => realm}/select/ui.rs (77%) rename bin/commands/issue/{ => realm}/suite.rs (95%) rename bin/commands/issue/{ => realm}/suite/event.rs (97%) rename bin/commands/issue/{ => realm}/suite/page.rs (90%) rename bin/commands/issue/{ => realm}/suite/ui.rs (91%) create mode 100644 bin/commands/patch/realm.rs create mode 100644 bin/commands/patch/realm/common.rs rename bin/commands/patch/{ => realm}/common/ui.rs (92%) rename bin/commands/patch/{ => realm}/select.rs (91%) rename bin/commands/patch/{ => realm}/select/event.rs (95%) rename bin/commands/{issue => patch/realm}/select/page.rs (92%) rename bin/commands/patch/{ => realm}/select/ui.rs (76%) rename bin/commands/patch/{ => realm}/suite.rs (93%) rename bin/commands/patch/{ => realm}/suite/event.rs (93%) rename bin/commands/patch/{ => realm}/suite/page.rs (87%) rename bin/commands/patch/{ => realm}/suite/ui.rs (87%) create mode 100644 src/common.rs rename src/{ => common}/cob.rs (100%) rename src/{ => common}/cob/format.rs (100%) rename src/{ => common}/cob/inbox.rs (100%) rename src/{ => common}/cob/issue.rs (100%) rename src/{ => common}/cob/patch.rs (100%) rename src/{ => common}/context.rs (97%) rename src/{ => common}/log.rs (100%) create mode 100644 src/realm.rs rename src/{ => realm}/ui.rs (99%) rename src/{ => realm}/ui/cob.rs (99%) rename src/{ => realm}/ui/cob/format.rs (100%) rename src/{ => realm}/ui/ext.rs (100%) rename src/{ => realm}/ui/layout.rs (100%) rename src/{ => realm}/ui/state.rs (100%) rename src/{ => realm}/ui/subscription.rs (100%) rename src/{ => realm}/ui/theme.rs (100%) rename src/{ => realm}/ui/widget.rs (100%) rename src/{ => realm}/ui/widget/common.rs (100%) rename src/{ => realm}/ui/widget/container.rs (98%) rename src/{ => realm}/ui/widget/context.rs (98%) rename src/{ => realm}/ui/widget/form.rs (96%) rename src/{ => realm}/ui/widget/label.rs (98%) rename src/{ => realm}/ui/widget/list.rs (98%) rename src/{ => realm}/ui/widget/utils.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index f5075651..1f3dfcd2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,11 @@ build = "build.rs" name = "rad-tui" path = "bin/main.rs" +[features] +default = ["flux"] +realm = ["dep:tuirealm", "dep:tui-realm-stdlib"] +flux = ["dep:tokio", "dep:tokio-stream"] + [dependencies] anyhow = { version = "1" } inquire = { version = "0.6.2", default-features = false, features = ["termion", "editor"] } @@ -26,7 +31,7 @@ timeago = { version = "0.4.1" } termion = { version = "3" } textwrap = { version = "0.16.0" } thiserror = { version = "1" } -tokio = { version = "1.32.0", features = ["full"] } -tokio-stream = { version = "0.1.14" } -tuirealm = { version = "^1.9.0", default-features = false, features = ["termion", "ratatui", "derive"] } -tui-realm-stdlib = { version = "1.3.1", default-features = false, features = ["termion", "ratatui"] } +tokio = { version = "1.32.0", features = ["full"], optional = true } +tokio-stream = { version = "0.1.14", optional = true } +tuirealm = { version = "^1.9.0", default-features = false, features = ["termion", "ratatui", "derive"], optional = true } +tui-realm-stdlib = { version = "1.3.1", default-features = false, features = ["termion", "ratatui"], optional = true } diff --git a/bin/commands/inbox.rs b/bin/commands/inbox.rs index 83252d2e..fe968a40 100644 --- a/bin/commands/inbox.rs +++ b/bin/commands/inbox.rs @@ -1,5 +1,12 @@ -#[path = "inbox/select.rs"] -mod select; +#[cfg(feature = "flux")] +#[path = "inbox/flux.rs"] +mod flux; +#[cfg(feature = "realm")] +#[path = "inbox/realm.rs"] +mod realm; + +#[path = "inbox/common.rs"] +mod common; use std::ffi::OsString; @@ -7,13 +14,13 @@ use anyhow::anyhow; use radicle_tui as tui; -use tui::cob::inbox::{self}; -use tui::{context, log, Window}; +use tui::common::cob::inbox::{self}; +use tui::common::context; +use tui::common::log; 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", @@ -51,7 +58,7 @@ pub enum OperationName { #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct SelectOptions { - mode: select::Mode, + mode: common::Mode, filter: inbox::Filter, sort_by: inbox::SortBy, } @@ -78,8 +85,8 @@ impl Args for Options { let val = val.to_str().unwrap_or_default(); select_opts.mode = match val { - "operation" => select::Mode::Operation, - "id" => select::Mode::Id, + "operation" => common::Mode::Operation, + "id" => common::Mode::Id, unknown => anyhow::bail!("unknown mode '{}'", unknown), }; } @@ -121,7 +128,11 @@ impl Args for Options { } } +#[cfg(feature = "realm")] pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + use tui::realm::Window; + + pub const FPS: u64 = 60; let (_, id) = radicle::rad::cwd() .map_err(|_| anyhow!("this command must be run in the context of a project"))?; @@ -132,7 +143,7 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> log::enable(context.profile(), "inbox", "select")?; - let mut app = select::App::new( + let mut app = realm::select::App::new( context, opts.mode.clone(), opts.filter.clone(), @@ -150,3 +161,25 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> Ok(()) } + +#[cfg(feature = "flux")] +#[tokio::main] +pub async fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + let (_, id) = radicle::rad::cwd() + .map_err(|_| anyhow!("this command must be run in the context of a project"))?; + + match options.op { + Operation::Select { opts } => { + let profile = terminal::profile()?; + let context = context::Context::new(profile, id)?; + + log::enable(context.profile(), "inbox", "select")?; + + let _ = flux::select::App::new(context, opts.filter.clone()) + .run() + .await; + } + } + + Ok(()) +} diff --git a/bin/commands/inbox/common.rs b/bin/commands/inbox/common.rs new file mode 100644 index 00000000..a3185c39 --- /dev/null +++ b/bin/commands/inbox/common.rs @@ -0,0 +1,10 @@ +/// 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(Debug, Default, Clone, PartialEq, Eq)] +pub enum Mode { + Id, + #[default] + Operation, +} diff --git a/bin/commands/inbox/flux.rs b/bin/commands/inbox/flux.rs new file mode 100644 index 00000000..ffc8d2d0 --- /dev/null +++ b/bin/commands/inbox/flux.rs @@ -0,0 +1,2 @@ +#[path = "flux/select.rs"] +pub mod select; diff --git a/bin/commands/inbox/flux/select.rs b/bin/commands/inbox/flux/select.rs new file mode 100644 index 00000000..bc83534f --- /dev/null +++ b/bin/commands/inbox/flux/select.rs @@ -0,0 +1,102 @@ +#[path = "select/ui.rs"] +mod ui; + +use anyhow::Result; + +use radicle::node::notifications::NotificationId; + +use radicle_tui as tui; + +use tui::common::cob::inbox::{self, Filter}; +use tui::common::context::Context; +use tui::flux::store::{State, Store}; +use tui::flux::termination::{self, Interrupted}; +use tui::flux::ui::cob::NotificationItem; +use tui::flux::ui::Frontend; +use tui::Exit; + +use ui::ListPage; + +pub struct App { + context: Context, + _filter: Filter, +} + +#[derive(Clone, Debug)] +pub struct InboxState { + notifications: Vec, + selected: Option, +} + +impl TryFrom<&Context> for InboxState { + type Error = anyhow::Error; + + fn try_from(context: &Context) -> Result { + let notifications = inbox::all(context.repository(), context.profile())?; + let mut items = vec![]; + + for notif in ¬ifications { + if let Ok(notif) = NotificationItem::try_from((context.repository(), notif)) { + items.push(notif); + } + } + + Ok(Self { + notifications: items, + selected: None, + }) + } +} + +pub enum Action { + Exit, + Select(NotificationId), +} + +impl State for InboxState { + type Exit = Exit; + + fn tick(&self) {} + + fn handle_action(&mut self, action: Action) -> Option> { + match action { + Action::Select(id) => { + self.selected = Some(id); + None + } + Action::Exit => Some(Exit { value: None }), + } + } +} + +impl App { + pub fn new(context: Context, filter: Filter) -> Self { + Self { + context, + _filter: filter, + } + } + + pub async fn run(&self) -> Result<()> { + let (terminator, mut interrupt_rx) = termination::create_termination(); + let (store, state_rx) = Store::::new(); + let (frontend, action_rx) = Frontend::::new(); + let state = InboxState::try_from(&self.context)?; + + tokio::try_join!( + store.main_loop(state, terminator, action_rx, interrupt_rx.resubscribe()), + frontend.main_loop::(state_rx, interrupt_rx.resubscribe()), + )?; + + if let Ok(reason) = interrupt_rx.recv().await { + match reason { + Interrupted::UserInt => {} + Interrupted::OsSigInt => println!("exited because of an os sig int"), + } + } else { + println!("exited because of an unexpected error"); + } + + Ok(()) + } +} diff --git a/bin/commands/inbox/flux/select/ui.rs b/bin/commands/inbox/flux/select/ui.rs new file mode 100644 index 00000000..bf7e06f2 --- /dev/null +++ b/bin/commands/inbox/flux/select/ui.rs @@ -0,0 +1,228 @@ +use tokio::sync::mpsc::UnboundedSender; + +use termion::event::Key; + +use ratatui::backend::Backend; +use ratatui::layout::{Constraint, Rect}; +use ratatui::widgets::Cell; + +use radicle_tui as tui; + +use tui::flux::ui::cob::NotificationItem; +use tui::flux::ui::span; +use tui::flux::ui::widget::{ + FooterProps, Render, Shortcut, Shortcuts, ShortcutsProps, Table, TableProps, Widget, +}; + +use super::{Action, InboxState}; + +pub struct ListPage { + /// Action sender + pub action_tx: UnboundedSender, + /// notification widget + notifications: Notifications, + /// Shortcut widget + shortcuts: Shortcuts, +} + +impl Widget for ListPage { + fn new(state: &InboxState, action_tx: UnboundedSender) -> Self + where + Self: Sized, + { + Self { + action_tx: action_tx.clone(), + notifications: Notifications::new(state, action_tx.clone()), + shortcuts: Shortcuts::new(state, action_tx.clone()), + } + .move_with_state(state) + } + + fn move_with_state(self, state: &InboxState) -> Self + where + Self: Sized, + { + ListPage { + notifications: self.notifications.move_with_state(state), + shortcuts: self.shortcuts.move_with_state(state), + ..self + } + } + + fn name(&self) -> &str { + "list-page" + } + + fn handle_key_event(&mut self, key: termion::event::Key) { + match key { + Key::Char('q') => { + let _ = self.action_tx.send(Action::Exit); + } + _ => { + >::handle_key_event( + &mut self.notifications, + key, + ); + } + } + } +} + +impl Render<()> for ListPage { + fn render(&mut self, frame: &mut ratatui::Frame, _area: Rect, _props: ()) { + let area = frame.size(); + let layout = tui::flux::ui::layout::default_page(area, 0u16, 1u16); + + self.notifications.render::(frame, layout.component, ()); + self.shortcuts.render::( + frame, + layout.shortcuts, + ShortcutsProps { + shortcuts: vec![Shortcut::new("enter", "select"), Shortcut::new("q", "quit")], + divider: '∙', + }, + ); + } +} + +struct NotificationsProps { + notifications: Vec, +} + +impl From<&InboxState> for NotificationsProps { + fn from(state: &InboxState) -> Self { + Self { + notifications: state.notifications.clone(), + } + } +} + +struct Notifications { + /// Sending actions to the state store + action_tx: UnboundedSender, + /// State Mapped RoomList Props + props: NotificationsProps, + /// Notification table + table: Table, +} + +impl Widget for Notifications { + fn new(state: &InboxState, action_tx: UnboundedSender) -> Self { + Self { + action_tx: action_tx.clone(), + props: NotificationsProps::from(state), + table: Table::new(state, action_tx.clone()), + } + } + + fn move_with_state(self, state: &InboxState) -> Self + where + Self: Sized, + { + Self { + props: NotificationsProps::from(state), + table: self.table.move_with_state(state), + ..self + } + } + + fn name(&self) -> &str { + "notification-list" + } + + fn handle_key_event(&mut self, key: Key) { + match key { + Key::Up => { + self.table.prev(); + + let selected = self + .table + .selected() + .and_then(|selected| self.props.notifications.get(selected)); + + // TODO: propagate error + if let Some(notif) = selected { + let _ = self.action_tx.send(Action::Select(notif.id)); + } + } + Key::Down => { + self.table.next(self.props.notifications.len()); + + let selected = self + .table + .selected() + .and_then(|selected| self.props.notifications.get(selected)); + + // TODO: propagate error + if let Some(notif) = selected { + let _ = self.action_tx.send(Action::Select(notif.id)); + } + } + _ => {} + } + } +} + +impl Render<()> for Notifications { + fn render(&mut self, frame: &mut ratatui::Frame, area: Rect, _props: ()) { + let header: [Cell; 7] = [ + String::from("").into(), + String::from(" ● ").into(), + String::from("Type").into(), + String::from("Summary").into(), + String::from("ID").into(), + String::from("Status").into(), + String::from("Updated").into(), + ]; + + let widths = [ + Constraint::Length(5), + Constraint::Length(3), + Constraint::Length(6), + Constraint::Fill(1), + Constraint::Length(15), + Constraint::Length(10), + Constraint::Length(18), + ]; + + let progress = { + let step = self + .table + .selected() + .map(|selected| selected.saturating_add(1).to_string()) + .unwrap_or("-".to_string()); + let length = self.props.notifications.len().to_string(); + + span::badge(format!("{}/{}", step, length)) + }; + + let footer = FooterProps { + cells: [ + span::badge("/".to_string()), + String::from("").into(), + String::from("").into(), + progress.clone(), + ] + .to_vec(), + widths: [ + Constraint::Length(3), + Constraint::Fill(1), + Constraint::Fill(1), + Constraint::Length(progress.width() as u16), + ] + .to_vec(), + }; + + self.table.render::( + frame, + area, + TableProps { + items: self.props.notifications.to_vec(), + focus: false, + widths, + header, + footer: Some(footer), + }, + ); + } +} diff --git a/bin/commands/inbox/realm.rs b/bin/commands/inbox/realm.rs new file mode 100644 index 00000000..8683ca9b --- /dev/null +++ b/bin/commands/inbox/realm.rs @@ -0,0 +1,2 @@ +#[path = "realm/select.rs"] +pub mod select; diff --git a/bin/commands/inbox/select.rs b/bin/commands/inbox/realm/select.rs similarity index 89% rename from bin/commands/inbox/select.rs rename to bin/commands/inbox/realm/select.rs index 7297bd46..f56e904e 100644 --- a/bin/commands/inbox/select.rs +++ b/bin/commands/inbox/realm/select.rs @@ -9,23 +9,25 @@ 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, SortBy}; -use tui::context::Context; - -use tui::ui::subscription; -use tui::ui::theme::Theme; -use tui::{Exit, PageStack, SelectionExit, Tui}; +use tui::common::cob::inbox::{Filter, SortBy}; +use tui::common::context::Context; +use tui::realm::ui::subscription; +use tui::realm::ui::theme::Theme; +use tui::realm::{PageStack, Tui}; +use tui::{Exit, SelectionExit}; use page::ListView; +use super::super::common::Mode; + /// Wrapper around radicle's `PatchId` that serializes /// to a human-readable string. #[derive(Clone, Debug, Eq, PartialEq)] @@ -52,18 +54,6 @@ impl Serialize for PatchId { } } -/// 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, - #[allow(dead_code)] - Id, -} - /// The selected issue operation returned by the operation /// selection widget. #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -115,12 +105,13 @@ pub struct App { mode: Mode, filter: Filter, sort_by: SortBy, - output: Option, quit: bool, + output: Option, } /// Creates a new application using a tui-realm-application, mounts all /// components and sets focus to a default one. +#[allow(dead_code)] impl App { pub fn new(context: Context, mode: Mode, filter: Filter, sort_by: SortBy) -> Self { Self { @@ -130,8 +121,8 @@ impl App { mode, filter, sort_by, - output: None, quit: false, + output: None, } } @@ -188,12 +179,12 @@ impl Tui for App { self.view_list(app, &self.theme.clone())?; // Add global key listener and subscribe to key events - let global = tui::ui::global_listener().to_boxed(); + let global = tui::realm::ui::global_listener().to_boxed(); app.mount( Cid::GlobalListener, global, vec![Sub::new( - subscription::quit_clause(Key::Char('q')), + subscription::quit_clause(tuirealm::event::Key::Char('q')), SubClause::Always, )], )?; diff --git a/bin/commands/inbox/realm/select/event.rs b/bin/commands/inbox/realm/select/event.rs new file mode 100644 index 00000000..8d6d3bb2 --- /dev/null +++ b/bin/commands/inbox/realm/select/event.rs @@ -0,0 +1,161 @@ +use radicle::node::notifications::NotificationId; + +use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection}; +use tuirealm::event::{Event, Key, KeyEvent}; +use tuirealm::{MockComponent, NoUserEvent}; + +use radicle_tui as tui; + +use tui::realm::ui::state::ItemState; +use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer}; +use tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use tui::realm::ui::widget::list::PropertyList; +use tui::realm::ui::widget::Widget; +use tui::{Id, SelectionExit}; + +use super::ui::{IdSelect, OperationSelect}; +use super::{InboxOperation, 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 for Widget { + fn on(&mut self, event: Event) -> Option { + match event { + Event::Keyboard(KeyEvent { + code: Key::Char('q'), + .. + }) => Some(Message::Quit(None)), + _ => None, + } + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, event: Event) -> Option { + let mut submit = || -> Option { + match self.perform(Cmd::Submit) { + CmdResult::Submit(state) => { + let selected = ItemState::try_from(state).ok()?.selected()?; + let item = self.items().get(selected)?; + Some(item.id().to_owned()) + } + _ => None, + } + }; + + match event { + Event::Keyboard(KeyEvent { code: Key::Up, .. }) + | Event::Keyboard(KeyEvent { + code: Key::Char('k'), + .. + }) => { + self.perform(Cmd::Move(MoveDirection::Up)); + Some(Message::Tick) + } + Event::Keyboard(KeyEvent { + code: Key::Down, .. + }) + | Event::Keyboard(KeyEvent { + code: Key::Char('j'), + .. + }) => { + self.perform(Cmd::Move(MoveDirection::Down)); + Some(Message::Tick) + } + Event::Keyboard(KeyEvent { + code: Key::Enter, .. + }) => submit().map(|id| { + let output = SelectionExit::default().with_id(Id::Notification(id)); + Message::Quit(Some(output)) + }), + _ => None, + } + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, event: Event) -> Option { + let mut submit = || -> Option { + match self.perform(Cmd::Submit) { + CmdResult::Submit(state) => { + let selected = ItemState::try_from(state).ok()?.selected()?; + let item = self.items().get(selected)?; + Some(item.id().to_owned()) + } + _ => None, + } + }; + + match event { + Event::Keyboard(KeyEvent { code: Key::Up, .. }) + | Event::Keyboard(KeyEvent { + code: Key::Char('k'), + .. + }) => { + self.perform(Cmd::Move(MoveDirection::Up)); + Some(Message::Tick) + } + Event::Keyboard(KeyEvent { + code: Key::Down, .. + }) + | Event::Keyboard(KeyEvent { + code: Key::Char('j'), + .. + }) => { + self.perform(Cmd::Move(MoveDirection::Down)); + Some(Message::Tick) + } + Event::Keyboard(KeyEvent { + code: Key::Enter, .. + }) => submit().map(|id| { + let exit = SelectionExit::default() + .with_operation(InboxOperation::Show.to_string()) + .with_id(Id::Notification(id)); + Message::Quit(Some(exit)) + }), + Event::Keyboard(KeyEvent { + code: Key::Char('c'), + .. + }) => submit().map(|id| { + let exit = SelectionExit::default() + .with_operation(InboxOperation::Clear.to_string()) + .with_id(Id::Notification(id)); + Message::Quit(Some(exit)) + }), + _ => None, + } + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, _event: Event) -> Option { + None + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, _event: Event) -> Option { + None + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, _event: Event) -> Option { + None + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, _event: Event) -> Option { + None + } +} + +impl tuirealm::Component for Widget { + fn on(&mut self, _event: Event) -> Option { + None + } +} diff --git a/bin/commands/inbox/realm/select/page.rs b/bin/commands/inbox/realm/select/page.rs new file mode 100644 index 00000000..1affd72a --- /dev/null +++ b/bin/commands/inbox/realm/select/page.rs @@ -0,0 +1,168 @@ +use std::collections::HashMap; + +use anyhow::Result; + +use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent}; + +use radicle_tui as tui; + +use tui::common::cob::inbox::{Filter, SortBy}; +use tui::common::context::Context; +use tui::realm::ui::layout; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ViewPage; + +use super::{ui, Application, Cid, ListCid, Message, Mode}; + +/// +/// Home +/// +pub struct ListView { + active_component: ListCid, + mode: Mode, + filter: Filter, + sort_by: SortBy, + shortcuts: HashMap>, +} + +impl ListView { + pub fn new(mode: Mode, filter: Filter, sort_by: SortBy) -> Self { + Self { + active_component: ListCid::NotificationBrowser, + mode, + filter, + sort_by, + shortcuts: HashMap::default(), + } + } + + fn update_context( + &self, + app: &mut Application, + 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: ListCid, + ) -> Result<()> { + if let Some(shortcuts) = self.shortcuts.get(&cid) { + app.remount( + Cid::List(ListCid::Shortcuts), + shortcuts.clone().to_boxed(), + vec![], + )?; + } + + Ok(()) + } +} + +impl ViewPage for ListView { + fn mount( + &mut self, + app: &mut Application, + context: &Context, + theme: &Theme, + ) -> Result<()> { + let browser = ui::operation_select(theme, context, self.filter.clone(), self.sort_by, None) + .to_boxed(); + self.shortcuts = browser.as_ref().shortcuts(); + + match self.mode { + Mode::Id => { + let notif_browser = + ui::id_select(theme, context, self.filter.clone(), self.sort_by, None) + .to_boxed(); + self.shortcuts = notif_browser.as_ref().shortcuts(); + + app.remount(Cid::List(ListCid::NotificationBrowser), browser, vec![])?; + } + Mode::Operation => { + let notif_browser = + ui::operation_select(theme, context, self.filter.clone(), self.sort_by, None) + .to_boxed(); + self.shortcuts = notif_browser.as_ref().shortcuts(); + + app.remount(Cid::List(ListCid::NotificationBrowser), browser, vec![])?; + } + }; + + app.active(&Cid::List(self.active_component.clone()))?; + self.update_shortcuts(app, self.active_component.clone())?; + self.update_context(app, context, theme)?; + + Ok(()) + } + + fn unmount(&self, app: &mut Application) -> 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, + context: &Context, + theme: &Theme, + _message: Message, + ) -> Result> { + self.update_context(app, context, theme)?; + + Ok(None) + } + + fn view(&mut self, app: &mut Application, 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) -> Result<()> { + Ok(()) + } + + fn unsubscribe(&self, _app: &mut Application) -> Result<()> { + Ok(()) + } +} diff --git a/bin/commands/inbox/realm/select/ui.rs b/bin/commands/inbox/realm/select/ui.rs new file mode 100644 index 00000000..455f161c --- /dev/null +++ b/bin/commands/inbox/realm/select/ui.rs @@ -0,0 +1,267 @@ +use std::collections::HashMap; + +use radicle::node::notifications::Notification; + +use tuirealm::command::{Cmd, CmdResult}; +use tuirealm::tui::layout::Rect; +use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State}; + +use radicle_tui as tui; + +use tui::common::cob::inbox::{Filter, SortBy}; +use tui::common::context::Context; +use tui::realm::ui::cob::NotificationItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::context::{ContextBar, Progress, Shortcuts}; +use tui::realm::ui::widget::label::{self}; +use tui::realm::ui::widget::list::{ColumnWidth, Table}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; + +use super::ListCid; + +pub struct NotificationBrowser { + items: Vec, + table: Widget>, +} + +impl NotificationBrowser { + pub fn new( + theme: &Theme, + context: &Context, + sort_by: SortBy, + selected: Option, + ) -> Self { + let header = [ + label::header(""), + label::header(" ● "), + label::header("Type"), + label::header("Summary"), + label::header("ID"), + label::header("Status"), + label::header("Updated"), + ]; + let widths = [ + ColumnWidth::Fixed(5), + ColumnWidth::Fixed(3), + ColumnWidth::Fixed(6), + ColumnWidth::Grow, + ColumnWidth::Fixed(15), + ColumnWidth::Fixed(10), + ColumnWidth::Fixed(18), + ]; + + let mut items = vec![]; + for notification in context.notifications() { + if let Ok(item) = + NotificationItem::try_from((context.repository(), notification.clone())) + { + items.push(item); + } + } + + match sort_by.field { + "timestamp" => items.sort_by(|a, b| b.timestamp().cmp(a.timestamp())), + "id" => items.sort_by(|a, b| b.id().cmp(a.id())), + _ => {} + } + if sort_by.reverse { + items.reverse(); + } + + let selected = match selected { + Some(notif) => { + Some(NotificationItem::try_from((context.repository(), notif.clone())).unwrap()) + } + _ => items.first().cloned(), + }; + + let table = Widget::new(Table::new(&items, selected, header, widths, theme.clone())); + + Self { items, table } + } + + pub fn items(&self) -> &Vec { + &self.items + } +} + +impl WidgetComponent for NotificationBrowser { + fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) { + let focus = properties + .get_or(Attribute::Focus, AttrValue::Flag(false)) + .unwrap_flag(); + + self.table.attr(Attribute::Focus, AttrValue::Flag(focus)); + self.table.view(frame, area); + } + + fn state(&self) -> State { + self.table.state() + } + + fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult { + self.table.perform(cmd) + } +} + +pub struct IdSelect { + theme: Theme, + browser: Widget, +} + +impl IdSelect { + pub fn new(theme: Theme, browser: Widget) -> Self { + Self { theme, browser } + } + + pub fn items(&self) -> &Vec { + self.browser.items() + } + + pub fn shortcuts(&self) -> HashMap> { + [( + ListCid::NotificationBrowser, + tui::realm::ui::shortcuts( + &self.theme, + vec![ + tui::realm::ui::shortcut(&self.theme, "enter", "select"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), + ], + ), + )] + .iter() + .cloned() + .collect() + } +} + +impl WidgetComponent for IdSelect { + fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) { + let focus = properties + .get_or(Attribute::Focus, AttrValue::Flag(false)) + .unwrap_flag(); + + self.browser.attr(Attribute::Focus, AttrValue::Flag(focus)); + self.browser.view(frame, area); + } + + fn state(&self) -> State { + self.browser.state() + } + + fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult { + self.browser.perform(cmd) + } +} + +pub struct OperationSelect { + theme: Theme, + browser: Widget, +} + +impl OperationSelect { + pub fn new(theme: Theme, browser: Widget) -> Self { + Self { theme, browser } + } + + pub fn items(&self) -> &Vec { + self.browser.items() + } + + pub fn shortcuts(&self) -> HashMap> { + [( + ListCid::NotificationBrowser, + tui::realm::ui::shortcuts( + &self.theme, + vec![ + tui::realm::ui::shortcut(&self.theme, "enter", "show"), + tui::realm::ui::shortcut(&self.theme, "c", "clear"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), + ], + ), + )] + .iter() + .cloned() + .collect() + } +} + +impl WidgetComponent for OperationSelect { + fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) { + let focus = properties + .get_or(Attribute::Focus, AttrValue::Flag(false)) + .unwrap_flag(); + + self.browser.attr(Attribute::Focus, AttrValue::Flag(focus)); + self.browser.view(frame, area); + } + + fn state(&self) -> State { + self.browser.state() + } + + fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult { + self.browser.perform(cmd) + } +} + +pub fn id_select( + theme: &Theme, + context: &Context, + _filter: Filter, + sort_by: SortBy, + selected: Option, +) -> Widget { + let browser = Widget::new(NotificationBrowser::new(theme, context, sort_by, selected)); + + Widget::new(IdSelect::new(theme.clone(), browser)) +} + +pub fn operation_select( + theme: &Theme, + context: &Context, + _filter: Filter, + sort_by: SortBy, + selected: Option, +) -> Widget { + let browser = Widget::new(NotificationBrowser::new(theme, context, sort_by, selected)); + + Widget::new(OperationSelect::new(theme.clone(), browser)) +} + +pub fn browse_context( + _context: &Context, + _theme: &Theme, + _filter: Filter, + progress: Progress, +) -> Widget { + 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) +} diff --git a/bin/commands/inbox/select/event.rs b/bin/commands/inbox/select/event.rs index 8e33ae96..8d6d3bb2 100644 --- a/bin/commands/inbox/select/event.rs +++ b/bin/commands/inbox/select/event.rs @@ -6,11 +6,11 @@ use tuirealm::{MockComponent, NoUserEvent}; use radicle_tui as tui; -use tui::ui::state::ItemState; -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::realm::ui::state::ItemState; +use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer}; +use tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use tui::realm::ui::widget::list::PropertyList; +use tui::realm::ui::widget::Widget; use tui::{Id, SelectionExit}; use super::ui::{IdSelect, OperationSelect}; diff --git a/bin/commands/inbox/select/page.rs b/bin/commands/inbox/select/page.rs index 42f055d5..1affd72a 100644 --- a/bin/commands/inbox/select/page.rs +++ b/bin/commands/inbox/select/page.rs @@ -6,14 +6,14 @@ use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent}; use radicle_tui as tui; -use tui::cob::inbox::{Filter, SortBy}; -use tui::context::Context; -use tui::ui::layout; -use tui::ui::state::ItemState; -use tui::ui::theme::Theme; -use tui::ui::widget::context::{Progress, Shortcuts}; -use tui::ui::widget::Widget; -use tui::ViewPage; +use tui::common::cob::inbox::{Filter, SortBy}; +use tui::common::context::Context; +use tui::realm::ui::layout; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ViewPage; use super::{ui, Application, Cid, ListCid, Message, Mode}; diff --git a/bin/commands/inbox/select/ui.rs b/bin/commands/inbox/select/ui.rs index f4f938bd..455f161c 100644 --- a/bin/commands/inbox/select/ui.rs +++ b/bin/commands/inbox/select/ui.rs @@ -2,20 +2,20 @@ use std::collections::HashMap; use radicle::node::notifications::Notification; -use tui::ui::cob::NotificationItem; -use tui::ui::widget::list::{ColumnWidth, Table}; 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, SortBy}; -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 tui::common::cob::inbox::{Filter, SortBy}; +use tui::common::context::Context; +use tui::realm::ui::cob::NotificationItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::context::{ContextBar, Progress, Shortcuts}; +use tui::realm::ui::widget::label::{self}; +use tui::realm::ui::widget::list::{ColumnWidth, Table}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; use super::ListCid; @@ -121,11 +121,11 @@ impl IdSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::NotificationBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "select"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "select"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] @@ -171,12 +171,12 @@ impl OperationSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::NotificationBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "show"), - tui::ui::shortcut(&self.theme, "c", "clear"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "show"), + tui::realm::ui::shortcut(&self.theme, "c", "clear"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] diff --git a/bin/commands/issue.rs b/bin/commands/issue.rs index 09b7a2fe..ecda0112 100644 --- a/bin/commands/issue.rs +++ b/bin/commands/issue.rs @@ -1,9 +1,9 @@ +#[cfg(feature = "realm")] +#[path = "issue/realm.rs"] +mod realm; + #[path = "issue/common.rs"] mod common; -#[path = "issue/select.rs"] -mod select; -#[path = "issue/suite.rs"] -mod suite; use std::ffi::OsString; @@ -11,13 +11,11 @@ use anyhow::anyhow; use radicle_tui as tui; -use tui::cob::issue::{self, State}; -use tui::{context, log, Window}; +use tui::common::cob::issue::{self, State}; use crate::terminal; use crate::terminal::args::{Args, Error, Help}; -pub const FPS: u64 = 60; pub const HELP: Help = Help { name: "issue", description: "Terminal interfaces for issues", @@ -55,7 +53,7 @@ pub enum OperationName { #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct SelectOptions { - mode: select::Mode, + mode: common::Mode, filter: issue::Filter, } @@ -79,8 +77,8 @@ impl Args for Options { let val = val.to_str().unwrap_or_default(); select_opts.mode = match val { - "operation" => select::Mode::Operation, - "id" => select::Mode::Id, + "operation" => common::Mode::Operation, + "id" => common::Mode::Id, unknown => anyhow::bail!("unknown mode '{}'", unknown), }; } @@ -120,7 +118,13 @@ impl Args for Options { } } +#[cfg(feature = "realm")] pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + use tui::common::context; + use tui::common::log; + use tui::realm::Window; + + pub const FPS: u64 = 60; let (_, id) = radicle::rad::cwd() .map_err(|_| anyhow!("this command must be run in the context of a project"))?; @@ -131,7 +135,7 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> log::enable(context.profile(), "issue", "select")?; - let mut app = select::App::new(context, opts.mode.clone(), opts.filter.clone()); + let mut app = realm::select::App::new(context, opts.mode.clone(), opts.filter.clone()); let output = Window::default().run(&mut app, 1000 / FPS)?; let output = output @@ -144,3 +148,12 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> Ok(()) } + +#[cfg(feature = "flux")] +pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + match options.op { + Operation::Select { opts: _ } => { + anyhow::bail!("operation not yet implemented with flux") + } + } +} diff --git a/bin/commands/issue/common.rs b/bin/commands/issue/common.rs index 6c6eb76c..678697d9 100644 --- a/bin/commands/issue/common.rs +++ b/bin/commands/issue/common.rs @@ -1,2 +1,9 @@ -#[path = "common/ui.rs"] -pub mod ui; +/// The application's mode. 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, +} diff --git a/bin/commands/issue/realm.rs b/bin/commands/issue/realm.rs new file mode 100644 index 00000000..31f9ee56 --- /dev/null +++ b/bin/commands/issue/realm.rs @@ -0,0 +1,6 @@ +#[path = "realm/common.rs"] +pub mod common; +#[path = "realm/select.rs"] +pub mod select; +#[path = "realm/suite.rs"] +pub mod suite; diff --git a/bin/commands/issue/realm/common.rs b/bin/commands/issue/realm/common.rs new file mode 100644 index 00000000..6c6eb76c --- /dev/null +++ b/bin/commands/issue/realm/common.rs @@ -0,0 +1,2 @@ +#[path = "common/ui.rs"] +pub mod ui; diff --git a/bin/commands/issue/common/ui.rs b/bin/commands/issue/realm/common/ui.rs similarity index 91% rename from bin/commands/issue/common/ui.rs rename to bin/commands/issue/realm/common/ui.rs index b8520d18..c14490ca 100644 --- a/bin/commands/issue/common/ui.rs +++ b/bin/commands/issue/realm/common/ui.rs @@ -6,15 +6,14 @@ use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State}; use radicle_tui as tui; -use tui::cob::issue::Filter; -use tui::context::Context; -use tui::ui::cob::IssueItem; -use tui::ui::theme::{style, Theme}; -use tui::ui::widget::context::{ContextBar, Progress}; -use tui::ui::widget::{Widget, WidgetComponent}; - -use tui::ui::widget::label::{self}; -use tui::ui::widget::list::{ColumnWidth, Table}; +use tui::common::cob::issue::Filter; +use tui::common::context::Context; +use tui::realm::ui::cob::IssueItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::context::{ContextBar, Progress}; +use tui::realm::ui::widget::label::{self}; +use tui::realm::ui::widget::list::{ColumnWidth, Table}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; pub struct IssueBrowser { items: Vec, diff --git a/bin/commands/issue/select.rs b/bin/commands/issue/realm/select.rs similarity index 91% rename from bin/commands/issue/select.rs rename to bin/commands/issue/realm/select.rs index 6ee77fa8..7b5a2d55 100644 --- a/bin/commands/issue/select.rs +++ b/bin/commands/issue/realm/select.rs @@ -17,15 +17,18 @@ use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause}; use radicle_tui as tui; -use tui::cob::issue::Filter; -use tui::context::Context; +use tui::common::cob::issue::Filter; +use tui::common::context::Context; -use tui::ui::subscription; -use tui::ui::theme::Theme; -use tui::{Exit, PageStack, SelectionExit, Tui}; +use tui::realm::ui::subscription; +use tui::realm::ui::theme::Theme; +use tui::realm::{PageStack, Tui}; +use tui::{Exit, SelectionExit}; use page::ListView; +use super::super::common::Mode; + /// Wrapper around radicle's `PatchId` that serializes /// to a human-readable string. #[derive(Clone, Debug, Eq, PartialEq)] @@ -52,17 +55,6 @@ impl Serialize for PatchId { } } -/// 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)] @@ -190,7 +182,7 @@ impl Tui for App { self.view_list(app, &self.theme.clone())?; // Add global key listener and subscribe to key events - let global = tui::ui::global_listener().to_boxed(); + let global = tui::realm::ui::global_listener().to_boxed(); app.mount( Cid::GlobalListener, global, diff --git a/bin/commands/issue/select/event.rs b/bin/commands/issue/realm/select/event.rs similarity index 95% rename from bin/commands/issue/select/event.rs rename to bin/commands/issue/realm/select/event.rs index 7bce99ac..7cf7cf4a 100644 --- a/bin/commands/issue/select/event.rs +++ b/bin/commands/issue/realm/select/event.rs @@ -4,11 +4,11 @@ use tuirealm::{MockComponent, NoUserEvent}; use radicle_tui as tui; -use tui::ui::state::ItemState; -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::realm::ui::state::ItemState; +use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer}; +use tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use tui::realm::ui::widget::list::PropertyList; +use tui::realm::ui::widget::Widget; use tui::{Id, SelectionExit}; use super::ui::{IdSelect, OperationSelect}; diff --git a/bin/commands/patch/select/page.rs b/bin/commands/issue/realm/select/page.rs similarity index 92% rename from bin/commands/patch/select/page.rs rename to bin/commands/issue/realm/select/page.rs index 99886588..310f22f4 100644 --- a/bin/commands/patch/select/page.rs +++ b/bin/commands/issue/realm/select/page.rs @@ -2,18 +2,18 @@ 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::patch::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 tui::common::cob::issue::Filter; +use tui::common::context::Context; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ui::{layout, subscription}; +use tui::realm::ViewPage; use super::super::common; use super::{ui, Application, Cid, ListCid, Message, Mode}; @@ -88,7 +88,7 @@ impl ViewPage for ListView { theme: &Theme, ) -> Result<()> { let navigation = ui::list_navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); app.remount(Cid::List(ListCid::Header), header, vec![])?; diff --git a/bin/commands/issue/select/ui.rs b/bin/commands/issue/realm/select/ui.rs similarity index 77% rename from bin/commands/issue/select/ui.rs rename to bin/commands/issue/realm/select/ui.rs index 0e0598a9..39ce8215 100644 --- a/bin/commands/issue/select/ui.rs +++ b/bin/commands/issue/realm/select/ui.rs @@ -8,14 +8,14 @@ use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State}; use radicle_tui as tui; -use tui::cob::issue::Filter; -use tui::context::Context; -use tui::ui::cob::IssueItem; -use tui::ui::theme::{style, Theme}; -use tui::ui::widget::container::Tabs; -use tui::ui::widget::context::Shortcuts; -use tui::ui::widget::label::{self}; -use tui::ui::widget::{Widget, WidgetComponent}; +use tui::common::cob::issue::Filter; +use tui::common::context::Context; +use tui::realm::ui::cob::IssueItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::container::Tabs; +use tui::realm::ui::widget::context::Shortcuts; +use tui::realm::ui::widget::label::{self}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; use super::super::common; use super::ListCid; @@ -37,11 +37,11 @@ impl IdSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::PatchBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "select"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "select"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] @@ -87,14 +87,14 @@ impl OperationSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::PatchBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "show"), - tui::ui::shortcut(&self.theme, "m", "comment"), - tui::ui::shortcut(&self.theme, "e", "edit"), - tui::ui::shortcut(&self.theme, "d", "delete"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "show"), + tui::realm::ui::shortcut(&self.theme, "m", "comment"), + tui::realm::ui::shortcut(&self.theme, "e", "edit"), + tui::realm::ui::shortcut(&self.theme, "d", "delete"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] @@ -124,7 +124,7 @@ impl WidgetComponent for OperationSelect { } pub fn list_navigation(theme: &Theme) -> Widget { - tui::ui::tabs( + tui::realm::ui::tabs( theme, vec![label::reversable("Patches").style(style::cyan())], ) diff --git a/bin/commands/issue/suite.rs b/bin/commands/issue/realm/suite.rs similarity index 95% rename from bin/commands/issue/suite.rs rename to bin/commands/issue/realm/suite.rs index fbeb8b2e..7f65b564 100644 --- a/bin/commands/issue/suite.rs +++ b/bin/commands/issue/realm/suite.rs @@ -15,11 +15,12 @@ use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause}; use radicle_tui as tui; -use tui::cob; -use tui::context::Context; -use tui::ui::subscription; -use tui::ui::theme::Theme; -use tui::{Exit, PageStack, Tui}; +use tui::common::cob; +use tui::common::context::Context; +use tui::realm::ui::subscription; +use tui::realm::ui::theme::Theme; +use tui::realm::{PageStack, Tui}; +use tui::Exit; use page::{IssuePage, ListPage}; @@ -237,7 +238,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::info(theme, message); + let popup = tui::realm::ui::info(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -250,7 +251,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::warning(theme, message); + let popup = tui::realm::ui::warning(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -263,7 +264,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::error(theme, message); + let popup = tui::realm::ui::error(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -306,7 +307,7 @@ impl Tui for App { self.view_list(app, &self.theme.clone())?; // Add global key listener and subscribe to key events - let global = tui::ui::global_listener().to_boxed(); + let global = tui::realm::ui::global_listener().to_boxed(); app.mount( Cid::GlobalListener, global, diff --git a/bin/commands/issue/suite/event.rs b/bin/commands/issue/realm/suite/event.rs similarity index 97% rename from bin/commands/issue/suite/event.rs rename to bin/commands/issue/realm/suite/event.rs index e698dfcf..d8d2e7ab 100644 --- a/bin/commands/issue/suite/event.rs +++ b/bin/commands/issue/realm/suite/event.rs @@ -1,17 +1,17 @@ use radicle::cob::issue::IssueId; -use tui::ui::state::ItemState; + use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection, Position}; use tuirealm::event::{Event, Key, KeyEvent, KeyModifiers}; use tuirealm::{MockComponent, NoUserEvent, State, StateValue}; use radicle_tui as tui; -use tui::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer, Popup}; -use tui::ui::widget::context::{ContextBar, Shortcuts}; -use tui::ui::widget::form::Form; -use tui::ui::widget::list::PropertyList; - -use tui::ui::widget::Widget; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer, Popup}; +use tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use tui::realm::ui::widget::form::Form; +use tui::realm::ui::widget::list::PropertyList; +use tui::realm::ui::widget::Widget; use super::ui; use super::{IssueCid, IssueMessage, Message, PopupMessage}; diff --git a/bin/commands/issue/suite/page.rs b/bin/commands/issue/realm/suite/page.rs similarity index 90% rename from bin/commands/issue/suite/page.rs rename to bin/commands/issue/realm/suite/page.rs index 9ca78e47..90b3cfe8 100644 --- a/bin/commands/issue/suite/page.rs +++ b/bin/commands/issue/realm/suite/page.rs @@ -4,19 +4,19 @@ use anyhow::Result; use radicle::cob::issue::{Issue, IssueId}; -use tui::ui::state::ItemState; use tuirealm::event::Key; use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent, State, StateValue, Sub, SubClause}; use radicle_tui as tui; -use tui::cob; -use tui::context::Context; -use tui::ui::layout; -use tui::ui::theme::Theme; -use tui::ui::widget::context::{Progress, Shortcuts}; -use tui::ui::widget::Widget; -use tui::ViewPage; +use tui::common::cob; +use tui::common::context::Context; +use tui::realm::ui::layout; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ViewPage; use super::{ Application, Cid, IssueCid, IssueCobMessage, IssueMessage, ListCid, Message, PopupMessage, @@ -58,14 +58,14 @@ impl ListPage { fn build_shortcuts(theme: &Theme) -> HashMap> { [( ListCid::IssueBrowser, - tui::ui::shortcuts( + tui::realm::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, "o", "open"), - tui::ui::shortcut(theme, "q", "quit"), + tui::realm::ui::shortcut(theme, "tab", "section"), + tui::realm::ui::shortcut(theme, "↑/↓", "navigate"), + tui::realm::ui::shortcut(theme, "enter", "show"), + tui::realm::ui::shortcut(theme, "o", "open"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), )] @@ -122,7 +122,7 @@ impl ViewPage for ListPage { theme: &Theme, ) -> Result<()> { let navigation = ui::list_navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); let issue_browser = ui::issues(context, theme, None).to_boxed(); app.remount(Cid::List(ListCid::Header), header, vec![])?; @@ -245,36 +245,36 @@ impl IssuePage { [ ( IssueCid::List, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( theme, vec![ - tui::ui::shortcut(theme, "esc", "back"), - tui::ui::shortcut(theme, "↑/↓", "navigate"), - tui::ui::shortcut(theme, "enter", "show"), - tui::ui::shortcut(theme, "o", "open"), - tui::ui::shortcut(theme, "q", "quit"), + tui::realm::ui::shortcut(theme, "esc", "back"), + tui::realm::ui::shortcut(theme, "↑/↓", "navigate"), + tui::realm::ui::shortcut(theme, "enter", "show"), + tui::realm::ui::shortcut(theme, "o", "open"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), ), ( IssueCid::Details, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( theme, vec![ - tui::ui::shortcut(theme, "esc", "back"), - tui::ui::shortcut(theme, "↑/↓", "scroll"), - tui::ui::shortcut(theme, "q", "quit"), + tui::realm::ui::shortcut(theme, "esc", "back"), + tui::realm::ui::shortcut(theme, "↑/↓", "scroll"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), ), ( IssueCid::Form, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( theme, vec![ - tui::ui::shortcut(theme, "esc", "back"), - tui::ui::shortcut(theme, "shift + tab / tab", "navigate"), - tui::ui::shortcut(theme, "ctrl + s", "submit"), + tui::realm::ui::shortcut(theme, "esc", "back"), + tui::realm::ui::shortcut(theme, "shift + tab / tab", "navigate"), + tui::realm::ui::shortcut(theme, "ctrl + s", "submit"), ], ), ), @@ -350,7 +350,7 @@ impl ViewPage for IssuePage { theme: &Theme, ) -> Result<()> { let navigation = ui::list_navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); let list = ui::list(context, theme, self.issue.clone()).to_boxed(); app.remount(Cid::Issue(IssueCid::Header), header, vec![])?; diff --git a/bin/commands/issue/suite/ui.rs b/bin/commands/issue/realm/suite/ui.rs similarity index 91% rename from bin/commands/issue/suite/ui.rs rename to bin/commands/issue/realm/suite/ui.rs index cc72c95e..79d5c167 100644 --- a/bin/commands/issue/suite/ui.rs +++ b/bin/commands/issue/realm/suite/ui.rs @@ -6,24 +6,23 @@ use radicle::cob::thread::CommentId; use radicle::cob::issue::Issue; use radicle::cob::issue::IssueId; -use tui::ui::theme::style; use tuirealm::command::{Cmd, CmdResult}; use tuirealm::tui::layout::{Constraint, Direction, 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::IssueItem; -use tui::ui::theme::Theme; -use tui::ui::widget::{Widget, WidgetComponent}; - -use tui::ui::widget::container::{Container, Tabs}; -use tui::ui::widget::context::{ContextBar, Progress}; -use tui::ui::widget::form::{Form, TextArea, TextField}; -use tui::ui::widget::label::{self, Textarea}; -use tui::ui::widget::list::{ColumnWidth, List, Property, Table}; +use tui::common::context::Context; +use tui::realm::ui::cob; +use tui::realm::ui::cob::IssueItem; +use tui::realm::ui::theme::style; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::container::{Container, Tabs}; +use tui::realm::ui::widget::context::{ContextBar, Progress}; +use tui::realm::ui::widget::form::{Form, TextArea, TextField}; +use tui::realm::ui::widget::label::{self, Textarea}; +use tui::realm::ui::widget::list::{ColumnWidth, List, Property, Table}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; pub const FORM_ID_EDIT: &str = "edit-form"; @@ -124,7 +123,7 @@ impl LargeList { let list = Widget::new(List::new(&items, selected, theme.clone())); - let container = tui::ui::container(theme, list.to_boxed()); + let container = tui::realm::ui::container(theme, list.to_boxed()); Self { items, @@ -205,7 +204,7 @@ impl IssueHeader { label::default(&item.state().to_string()), ); - let table = tui::ui::property_table( + let table = tui::realm::ui::property_table( theme, vec![ Widget::new(title), @@ -216,7 +215,7 @@ impl IssueHeader { Widget::new(state), ], ); - let container = tui::ui::container(theme, table.to_boxed()); + let container = tui::realm::ui::container(theme, table.to_boxed()); Self { container } } @@ -295,7 +294,7 @@ impl CommentBody { .content(AttrValue::String(content)) .style(style::reset()); - let textarea = tui::ui::container(theme, textarea.to_boxed()); + let textarea = tui::realm::ui::container(theme, textarea.to_boxed()); Self { textarea } } @@ -321,7 +320,7 @@ impl WidgetComponent for CommentBody { } pub fn list_navigation(theme: &Theme) -> Widget { - tui::ui::tabs( + tui::realm::ui::tabs( theme, vec![label::reversable("Issues").style(style::magenta())], ) @@ -404,7 +403,7 @@ pub fn browse_context(context: &Context, theme: &Theme, progress: Progress) -> W .collect::>() .len(); - tui::ui::widget::context::bar( + tui::realm::ui::widget::context::bar( theme, "Browse", "", @@ -419,11 +418,11 @@ pub fn description_context( theme: &Theme, progress: Progress, ) -> Widget { - tui::ui::widget::context::bar(theme, "Show", "", "", "", &progress.to_string()) + tui::realm::ui::widget::context::bar(theme, "Show", "", "", "", &progress.to_string()) } pub fn form_context(_context: &Context, theme: &Theme, progress: Progress) -> Widget { - tui::ui::widget::context::bar(theme, "Open", "", "", "", &progress.to_string()) + tui::realm::ui::widget::context::bar(theme, "Open", "", "", "", &progress.to_string()) .custom(ContextBar::PROP_EDIT_MODE, AttrValue::Flag(true)) } diff --git a/bin/commands/patch.rs b/bin/commands/patch.rs index edcda25a..54891c69 100644 --- a/bin/commands/patch.rs +++ b/bin/commands/patch.rs @@ -1,9 +1,9 @@ +#[cfg(feature = "realm")] +#[path = "patch/realm.rs"] +mod realm; + #[path = "patch/common.rs"] mod common; -#[path = "patch/select.rs"] -mod select; -#[path = "patch/suite.rs"] -mod suite; use std::ffi::OsString; @@ -11,13 +11,11 @@ use anyhow::anyhow; use radicle_tui as tui; -use tui::cob::patch::{self, State}; -use tui::{context, log, Window}; +use tui::common::cob::patch::{self, State}; use crate::terminal; use crate::terminal::args::{Args, Error, Help}; -pub const FPS: u64 = 60; pub const HELP: Help = Help { name: "patch", description: "Terminal interfaces for patches", @@ -64,7 +62,7 @@ pub enum OperationName { #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct SelectOptions { - mode: select::Mode, + mode: common::Mode, filter: patch::Filter, } @@ -88,8 +86,8 @@ impl Args for Options { let val = val.to_str().unwrap_or_default(); select_opts.mode = match val { - "operation" => select::Mode::Operation, - "id" => select::Mode::Id, + "operation" => common::Mode::Operation, + "id" => common::Mode::Id, unknown => anyhow::bail!("unknown mode '{}'", unknown), }; } @@ -132,7 +130,13 @@ impl Args for Options { } } +#[cfg(feature = "realm")] pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + use tui::common::context; + use tui::common::log; + use tui::realm::Window; + + pub const FPS: u64 = 60; let (_, id) = radicle::rad::cwd() .map_err(|_| anyhow!("this command must be run in the context of a project"))?; @@ -143,7 +147,7 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> log::enable(context.profile(), "patch", "select")?; - let mut app = select::App::new(context, opts.mode.clone(), opts.filter.clone()); + let mut app = realm::select::App::new(context, opts.mode.clone(), opts.filter.clone()); let output = Window::default().run(&mut app, 1000 / FPS)?; let output = output @@ -156,3 +160,12 @@ pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> Ok(()) } + +#[cfg(feature = "flux")] +pub fn run(options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> { + match options.op { + Operation::Select { opts: _ } => { + anyhow::bail!("operation not yet implemented with flux") + } + } +} diff --git a/bin/commands/patch/common.rs b/bin/commands/patch/common.rs index 6c6eb76c..af1d92f7 100644 --- a/bin/commands/patch/common.rs +++ b/bin/commands/patch/common.rs @@ -1,2 +1,10 @@ -#[path = "common/ui.rs"] -pub mod ui; +/// The application's mode. 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, +} diff --git a/bin/commands/patch/realm.rs b/bin/commands/patch/realm.rs new file mode 100644 index 00000000..31f9ee56 --- /dev/null +++ b/bin/commands/patch/realm.rs @@ -0,0 +1,6 @@ +#[path = "realm/common.rs"] +pub mod common; +#[path = "realm/select.rs"] +pub mod select; +#[path = "realm/suite.rs"] +pub mod suite; diff --git a/bin/commands/patch/realm/common.rs b/bin/commands/patch/realm/common.rs new file mode 100644 index 00000000..6c6eb76c --- /dev/null +++ b/bin/commands/patch/realm/common.rs @@ -0,0 +1,2 @@ +#[path = "common/ui.rs"] +pub mod ui; diff --git a/bin/commands/patch/common/ui.rs b/bin/commands/patch/realm/common/ui.rs similarity index 92% rename from bin/commands/patch/common/ui.rs rename to bin/commands/patch/realm/common/ui.rs index 6e12e7d4..ec43cd6f 100644 --- a/bin/commands/patch/common/ui.rs +++ b/bin/commands/patch/realm/common/ui.rs @@ -1,20 +1,19 @@ use radicle::cob::patch::{Patch, PatchId}; -use tui::ui::widget::context::{ContextBar, Progress}; 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::patch::Filter; -use tui::context::Context; -use tui::ui::cob::PatchItem; -use tui::ui::theme::{style, Theme}; -use tui::ui::widget::{Widget, WidgetComponent}; - -use tui::ui::widget::label::{self}; -use tui::ui::widget::list::{ColumnWidth, Table}; +use tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::cob::PatchItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::context::{ContextBar, Progress}; +use tui::realm::ui::widget::label::{self}; +use tui::realm::ui::widget::list::{ColumnWidth, Table}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; pub struct PatchBrowser { items: Vec, diff --git a/bin/commands/patch/select.rs b/bin/commands/patch/realm/select.rs similarity index 91% rename from bin/commands/patch/select.rs rename to bin/commands/patch/realm/select.rs index 2400cd3b..43a3cef7 100644 --- a/bin/commands/patch/select.rs +++ b/bin/commands/patch/realm/select.rs @@ -17,24 +17,17 @@ use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause}; use radicle_tui as tui; -use tui::cob::patch::Filter; -use tui::context::Context; +use tui::common::cob::patch::Filter; +use tui::common::context::Context; -use tui::ui::subscription; -use tui::ui::theme::Theme; -use tui::{Exit, PageStack, SelectionExit, Tui}; +use tui::realm::ui::subscription; +use tui::realm::ui::theme::Theme; +use tui::realm::{PageStack, Tui}; +use tui::{Exit, SelectionExit}; use page::ListView; -/// The application's mode. 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, -} +use super::super::common::Mode; /// The selected patch operation returned by the operation /// selection widget. @@ -167,7 +160,7 @@ impl Tui for App { self.view_list(app, &self.theme.clone())?; // Add global key listener and subscribe to key events - let global = tui::ui::global_listener().to_boxed(); + let global = tui::realm::ui::global_listener().to_boxed(); app.mount( Cid::GlobalListener, global, diff --git a/bin/commands/patch/select/event.rs b/bin/commands/patch/realm/select/event.rs similarity index 95% rename from bin/commands/patch/select/event.rs rename to bin/commands/patch/realm/select/event.rs index 5d73a9a3..feb2e059 100644 --- a/bin/commands/patch/select/event.rs +++ b/bin/commands/patch/realm/select/event.rs @@ -4,11 +4,11 @@ use tuirealm::{MockComponent, NoUserEvent}; use radicle_tui as tui; -use tui::ui::state::ItemState; -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::realm::ui::state::ItemState; +use tui::realm::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer}; +use tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use tui::realm::ui::widget::list::PropertyList; +use tui::realm::ui::widget::Widget; use tui::{Id, SelectionExit}; use super::ui::{IdSelect, OperationSelect}; diff --git a/bin/commands/issue/select/page.rs b/bin/commands/patch/realm/select/page.rs similarity index 92% rename from bin/commands/issue/select/page.rs rename to bin/commands/patch/realm/select/page.rs index 7cca1332..2624f487 100644 --- a/bin/commands/issue/select/page.rs +++ b/bin/commands/patch/realm/select/page.rs @@ -2,18 +2,18 @@ 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::issue::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 tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ui::{layout, subscription}; +use tui::realm::ViewPage; use super::super::common; use super::{ui, Application, Cid, ListCid, Message, Mode}; @@ -88,7 +88,7 @@ impl ViewPage for ListView { theme: &Theme, ) -> Result<()> { let navigation = ui::list_navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); app.remount(Cid::List(ListCid::Header), header, vec![])?; diff --git a/bin/commands/patch/select/ui.rs b/bin/commands/patch/realm/select/ui.rs similarity index 76% rename from bin/commands/patch/select/ui.rs rename to bin/commands/patch/realm/select/ui.rs index a2903dcc..0259995e 100644 --- a/bin/commands/patch/select/ui.rs +++ b/bin/commands/patch/realm/select/ui.rs @@ -4,15 +4,15 @@ use radicle::cob::patch::{Patch, PatchId}; use radicle_tui as tui; -use tui::cob::patch::Filter; -use tui::context::Context; -use tui::ui::cob::PatchItem; -use tui::ui::theme::{style, Theme}; -use tui::ui::widget::context::Shortcuts; -use tui::ui::widget::{Widget, WidgetComponent}; +use tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::cob::PatchItem; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::context::Shortcuts; +use tui::realm::ui::widget::{Widget, WidgetComponent}; -use tui::ui::widget::container::Tabs; -use tui::ui::widget::label::{self}; +use tui::realm::ui::widget::container::Tabs; +use tui::realm::ui::widget::label::{self}; use tuirealm::command::{Cmd, CmdResult}; use tuirealm::tui::layout::Rect; use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State}; @@ -37,11 +37,11 @@ impl IdSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::PatchBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "select"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "select"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] @@ -87,15 +87,15 @@ impl OperationSelect { pub fn shortcuts(&self) -> HashMap> { [( ListCid::PatchBrowser, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( &self.theme, vec![ - tui::ui::shortcut(&self.theme, "enter", "show"), - tui::ui::shortcut(&self.theme, "c", "checkout"), - tui::ui::shortcut(&self.theme, "m", "comment"), - tui::ui::shortcut(&self.theme, "e", "edit"), - tui::ui::shortcut(&self.theme, "d", "delete"), - tui::ui::shortcut(&self.theme, "q", "quit"), + tui::realm::ui::shortcut(&self.theme, "enter", "show"), + tui::realm::ui::shortcut(&self.theme, "c", "checkout"), + tui::realm::ui::shortcut(&self.theme, "m", "comment"), + tui::realm::ui::shortcut(&self.theme, "e", "edit"), + tui::realm::ui::shortcut(&self.theme, "d", "delete"), + tui::realm::ui::shortcut(&self.theme, "q", "quit"), ], ), )] @@ -125,7 +125,7 @@ impl WidgetComponent for OperationSelect { } pub fn list_navigation(theme: &Theme) -> Widget { - tui::ui::tabs( + tui::realm::ui::tabs( theme, vec![label::reversable("Patches").style(style::cyan())], ) diff --git a/bin/commands/patch/suite.rs b/bin/commands/patch/realm/suite.rs similarity index 93% rename from bin/commands/patch/suite.rs rename to bin/commands/patch/realm/suite.rs index 7cd80d10..5402d37f 100644 --- a/bin/commands/patch/suite.rs +++ b/bin/commands/patch/realm/suite.rs @@ -17,12 +17,13 @@ use tuirealm::{Application, Frame, NoUserEvent, Sub, SubClause}; use radicle_tui as tui; -use tui::cob; -use tui::cob::patch::Filter; -use tui::context::Context; -use tui::ui::subscription; -use tui::ui::theme::Theme; -use tui::{Exit, PageStack, Tui}; +use tui::common::cob; +use tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::subscription; +use tui::realm::ui::theme::Theme; +use tui::realm::{PageStack, Tui}; +use tui::Exit; use page::{ListView, PatchView}; @@ -194,7 +195,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::info(theme, message); + let popup = tui::realm::ui::info(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -207,7 +208,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::warning(theme, message); + let popup = tui::realm::ui::warning(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -220,7 +221,7 @@ impl App { theme: &Theme, message: &str, ) -> Result<()> { - let popup = tui::ui::error(theme, message); + let popup = tui::realm::ui::error(theme, message); app.remount(Cid::Popup, popup.to_boxed(), vec![])?; app.active(&Cid::Popup)?; @@ -240,7 +241,7 @@ impl Tui for App { self.view_list(app, &self.theme.clone())?; // Add global key listener and subscribe to key events - let global = tui::ui::global_listener().to_boxed(); + let global = tui::realm::ui::global_listener().to_boxed(); app.mount( Cid::GlobalListener, global, diff --git a/bin/commands/patch/suite/event.rs b/bin/commands/patch/realm/suite/event.rs similarity index 93% rename from bin/commands/patch/suite/event.rs rename to bin/commands/patch/realm/suite/event.rs index 0d5ccf86..0603068c 100644 --- a/bin/commands/patch/suite/event.rs +++ b/bin/commands/patch/realm/suite/event.rs @@ -1,13 +1,14 @@ -use radicle_tui::ui::state::ItemState; 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 radicle_tui::realm::ui::state::ItemState; +use radicle_tui::realm::ui::widget::container::{ + AppHeader, GlobalListener, LabeledContainer, Popup, +}; +use radicle_tui::realm::ui::widget::context::{ContextBar, Shortcuts}; +use radicle_tui::realm::ui::widget::list::PropertyList; +use radicle_tui::realm::ui::widget::Widget; use super::super::common; use super::{ui, Message, PatchMessage, PopupMessage}; diff --git a/bin/commands/patch/suite/page.rs b/bin/commands/patch/realm/suite/page.rs similarity index 87% rename from bin/commands/patch/suite/page.rs rename to bin/commands/patch/realm/suite/page.rs index 74b10bd0..83d8f153 100644 --- a/bin/commands/patch/suite/page.rs +++ b/bin/commands/patch/realm/suite/page.rs @@ -4,18 +4,18 @@ use anyhow::Result; use radicle::cob::patch::{Patch, PatchId}; -use tui::ui::state::ItemState; use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent, Sub, SubClause}; use radicle_tui as tui; -use tui::cob::patch::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 tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::state::ItemState; +use tui::realm::ui::theme::Theme; +use tui::realm::ui::widget::context::{Progress, Shortcuts}; +use tui::realm::ui::widget::Widget; +use tui::realm::ui::{layout, subscription}; +use tui::realm::ViewPage; use super::{ui, Application, Cid, ListCid, Message, PatchCid}; @@ -41,13 +41,13 @@ impl ListView { fn build_shortcuts(theme: &Theme) -> HashMap> { [( ListCid::PatchBrowser, - tui::ui::shortcuts( + tui::realm::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"), + tui::realm::ui::shortcut(theme, "tab", "section"), + tui::realm::ui::shortcut(theme, "↑/↓", "navigate"), + tui::realm::ui::shortcut(theme, "enter", "show"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), )] @@ -104,7 +104,7 @@ impl ViewPage for ListView { theme: &Theme, ) -> Result<()> { let navigation = ui::list_navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); let patch_browser = ui::patches(theme, context, self.filter.clone(), None).to_boxed(); app.remount(Cid::List(ListCid::Header), header, vec![])?; @@ -201,23 +201,23 @@ impl PatchView { [ ( PatchCid::Activity, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( theme, vec![ - tui::ui::shortcut(theme, "esc", "back"), - tui::ui::shortcut(theme, "tab", "section"), - tui::ui::shortcut(theme, "q", "quit"), + tui::realm::ui::shortcut(theme, "esc", "back"), + tui::realm::ui::shortcut(theme, "tab", "section"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), ), ( PatchCid::Files, - tui::ui::shortcuts( + tui::realm::ui::shortcuts( theme, vec![ - tui::ui::shortcut(theme, "esc", "back"), - tui::ui::shortcut(theme, "tab", "section"), - tui::ui::shortcut(theme, "q", "quit"), + tui::realm::ui::shortcut(theme, "esc", "back"), + tui::realm::ui::shortcut(theme, "tab", "section"), + tui::realm::ui::shortcut(theme, "q", "quit"), ], ), ), @@ -251,7 +251,7 @@ impl ViewPage for PatchView { theme: &Theme, ) -> Result<()> { let navigation = ui::navigation(theme); - let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed(); + let header = tui::realm::ui::app_header(context, theme, Some(navigation)).to_boxed(); let activity = ui::activity(theme).to_boxed(); let files = ui::files(theme).to_boxed(); let context = ui::context(context, theme, self.patch.clone()).to_boxed(); diff --git a/bin/commands/patch/suite/ui.rs b/bin/commands/patch/realm/suite/ui.rs similarity index 87% rename from bin/commands/patch/suite/ui.rs rename to bin/commands/patch/realm/suite/ui.rs index 1fc79744..a46e05bf 100644 --- a/bin/commands/patch/suite/ui.rs +++ b/bin/commands/patch/realm/suite/ui.rs @@ -7,16 +7,16 @@ use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State}; use radicle_tui as tui; -use tui::cob::patch::Filter; -use tui::context::Context; -use tui::ui::cob; -use tui::ui::layout; -use tui::ui::theme::{style, Theme}; -use tui::ui::widget::{Widget, WidgetComponent}; +use tui::common::cob::patch::Filter; +use tui::common::context::Context; +use tui::realm::ui::cob; +use tui::realm::ui::layout; +use tui::realm::ui::theme::{style, Theme}; +use tui::realm::ui::widget::{Widget, WidgetComponent}; -use tui::ui::widget::container::Tabs; -use tui::ui::widget::context::{ContextBar, Progress}; -use tui::ui::widget::label::{self, Label}; +use tui::realm::ui::widget::container::Tabs; +use tui::realm::ui::widget::context::{ContextBar, Progress}; +use tui::realm::ui::widget::label::{self, Label}; use super::super::common; @@ -83,14 +83,14 @@ impl WidgetComponent for Files { } pub fn list_navigation(theme: &Theme) -> Widget { - tui::ui::tabs( + tui::realm::ui::tabs( theme, vec![label::reversable("Patches").style(style::magenta())], ) } pub fn navigation(theme: &Theme) -> Widget { - tui::ui::tabs( + tui::realm::ui::tabs( theme, vec![ label::reversable("Activity").style(style::magenta()), @@ -136,7 +136,7 @@ pub fn context(context: &Context, theme: &Theme, patch: (PatchId, Patch)) -> Wid let author = cob::format_author(author, &alias, is_you); let comments = rev.discussion().len(); - tui::ui::widget::context::bar(theme, "Patch", &id, title, &author, &comments.to_string()) + tui::realm::ui::widget::context::bar(theme, "Patch", &id, title, &author, &comments.to_string()) } pub fn browse_context(context: &Context, theme: &Theme, progress: Progress) -> Widget { @@ -160,7 +160,7 @@ pub fn browse_context(context: &Context, theme: &Theme, progress: Progress) -> W } } - tui::ui::widget::context::bar( + tui::realm::ui::widget::context::bar( theme, "Browse", "", diff --git a/src/common.rs b/src/common.rs new file mode 100644 index 00000000..b1cfeb30 --- /dev/null +++ b/src/common.rs @@ -0,0 +1,3 @@ +pub mod cob; +pub mod context; +pub mod log; diff --git a/src/cob.rs b/src/common/cob.rs similarity index 100% rename from src/cob.rs rename to src/common/cob.rs diff --git a/src/cob/format.rs b/src/common/cob/format.rs similarity index 100% rename from src/cob/format.rs rename to src/common/cob/format.rs diff --git a/src/cob/inbox.rs b/src/common/cob/inbox.rs similarity index 100% rename from src/cob/inbox.rs rename to src/common/cob/inbox.rs diff --git a/src/cob/issue.rs b/src/common/cob/issue.rs similarity index 100% rename from src/cob/issue.rs rename to src/common/cob/issue.rs diff --git a/src/cob/patch.rs b/src/common/cob/patch.rs similarity index 100% rename from src/cob/patch.rs rename to src/common/cob/patch.rs diff --git a/src/context.rs b/src/common/context.rs similarity index 97% rename from src/context.rs rename to src/common/context.rs index aa3d219d..d3f61346 100644 --- a/src/context.rs +++ b/src/common/context.rs @@ -16,7 +16,7 @@ use term::{passphrase, spinner, Passphrase}; use inquire::validator; -use crate::cob::inbox; +use super::cob::inbox; /// Git revision parameter. Supports extended SHA-1 syntax. #[derive(Debug, Clone, PartialEq, Eq)] @@ -70,13 +70,13 @@ impl Context { } pub fn with_issues(mut self) -> Self { - use crate::cob::issue; + use super::cob::issue; self.issues = Some(issue::all(&self.repository).unwrap_or_default()); self } pub fn with_patches(mut self) -> Self { - use crate::cob::patch; + use super::cob::patch; self.patches = Some(patch::all(&self.repository).unwrap_or_default()); self } @@ -120,12 +120,12 @@ impl Context { } pub fn reload_patches(&mut self) { - use crate::cob::patch; + use super::cob::patch; self.patches = Some(patch::all(&self.repository).unwrap_or_default()); } pub fn reload_issues(&mut self) { - use crate::cob::issue; + use super::cob::issue; self.issues = Some(issue::all(&self.repository).unwrap_or_default()); } } diff --git a/src/log.rs b/src/common/log.rs similarity index 100% rename from src/log.rs rename to src/common/log.rs diff --git a/src/lib.rs b/src/lib.rs index 718106e7..071fb34b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,54 +1,20 @@ use std::fmt::Display; -use std::hash::Hash; -use std::time::Duration; use anyhow::Result; use serde::ser::{Serialize, SerializeStruct, Serializer}; -use tuirealm::terminal::TerminalBridge; -use tuirealm::tui::layout::Rect; -use tuirealm::Frame; -use tuirealm::{Application, EventListenerCfg, NoUserEvent}; - use radicle::cob::ObjectId; use radicle::node::notifications::NotificationId; -pub mod cob; -pub mod context; -pub mod log; -pub mod ui; +pub mod common; +#[cfg(feature = "realm")] +pub mod realm; + +#[cfg(feature = "flux")] pub mod flux; -use context::Context; -use ui::theme::Theme; - -/// Trait that must be implemented by client applications in order to be run -/// as tui-application using tui-realm. Implementors act as models to the -/// tui-realm application that can be polled for new messages, updated -/// accordingly and rendered with new state. -/// -/// Please see `examples/` for further information on how to use it. -pub trait Tui -where - Id: Eq + PartialEq + Clone + Hash, - Message: Eq, -{ - /// Should initialize an application by mounting and activating components. - fn init(&mut self, app: &mut Application) -> Result<()>; - - /// Should update the current state by handling a message from the view. Returns true - /// if view should be updated (e.g. a message was received and the current state changed). - fn update(&mut self, app: &mut Application) -> Result; - - /// Should draw the application to a frame. - fn view(&mut self, app: &mut Application, frame: &mut Frame); - - /// Should return `Some` if the application is requested to quit. - fn exit(&self) -> Option>; -} - /// An optional return value. pub struct Exit { pub value: Option, @@ -118,174 +84,3 @@ impl Serialize for SelectionExit { state.end() } } - -/// A tui-window using the cross-platform Terminal helper provided -/// by tui-realm. -pub struct Window { - /// Helper around `Terminal` to quickly setup and perform on terminal. - pub terminal: TerminalBridge, -} - -impl Default for Window { - fn default() -> Self { - Self::new() - } -} - -/// Provides a way to create and run a new tui-application. -impl Window { - /// Creates a tui-window using the default cross-platform Terminal - /// helper and panics if its creation fails. - pub fn new() -> Self { - let terminal = TerminalBridge::new().expect("Cannot create terminal bridge"); - - Self { terminal } - } - - /// Runs this tui-window with the tui-application given and performs the - /// following steps: - /// 1. Enter alternative terminal screen - /// 2. Run main loop until application should quit and with each iteration - /// - poll new events (tick or user event) - /// - update application state - /// - redraw view - /// 3. Leave alternative terminal screen - pub fn run( - &mut self, - tui: &mut T, - interval: u64, - ) -> Result> - where - T: Tui, - Id: Eq + PartialEq + Clone + Hash, - Message: Eq, - { - let mut update = true; - let mut resize = false; - let mut size = Rect::default(); - let mut app = Application::init( - EventListenerCfg::default().default_input_listener(Duration::from_millis(interval)), - ); - tui.init(&mut app)?; - - while tui.exit().is_none() { - if update || resize { - self.terminal - .raw_mut() - .draw(|frame| tui.view(&mut app, frame))?; - } - update = tui.update(&mut app)?; - - resize = size != self.terminal.raw_mut().size()?; - size = self.terminal.raw_mut().size()?; - } - - Ok(tui.exit().unwrap().value) - } -} - -/// `tuirealm`'s event and prop system is designed to work with flat component hierarchies. -/// Building deep nested component hierarchies would need a lot more additional effort to -/// properly pass events and props down these hierarchies. This makes it hard to implement -/// full app views (home, patch details etc) as components. -/// -/// View pages take into account these flat component hierarchies, and provide -/// switchable sets of components. -pub trait ViewPage -where - Id: Eq + PartialEq + Clone + Hash, - Message: Eq, -{ - /// Will be called whenever a view page is pushed onto the page stack. Should create and mount all widgets. - fn mount( - &mut self, - app: &mut Application, - context: &Context, - theme: &Theme, - ) -> Result<()>; - - /// Will be called whenever a view page is popped from the page stack. Should unmount all widgets. - fn unmount(&self, app: &mut Application) -> Result<()>; - - /// Will be called whenever a view page is on top of the stack and can be used to update its internal - /// state depending on the message passed. - fn update( - &mut self, - app: &mut Application, - context: &Context, - theme: &Theme, - message: Message, - ) -> Result>; - - /// Will be called whenever a view page is on top of the page stack and needs to be rendered. - fn view(&mut self, app: &mut Application, frame: &mut Frame); - - /// Will be called whenever this view page is pushed to the stack, or it is on top of the stack again - /// after another view page was popped from the stack. - fn subscribe(&self, app: &mut Application) -> Result<()>; - - /// Will be called whenever this view page is on top of the stack and another view page is pushed - /// to the stack, or if this is popped from the stack. - fn unsubscribe(&self, app: &mut Application) -> Result<()>; -} - -/// View pages need to preserve their state (e.g. selected navigation tab, contents -/// and the selected row of a table). Therefor they should not be (re-)created -/// each time they are displayed. -/// Instead the application can push a new page onto the page stack if it needs to -/// be displayed. Its components are then created using the internal state. If a -/// new page needs to be displayed, it will also be pushed onto the stack. Leaving -/// that page again will pop it from the stack. The application can then return to -/// the previously displayed page in the state it was left. -#[derive(Default)] -pub struct PageStack -where - Id: Eq + PartialEq + Clone + Hash, - Message: Eq, -{ - pages: Vec>>, -} - -impl PageStack -where - Id: Eq + PartialEq + Clone + Hash, - Message: Eq, -{ - pub fn push( - &mut self, - mut page: Box>, - app: &mut Application, - context: &Context, - theme: &Theme, - ) -> Result<()> { - if let Some(page) = self.pages.last() { - page.unsubscribe(app)?; - } - - page.mount(app, context, theme)?; - page.subscribe(app)?; - - self.pages.push(page); - - Ok(()) - } - - pub fn pop(&mut self, app: &mut Application) -> Result<()> { - self.peek_mut()?.unsubscribe(app)?; - self.peek_mut()?.unmount(app)?; - self.pages.pop(); - - self.peek_mut()?.subscribe(app)?; - - Ok(()) - } - - pub fn peek_mut(&mut self) -> Result<&mut Box>> { - match self.pages.last_mut() { - Some(page) => Ok(page), - None => Err(anyhow::anyhow!( - "Could not peek active page. Page stack is empty." - )), - } - } -} diff --git a/src/realm.rs b/src/realm.rs new file mode 100644 index 00000000..46213c0c --- /dev/null +++ b/src/realm.rs @@ -0,0 +1,211 @@ +pub mod ui; + +use std::hash::Hash; +use std::time::Duration; + +use anyhow::Result; + +use tuirealm::terminal::TerminalBridge; +use tuirealm::tui::layout::Rect; +use tuirealm::Frame; +use tuirealm::{Application, EventListenerCfg, NoUserEvent}; + +use crate::common::context::Context; +use crate::Exit; +use ui::theme::Theme; + +/// Trait that must be implemented by client applications in order to be run +/// as tui-application using tui-realm. Implementors act as models to the +/// tui-realm application that can be polled for new messages, updated +/// accordingly and rendered with new state. +/// +/// Please see `examples/` for further information on how to use it. +pub trait Tui +where + Id: Eq + PartialEq + Clone + Hash, + Message: Eq, +{ + /// Should initialize an application by mounting and activating components. + fn init(&mut self, app: &mut Application) -> Result<()>; + + /// Should update the current state by handling a message from the view. Returns true + /// if view should be updated (e.g. a message was received and the current state changed). + fn update(&mut self, app: &mut Application) -> Result; + + /// Should draw the application to a frame. + fn view(&mut self, app: &mut Application, frame: &mut Frame); + + /// Should return `Some` if the application is requested to quit. + fn exit(&self) -> Option>; +} + +/// A tui-window using the cross-platform Terminal helper provided +/// by tui-realm. +pub struct Window { + /// Helper around `Terminal` to quickly setup and perform on terminal. + pub terminal: TerminalBridge, +} + +impl Default for Window { + fn default() -> Self { + Self::new() + } +} + +/// Provides a way to create and run a new tui-application. +impl Window { + /// Creates a tui-window using the default cross-platform Terminal + /// helper and panics if its creation fails. + pub fn new() -> Self { + let terminal = TerminalBridge::new().expect("Cannot create terminal bridge"); + + Self { terminal } + } + + /// Runs this tui-window with the tui-application given and performs the + /// following steps: + /// 1. Enter alternative terminal screen + /// 2. Run main loop until application should quit and with each iteration + /// - poll new events (tick or user event) + /// - update application state + /// - redraw view + /// 3. Leave alternative terminal screen + pub fn run( + &mut self, + tui: &mut T, + interval: u64, + ) -> Result> + where + T: Tui, + Id: Eq + PartialEq + Clone + Hash, + Message: Eq, + { + let mut update = true; + let mut resize = false; + let mut size = Rect::default(); + let mut app = Application::init( + EventListenerCfg::default().default_input_listener(Duration::from_millis(interval)), + ); + tui.init(&mut app)?; + + while tui.exit().is_none() { + if update || resize { + self.terminal + .raw_mut() + .draw(|frame| tui.view(&mut app, frame))?; + } + update = tui.update(&mut app)?; + + resize = size != self.terminal.raw_mut().size()?; + size = self.terminal.raw_mut().size()?; + } + + Ok(tui.exit().unwrap().value) + } +} + +/// `tuirealm`'s event and prop system is designed to work with flat component hierarchies. +/// Building deep nested component hierarchies would need a lot more additional effort to +/// properly pass events and props down these hierarchies. This makes it hard to implement +/// full app views (home, patch details etc) as components. +/// +/// View pages take into account these flat component hierarchies, and provide +/// switchable sets of components. +pub trait ViewPage +where + Id: Eq + PartialEq + Clone + Hash, + Message: Eq, +{ + /// Will be called whenever a view page is pushed onto the page stack. Should create and mount all widgets. + fn mount( + &mut self, + app: &mut Application, + context: &Context, + theme: &Theme, + ) -> Result<()>; + + /// Will be called whenever a view page is popped from the page stack. Should unmount all widgets. + fn unmount(&self, app: &mut Application) -> Result<()>; + + /// Will be called whenever a view page is on top of the stack and can be used to update its internal + /// state depending on the message passed. + fn update( + &mut self, + app: &mut Application, + context: &Context, + theme: &Theme, + message: Message, + ) -> Result>; + + /// Will be called whenever a view page is on top of the page stack and needs to be rendered. + fn view(&mut self, app: &mut Application, frame: &mut Frame); + + /// Will be called whenever this view page is pushed to the stack, or it is on top of the stack again + /// after another view page was popped from the stack. + fn subscribe(&self, app: &mut Application) -> Result<()>; + + /// Will be called whenever this view page is on top of the stack and another view page is pushed + /// to the stack, or if this is popped from the stack. + fn unsubscribe(&self, app: &mut Application) -> Result<()>; +} + +/// View pages need to preserve their state (e.g. selected navigation tab, contents +/// and the selected row of a table). Therefor they should not be (re-)created +/// each time they are displayed. +/// Instead the application can push a new page onto the page stack if it needs to +/// be displayed. Its components are then created using the internal state. If a +/// new page needs to be displayed, it will also be pushed onto the stack. Leaving +/// that page again will pop it from the stack. The application can then return to +/// the previously displayed page in the state it was left. +#[derive(Default)] +pub struct PageStack +where + Id: Eq + PartialEq + Clone + Hash, + Message: Eq, +{ + pages: Vec>>, +} + +impl PageStack +where + Id: Eq + PartialEq + Clone + Hash, + Message: Eq, +{ + pub fn push( + &mut self, + mut page: Box>, + app: &mut Application, + context: &Context, + theme: &Theme, + ) -> Result<()> { + if let Some(page) = self.pages.last() { + page.unsubscribe(app)?; + } + + page.mount(app, context, theme)?; + page.subscribe(app)?; + + self.pages.push(page); + + Ok(()) + } + + pub fn pop(&mut self, app: &mut Application) -> Result<()> { + self.peek_mut()?.unsubscribe(app)?; + self.peek_mut()?.unmount(app)?; + self.pages.pop(); + + self.peek_mut()?.subscribe(app)?; + + Ok(()) + } + + pub fn peek_mut(&mut self) -> Result<&mut Box>> { + match self.pages.last_mut() { + Some(page) => Ok(page), + None => Err(anyhow::anyhow!( + "Could not peek active page. Page stack is empty." + )), + } + } +} diff --git a/src/ui.rs b/src/realm/ui.rs similarity index 99% rename from src/ui.rs rename to src/realm/ui.rs index b987c9fd..a9a75602 100644 --- a/src/ui.rs +++ b/src/realm/ui.rs @@ -20,7 +20,7 @@ use widget::Widget; use theme::{style, Theme}; -use super::context::Context; +use crate::common::context::Context; pub fn global_listener() -> Widget { Widget::new(GlobalListener::default()) diff --git a/src/ui/cob.rs b/src/realm/ui/cob.rs similarity index 99% rename from src/ui/cob.rs rename to src/realm/ui/cob.rs index 03501644..a01b482e 100644 --- a/src/ui/cob.rs +++ b/src/realm/ui/cob.rs @@ -20,8 +20,8 @@ use radicle::storage::git::Repository; use radicle::storage::{Oid, ReadRepository, RefUpdate}; use radicle::{cob, Profile}; -use crate::ui::theme::Theme; -use crate::ui::widget::list::{ListItem, TableItem}; +use super::super::ui::theme::Theme; +use super::super::ui::widget::list::{ListItem, TableItem}; use super::widget::label; diff --git a/src/ui/cob/format.rs b/src/realm/ui/cob/format.rs similarity index 100% rename from src/ui/cob/format.rs rename to src/realm/ui/cob/format.rs diff --git a/src/ui/ext.rs b/src/realm/ui/ext.rs similarity index 100% rename from src/ui/ext.rs rename to src/realm/ui/ext.rs diff --git a/src/ui/layout.rs b/src/realm/ui/layout.rs similarity index 100% rename from src/ui/layout.rs rename to src/realm/ui/layout.rs diff --git a/src/ui/state.rs b/src/realm/ui/state.rs similarity index 100% rename from src/ui/state.rs rename to src/realm/ui/state.rs diff --git a/src/ui/subscription.rs b/src/realm/ui/subscription.rs similarity index 100% rename from src/ui/subscription.rs rename to src/realm/ui/subscription.rs diff --git a/src/ui/theme.rs b/src/realm/ui/theme.rs similarity index 100% rename from src/ui/theme.rs rename to src/realm/ui/theme.rs diff --git a/src/ui/widget.rs b/src/realm/ui/widget.rs similarity index 100% rename from src/ui/widget.rs rename to src/realm/ui/widget.rs diff --git a/src/ui/widget/common.rs b/src/realm/ui/widget/common.rs similarity index 100% rename from src/ui/widget/common.rs rename to src/realm/ui/widget/common.rs diff --git a/src/ui/widget/container.rs b/src/realm/ui/widget/container.rs similarity index 98% rename from src/ui/widget/container.rs rename to src/realm/ui/widget/container.rs index c0d8190e..40a53155 100644 --- a/src/ui/widget/container.rs +++ b/src/realm/ui/widget/container.rs @@ -4,11 +4,11 @@ use tuirealm::tui::layout::{Constraint, Direction, Layout, Margin, Rect}; use tuirealm::tui::widgets::{Block, Cell, Clear, Row}; use tuirealm::{Frame, MockComponent, State, StateValue}; -use crate::ui::ext::HeaderBlock; -use crate::ui::layout; -use crate::ui::state::TabState; -use crate::ui::theme::{style, Theme}; -use crate::ui::widget::{utils, Widget, WidgetComponent}; +use crate::realm::ui::ext::HeaderBlock; +use crate::realm::ui::layout; +use crate::realm::ui::state::TabState; +use crate::realm::ui::theme::{style, Theme}; +use crate::realm::ui::widget::{utils, Widget, WidgetComponent}; use super::label::Label; use super::list::ColumnWidth; diff --git a/src/ui/widget/context.rs b/src/realm/ui/widget/context.rs similarity index 98% rename from src/ui/widget/context.rs rename to src/realm/ui/widget/context.rs index e1c1a700..74d94d53 100644 --- a/src/ui/widget/context.rs +++ b/src/realm/ui/widget/context.rs @@ -5,9 +5,9 @@ use tuirealm::{Frame, MockComponent, State}; use super::label::{self, Label, LabelGroup}; -use crate::ui::layout; -use crate::ui::theme::{style, Theme}; -use crate::ui::widget::{Widget, WidgetComponent}; +use crate::realm::ui::layout; +use crate::realm::ui::theme::{style, Theme}; +use crate::realm::ui::widget::{Widget, WidgetComponent}; pub enum Progress { Percentage(usize), diff --git a/src/ui/widget/form.rs b/src/realm/ui/widget/form.rs similarity index 96% rename from src/ui/widget/form.rs rename to src/realm/ui/widget/form.rs index 13d757da..53d85b9c 100644 --- a/src/ui/widget/form.rs +++ b/src/realm/ui/widget/form.rs @@ -4,9 +4,9 @@ use tuirealm::command::{Cmd, CmdResult}; use tuirealm::tui::layout::{Constraint, Direction, Margin, Rect}; use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State, StateValue}; -use crate::ui::state::FormState; -use crate::ui::theme::{style, Theme}; -use crate::ui::widget::{Widget, WidgetComponent}; +use crate::realm::ui::state::FormState; +use crate::realm::ui::theme::{style, Theme}; +use crate::realm::ui::widget::{Widget, WidgetComponent}; use super::container::Container; use super::label::{self, Label}; @@ -26,7 +26,7 @@ impl TextField { // .cursor_line_style(Style::reset()) // .style(style::reset()); let input = tui_realm_stdlib::Textarea::default(); - let container = crate::ui::container(&theme, Box::new(input)); + let container = crate::realm::ui::container(&theme, Box::new(input)); Self { input: container, @@ -104,7 +104,7 @@ impl TextArea { // .cursor_line_style(Style::reset()) // .style(style::reset()); let input = tui_realm_stdlib::Textarea::default(); - let container = crate::ui::container(&theme, Box::new(input)); + let container = crate::realm::ui::container(&theme, Box::new(input)); Self { input: container, diff --git a/src/ui/widget/label.rs b/src/realm/ui/widget/label.rs similarity index 98% rename from src/ui/widget/label.rs rename to src/realm/ui/widget/label.rs index 06141aeb..1c90599f 100644 --- a/src/ui/widget/label.rs +++ b/src/realm/ui/widget/label.rs @@ -4,9 +4,9 @@ use tuirealm::tui::layout::{Constraint, Direction, Layout, Rect}; use tuirealm::tui::text::{Line, Span, Text}; use tuirealm::{Frame, MockComponent, State, StateValue}; -use crate::ui::layout; -use crate::ui::theme::style; -use crate::ui::widget::{Widget, WidgetComponent}; +use crate::realm::ui::layout; +use crate::realm::ui::theme::style; +use crate::realm::ui::widget::{Widget, WidgetComponent}; pub fn blank() -> Widget