issue-select: Add basic command implementation

This commit is contained in:
Erik Kundt
2024-01-30 10:23:25 +01:00
parent 8909cb668f
commit 26fae956fa
11 changed files with 1169 additions and 45 deletions
+88 -16
View File
@@ -1,3 +1,7 @@
#[path = "issue/common.rs"]
mod common;
#[path = "issue/select.rs"]
mod select;
#[path = "issue/suite.rs"]
mod suite;
@@ -5,10 +9,15 @@ use std::ffi::OsString;
use anyhow::anyhow;
use radicle_tui as tui;
use tui::cob::issue::{self};
use tui::{context, log, Window};
use crate::terminal;
use crate::terminal::args::{Args, Error, Help};
#[allow(dead_code)]
pub const FPS: u64 = 60;
pub const HELP: Help = Help {
name: "issue",
description: "Terminal interfaces for issues",
@@ -16,55 +25,118 @@ pub const HELP: Help = Help {
usage: r#"
Usage
rad-tui issue
rad-tui patch select [<option>...]
General options
Select options
--mode <MODE> Set selection mode; see MODE below (default: operation)
The MODE argument can be 'operation' or 'id'. 'operation' selects an issue id and
an operation, whereas 'id' selects an issue id only.
Other options
--help Print help
"#,
};
#[allow(dead_code)]
pub struct Options {
op: Operation,
json: bool,
}
pub enum Operation {
Suite,
Select { opts: SelectOptions },
}
#[derive(Default, PartialEq, Eq)]
#[derive(PartialEq, Eq)]
pub enum OperationName {
#[default]
Suite,
Select,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct SelectOptions {
mode: select::Mode,
filter: issue::Filter,
}
impl Args for Options {
#[allow(clippy::unnecessary_literal_unwrap)]
fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
use lexopt::prelude::*;
let mut parser = lexopt::Parser::from_args(args);
let op: Option<OperationName> = None;
let mut op: Option<OperationName> = None;
let mut json = false;
let mut select_opts = SelectOptions::default();
#[allow(clippy::never_loop)]
while let Some(arg) = parser.next()? {
match arg {
Long("help") | Short('h') => {
return Err(Error::Help.into());
}
Long("json") | Short('j') => {
json = true;
}
// select options.
Long("mode") | Short('m') if op == Some(OperationName::Select) => {
let val = parser.value()?;
let val = val.to_str().unwrap_or_default();
select_opts.mode = match val {
"operation" => select::Mode::Operation,
"id" => select::Mode::Id,
unknown => anyhow::bail!("unknown mode '{}'", unknown),
};
}
Value(val) if op.is_none() => match val.to_string_lossy().as_ref() {
"select" => op = Some(OperationName::Select),
unknown => anyhow::bail!("unknown operation '{}'", unknown),
},
_ => return Err(anyhow!(arg.unexpected())),
}
}
let op = match op.unwrap_or_default() {
OperationName::Suite => Operation::Suite,
let op = match op.ok_or_else(|| anyhow!("an operation must be provided"))? {
OperationName::Select => Operation::Select { opts: select_opts },
};
Ok((Options { op }, vec![]))
Ok((Options { op, json }, vec![]))
}
}
#[allow(dead_code)]
pub fn run(_options: Options, _ctx: impl terminal::Context) -> anyhow::Result<()> {
pub 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 { ref opts } => {
let profile = terminal::profile()?;
let context = context::Context::new(profile, id)?.with_issues();
log::enable(context.profile(), "issue", "select")?;
let mut app = select::App::new(context, opts.mode.clone(), opts.filter.clone());
let output = Window::default().run(&mut app, 1000 / FPS)?;
let output = if options.json {
output
.map(|o| serde_json::to_string(&o).unwrap_or_default())
.unwrap_or_default()
} else {
match options.op {
Operation::Select { ref opts } => match &opts.mode {
select::Mode::Id => output.map(|o| format!("{}", o)).unwrap_or_default(),
select::Mode::Operation => output
.map(|o| format!("rad patch {}", o))
.unwrap_or_default(),
},
}
};
eprint!("{output}");
}
}
Ok(())
}
+2
View File
@@ -0,0 +1,2 @@
#[path = "common/ui.rs"]
pub mod ui;
+163
View File
@@ -0,0 +1,163 @@
use radicle::issue::{Issue, IssueId};
use tuirealm::command::{Cmd, CmdResult};
use tuirealm::tui::layout::Rect;
use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State};
use radicle_tui as tui;
use tui::cob::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};
pub struct IssueBrowser {
items: Vec<IssueItem>,
table: Widget<Table<IssueItem, 7>>,
}
impl IssueBrowser {
pub fn new(
theme: &Theme,
context: &Context,
filter: Filter,
selected: Option<(IssueId, Issue)>,
) -> Self {
let header = [
label::header(" ● "),
label::header("ID"),
label::header("Title"),
label::header("Author"),
label::header("Tags"),
label::header("Assignees"),
label::header("Opened"),
];
let widths = [
ColumnWidth::Fixed(3),
ColumnWidth::Fixed(7),
ColumnWidth::Grow,
ColumnWidth::Fixed(21),
ColumnWidth::Fixed(25),
ColumnWidth::Fixed(21),
ColumnWidth::Fixed(18),
];
let repo = context.repository();
let issues = context
.issues()
.as_ref()
.unwrap()
.iter()
.filter(|(_, issue)| filter.matches(context.profile(), issue));
let mut items = vec![];
for (id, issue) in issues {
if let Ok(item) = IssueItem::try_from((context.profile(), repo, *id, issue.clone())) {
items.push(item);
}
}
items.sort_by(|a, b| b.timestamp().cmp(a.timestamp()));
items.sort_by(|a, b| b.state().cmp(a.state()));
let selected = match selected {
Some((id, issue)) => Some(IssueItem::from((context.profile(), repo, id, issue))),
_ => items.first().cloned(),
};
let table = Widget::new(Table::new(&items, selected, header, widths, theme.clone()));
Self { items, table }
}
pub fn items(&self) -> &Vec<IssueItem> {
&self.items
}
}
impl WidgetComponent for IssueBrowser {
fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
let focus = properties
.get_or(Attribute::Focus, AttrValue::Flag(false))
.unwrap_flag();
self.table.attr(Attribute::Focus, AttrValue::Flag(focus));
self.table.view(frame, area);
}
fn state(&self) -> State {
self.table.state()
}
fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
self.table.perform(cmd)
}
}
pub fn browse_context(
context: &Context,
_theme: &Theme,
filter: Filter,
progress: Progress,
) -> Widget<ContextBar> {
use radicle::issue::State;
let mut open = 0;
let mut closed = 0;
let issues = context
.issues()
.as_ref()
.unwrap()
.iter()
.filter(|(_, issue)| filter.matches(context.profile(), issue));
for (_, issue) in issues {
match issue.state() {
State::Open => open += 1,
State::Closed { reason: _ } => closed += 1,
}
}
let context = label::reversable("/").style(style::magenta_reversed());
let filter = label::default(&filter.to_string()).style(style::magenta_dim());
let open_n = label::default(&format!("{open}")).style(style::green());
let open = label::default(" Open");
let closed_n = label::default(&format!("{closed}")).style(style::cyan());
let closed = label::default(" Closed ");
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,
open_n,
open,
divider,
closed_n,
closed,
]),
label::group(&[progress]),
);
Widget::new(context_bar).height(1)
}
+259
View File
@@ -0,0 +1,259 @@
#[path = "select/event.rs"]
mod event;
#[path = "select/page.rs"]
mod page;
#[path = "select/ui.rs"]
mod ui;
use std::fmt::Display;
use std::hash::Hash;
use anyhow::Result;
use radicle::issue::IssueId;
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::issue::Filter;
use tui::context::Context;
use tui::ui::subscription;
use tui::ui::theme::Theme;
use tui::{Exit, PageStack, Tui};
use page::ListView;
/// Wrapper around radicle's `PatchId` that serializes
/// to a human-readable string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PatchId(radicle::cob::patch::PatchId);
impl From<radicle::cob::patch::PatchId> for PatchId {
fn from(value: radicle::cob::patch::PatchId) -> Self {
PatchId(value)
}
}
impl Display for PatchId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl Serialize for PatchId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}", *self.0))
}
}
/// The application's subject. It tells the application
/// which widgets to render and which output to produce.
///
/// Depends on CLI arguments given by the user.
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub enum Mode {
#[default]
Operation,
Id,
}
/// The selected issue operation returned by the operation
/// selection widget.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum IssueOperation {
Show,
Delete,
Edit,
Comment,
}
impl Display for IssueOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IssueOperation::Show => {
write!(f, "show")
}
IssueOperation::Delete => {
write!(f, "delete")
}
IssueOperation::Edit => {
write!(f, "edit")
}
IssueOperation::Comment => {
write!(f, "comment")
}
}
}
}
/// The application's output that depends on the application's
/// subject.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct Output {
operation: Option<IssueOperation>,
id: IssueId,
}
impl Output {
pub fn new(operation: Option<IssueOperation>, id: IssueId) -> Self {
Self { operation, id }
}
}
impl Display for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.operation {
Some(op) => write!(f, "{} {}", op, self.id),
None => write!(f, "{}", self.id),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum ListCid {
Header,
PatchBrowser,
Context,
Shortcuts,
}
/// All component ids known to this application.
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
pub enum Cid {
List(ListCid),
#[default]
GlobalListener,
}
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub enum Message {
#[default]
Tick,
Quit(Option<Output>),
Batch(Vec<Message>),
}
pub struct App {
context: Context,
pages: PageStack<Cid, Message>,
theme: Theme,
quit: bool,
mode: Mode,
filter: Filter,
output: Option<Output>,
}
/// Creates a new application using a tui-realm-application, mounts all
/// components and sets focus to a default one.
impl App {
pub fn new(context: Context, mode: Mode, filter: Filter) -> Self {
Self {
context,
pages: PageStack::default(),
theme: Theme::default(),
quit: false,
mode,
filter,
output: None,
}
}
fn view_list(
&mut self,
app: &mut Application<Cid, Message, NoUserEvent>,
theme: &Theme,
) -> Result<()> {
let home = Box::new(ListView::new(self.mode.clone(), self.filter.clone()));
self.pages.push(home, app, &self.context, theme)?;
Ok(())
}
fn process(
&mut self,
app: &mut Application<Cid, Message, NoUserEvent>,
message: Message,
) -> Result<Option<Message>> {
let theme = Theme::default();
match message {
Message::Batch(messages) => {
let mut results = vec![];
for message in messages {
if let Some(result) = self.process(app, message)? {
results.push(result);
}
}
match results.len() {
0 => Ok(None),
1 => Ok(Some(results[0].to_owned())),
_ => Ok(Some(Message::Batch(results))),
}
}
Message::Quit(output) => {
self.quit = true;
self.output = output;
Ok(None)
}
_ => self
.pages
.peek_mut()?
.update(app, &self.context, &theme, message),
}
}
}
impl Tui<Cid, Message, Output> for App {
fn init(&mut self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
self.view_list(app, &self.theme.clone())?;
// Add global key listener and subscribe to key events
let global = tui::ui::global_listener().to_boxed();
app.mount(
Cid::GlobalListener,
global,
vec![Sub::new(
subscription::quit_clause(Key::Char('q')),
SubClause::Always,
)],
)?;
Ok(())
}
fn view(&mut self, app: &mut Application<Cid, Message, NoUserEvent>, frame: &mut Frame) {
if let Ok(page) = self.pages.peek_mut() {
page.view(app, frame);
}
}
fn update(&mut self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<bool> {
match app.tick(PollStrategy::Once) {
Ok(messages) if !messages.is_empty() => {
for message in messages {
let mut msg = Some(message);
while msg.is_some() {
msg = self.process(app, msg.unwrap())?;
}
}
Ok(true)
}
_ => Ok(false),
}
}
fn exit(&self) -> Option<Exit<Output>> {
if self.quit {
return Some(Exit {
value: self.output.clone(),
});
}
None
}
}
+169
View File
@@ -0,0 +1,169 @@
use radicle::issue::IssueId;
use tuirealm::command::{Cmd, CmdResult, Direction as MoveDirection};
use tuirealm::event::{Event, Key, KeyEvent};
use tuirealm::{MockComponent, NoUserEvent, State, StateValue};
use radicle_tui as tui;
use tui::ui::widget::container::{AppHeader, GlobalListener, LabeledContainer};
use tui::ui::widget::context::{ContextBar, Shortcuts};
use tui::ui::widget::list::PropertyList;
use tui::ui::widget::Widget;
use super::ui::{IdSelect, OperationSelect};
use super::{IssueOperation, Message, Output};
/// Since the framework does not know the type of messages that are being
/// passed around in the app, the following handlers need to be implemented for
/// each component used.
///
/// TODO: should handle `Event::WindowResize`, which is not emitted by `termion`.
impl tuirealm::Component<Message, NoUserEvent> for Widget<GlobalListener> {
fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
match event {
Event::Keyboard(KeyEvent {
code: Key::Char('q'),
..
}) => Some(Message::Quit(None)),
_ => None,
}
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<IdSelect> {
fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
let mut submit = || -> Option<radicle::cob::patch::PatchId> {
let result = self.perform(Cmd::Submit);
match result {
CmdResult::Submit(State::One(StateValue::Usize(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 = Output::new(None, IssueId::from(id));
Message::Quit(Some(output))
}),
_ => None,
}
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<OperationSelect> {
fn on(&mut self, event: Event<NoUserEvent>) -> Option<Message> {
let mut submit = || -> Option<radicle::cob::patch::PatchId> {
let result = self.perform(Cmd::Submit);
match result {
CmdResult::Submit(State::One(StateValue::Usize(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 = Output::new(Some(IssueOperation::Show), IssueId::from(id));
Message::Quit(Some(output))
}),
Event::Keyboard(KeyEvent {
code: Key::Char('d'),
..
}) => submit().map(|id| {
let output = Output::new(Some(IssueOperation::Delete), IssueId::from(id));
Message::Quit(Some(output))
}),
Event::Keyboard(KeyEvent {
code: Key::Char('e'),
..
}) => submit().map(|id| {
let output = Output::new(Some(IssueOperation::Edit), IssueId::from(id));
Message::Quit(Some(output))
}),
Event::Keyboard(KeyEvent {
code: Key::Char('m'),
..
}) => submit().map(|id| {
let output = Output::new(Some(IssueOperation::Comment), IssueId::from(id));
Message::Quit(Some(output))
}),
_ => None,
}
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<AppHeader> {
fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
None
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<LabeledContainer> {
fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
None
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<PropertyList> {
fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
None
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<ContextBar> {
fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
None
}
}
impl tuirealm::Component<Message, NoUserEvent> for Widget<Shortcuts> {
fn on(&mut self, _event: Event<NoUserEvent>) -> Option<Message> {
None
}
}
+171
View File
@@ -0,0 +1,171 @@
use std::collections::HashMap;
use anyhow::Result;
use tuirealm::{AttrValue, Attribute, Frame, NoUserEvent, State, StateValue, 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 super::super::common;
use super::{ui, Application, Cid, ListCid, Message, Mode};
///
/// Home
///
pub struct ListView {
active_component: ListCid,
subject: Mode,
filter: Filter,
shortcuts: HashMap<ListCid, Widget<Shortcuts>>,
}
impl ListView {
pub fn new(subject: Mode, filter: Filter) -> Self {
Self {
active_component: ListCid::PatchBrowser,
subject,
filter,
shortcuts: HashMap::default(),
}
}
fn update_context(
&self,
app: &mut Application<Cid, Message, NoUserEvent>,
context: &Context,
theme: &Theme,
) -> Result<()> {
let state = app.state(&Cid::List(ListCid::PatchBrowser))?;
let progress = match state {
State::Tup2((StateValue::Usize(step), StateValue::Usize(total))) => {
Progress::Step(step.saturating_add(1), total)
}
_ => Progress::None,
};
let context = common::ui::browse_context(context, theme, self.filter.clone(), progress);
app.remount(Cid::List(ListCid::Context), context.to_boxed(), vec![])?;
Ok(())
}
fn update_shortcuts(
&self,
app: &mut Application<Cid, Message, NoUserEvent>,
cid: ListCid,
) -> Result<()> {
if let Some(shortcuts) = self.shortcuts.get(&cid) {
app.remount(
Cid::List(ListCid::Shortcuts),
shortcuts.clone().to_boxed(),
vec![],
)?;
}
Ok(())
}
}
impl ViewPage<Cid, Message> for ListView {
fn mount(
&mut self,
app: &mut Application<Cid, Message, NoUserEvent>,
context: &Context,
theme: &Theme,
) -> Result<()> {
let navigation = ui::list_navigation(theme);
let header = tui::ui::app_header(context, theme, Some(navigation)).to_boxed();
app.remount(Cid::List(ListCid::Header), header, vec![])?;
match self.subject {
Mode::Id => {
let patch_browser =
ui::id_select(theme, context, self.filter.clone(), None).to_boxed();
self.shortcuts = patch_browser.as_ref().shortcuts();
app.remount(Cid::List(ListCid::PatchBrowser), patch_browser, vec![])?;
}
Mode::Operation => {
let patch_browser =
ui::operation_select(theme, context, self.filter.clone(), None).to_boxed();
self.shortcuts = patch_browser.as_ref().shortcuts();
app.remount(Cid::List(ListCid::PatchBrowser), patch_browser, vec![])?;
}
};
app.active(&Cid::List(self.active_component.clone()))?;
self.update_shortcuts(app, self.active_component.clone())?;
self.update_context(app, context, theme)?;
Ok(())
}
fn unmount(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
app.umount(&Cid::List(ListCid::Header))?;
app.umount(&Cid::List(ListCid::PatchBrowser))?;
app.umount(&Cid::List(ListCid::Context))?;
app.umount(&Cid::List(ListCid::Shortcuts))?;
Ok(())
}
fn update(
&mut self,
app: &mut Application<Cid, Message, NoUserEvent>,
context: &Context,
theme: &Theme,
_message: Message,
) -> Result<Option<Message>> {
self.update_context(app, context, theme)?;
Ok(None)
}
fn view(&mut self, app: &mut Application<Cid, Message, NoUserEvent>, frame: &mut Frame) {
let area = frame.size();
let context_h = app
.query(&Cid::List(ListCid::Context), Attribute::Height)
.unwrap_or_default()
.unwrap_or(AttrValue::Size(0))
.unwrap_size();
let shortcuts_h = 1u16;
let layout = layout::default_page(area, context_h, shortcuts_h);
app.view(
&Cid::List(self.active_component.clone()),
frame,
layout.component,
);
app.view(&Cid::List(ListCid::Context), frame, layout.context);
app.view(&Cid::List(ListCid::Shortcuts), frame, layout.shortcuts);
}
fn subscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
app.subscribe(
&Cid::List(ListCid::Header),
Sub::new(subscription::navigation_clause(), SubClause::Always),
)?;
Ok(())
}
fn unsubscribe(&self, app: &mut Application<Cid, Message, NoUserEvent>) -> Result<()> {
app.unsubscribe(
&Cid::List(ListCid::Header),
subscription::navigation_clause(),
)?;
Ok(())
}
}
+157
View File
@@ -0,0 +1,157 @@
use std::collections::HashMap;
use radicle::issue::{Issue, IssueId};
use tuirealm::command::{Cmd, CmdResult};
use tuirealm::tui::layout::Rect;
use tuirealm::{AttrValue, Attribute, Frame, MockComponent, Props, State};
use radicle_tui as tui;
use tui::cob::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 super::super::common;
use super::ListCid;
pub struct IdSelect {
theme: Theme,
browser: Widget<common::ui::IssueBrowser>,
}
impl IdSelect {
pub fn new(theme: Theme, browser: Widget<common::ui::IssueBrowser>) -> Self {
Self { theme, browser }
}
pub fn items(&self) -> &Vec<IssueItem> {
self.browser.items()
}
pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
[(
ListCid::PatchBrowser,
tui::ui::shortcuts(
&self.theme,
vec![
tui::ui::shortcut(&self.theme, "enter", "select"),
tui::ui::shortcut(&self.theme, "q", "quit"),
],
),
)]
.iter()
.cloned()
.collect()
}
}
impl WidgetComponent for IdSelect {
fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
let focus = properties
.get_or(Attribute::Focus, AttrValue::Flag(false))
.unwrap_flag();
self.browser.attr(Attribute::Focus, AttrValue::Flag(focus));
self.browser.view(frame, area);
}
fn state(&self) -> State {
self.browser.state()
}
fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
self.browser.perform(cmd)
}
}
pub struct OperationSelect {
theme: Theme,
browser: Widget<common::ui::IssueBrowser>,
}
impl OperationSelect {
pub fn new(theme: Theme, browser: Widget<common::ui::IssueBrowser>) -> Self {
Self { theme, browser }
}
pub fn items(&self) -> &Vec<IssueItem> {
self.browser.items()
}
pub fn shortcuts(&self) -> HashMap<ListCid, Widget<Shortcuts>> {
[(
ListCid::PatchBrowser,
tui::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"),
],
),
)]
.iter()
.cloned()
.collect()
}
}
impl WidgetComponent for OperationSelect {
fn view(&mut self, properties: &Props, frame: &mut Frame, area: Rect) {
let focus = properties
.get_or(Attribute::Focus, AttrValue::Flag(false))
.unwrap_flag();
self.browser.attr(Attribute::Focus, AttrValue::Flag(focus));
self.browser.view(frame, area);
}
fn state(&self) -> State {
self.browser.state()
}
fn perform(&mut self, _properties: &Props, cmd: Cmd) -> CmdResult {
self.browser.perform(cmd)
}
}
pub fn list_navigation(theme: &Theme) -> Widget<Tabs> {
tui::ui::tabs(
theme,
vec![label::reversable("Patches").style(style::cyan())],
)
}
pub fn id_select(
theme: &Theme,
context: &Context,
filter: Filter,
selected: Option<(IssueId, Issue)>,
) -> Widget<IdSelect> {
let browser = Widget::new(common::ui::IssueBrowser::new(
theme, context, filter, selected,
));
Widget::new(IdSelect::new(theme.clone(), browser))
}
pub fn operation_select(
theme: &Theme,
context: &Context,
filter: Filter,
selected: Option<(IssueId, Issue)>,
) -> Widget<OperationSelect> {
let browser = Widget::new(common::ui::IssueBrowser::new(
theme, context, filter, selected,
));
Widget::new(OperationSelect::new(theme.clone(), browser))
}
-1
View File
@@ -79,7 +79,6 @@ impl Args for Options {
let mut json = false;
let mut select_opts = SelectOptions::default();
#[allow(clippy::never_loop)]
while let Some(arg) = parser.next()? {
match arg {
Long("help") | Short('h') => {
+7
View File
@@ -97,6 +97,13 @@ fn run(command: Command) -> Result<(), Option<anyhow::Error>> {
fn run_other(exe: &str, args: &[OsString]) -> Result<(), Option<anyhow::Error>> {
match exe {
"issue" => {
terminal::run_command_args::<tui_issue::Options, _>(
tui_issue::HELP,
tui_issue::run,
args.to_vec(),
);
}
"patch" => {
terminal::run_command_args::<tui_patch::Options, _>(
tui_patch::HELP,
+101
View File
@@ -1,8 +1,109 @@
use std::fmt::Display;
use anyhow::Result;
use radicle::cob::issue::{Issue, IssueId, Issues};
use radicle::cob::Label;
use radicle::prelude::{Did, Signer};
use radicle::storage::git::Repository;
use radicle::{issue, Profile};
use super::format;
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub enum State {
#[default]
Open,
Closed,
}
impl Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = match self {
State::Open => "open",
State::Closed => "closed",
};
f.write_str(state)
}
}
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct Filter {
state: Option<State>,
authored: bool,
authors: Vec<Did>,
}
impl Filter {
pub fn with_state(mut self, state: Option<State>) -> Self {
self.state = state;
self
}
pub fn with_authored(mut self, authored: bool) -> Self {
self.authored = authored;
self
}
pub fn with_author(mut self, author: Did) -> Self {
self.authors.push(author);
self
}
pub fn matches(&self, profile: &Profile, issue: &Issue) -> bool {
let matches_state = match self.state {
Some(State::Open) => matches!(issue.state(), issue::State::Open),
Some(State::Closed) => matches!(issue.state(), issue::State::Closed { .. }),
None => true,
};
let matches_authored = self
.authored
.then(|| *issue.author().id() == profile.did())
.unwrap_or(true);
let matches_authors = (!self.authors.is_empty())
.then(|| {
self.authors
.iter()
.any(|other| *issue.author().id() == *other)
})
.unwrap_or(true);
matches_state && matches_authored && matches_authors
}
}
impl ToString for Filter {
fn to_string(&self) -> String {
let mut filter = String::new();
filter.push(' ');
if let Some(state) = &self.state {
filter.push_str(&format!("is:{}", state));
filter.push(' ');
}
if self.authored {
filter.push_str("is:authored");
filter.push(' ');
}
if !self.authors.is_empty() {
filter.push_str("authors:");
filter.push('[');
let mut authors = self.authors.iter().peekable();
while let Some(author) = authors.next() {
filter.push_str(&format::did(author));
if authors.peek().is_some() {
filter.push(',');
}
}
filter.push(']');
}
filter
}
}
pub fn all(repository: &Repository) -> Result<Vec<(IssueId, Issue)>> {
let patches = Issues::open(repository)?
+52 -28
View File
@@ -278,40 +278,64 @@ impl From<(&Profile, &Repository, IssueId, Issue)> for IssueItem {
}
impl TableItem<7> for IssueItem {
fn row(&self, _theme: &Theme, _highlight: bool) -> [Cell; 7] {
fn row(&self, _theme: &Theme, highlight: bool) -> [Cell; 7] {
let (icon, color) = format_issue_state(&self.state);
let state = label::default(&icon)
.style(Style::default().fg(color))
if highlight {
let state = label::reversed(&icon).into();
let id = label::reversed(&format::cob(&self.id)).into();
let title = label::reversed(&self.title.clone()).into();
let author = label::reversed(&format_author(
&self.author.did,
&self.author.alias,
self.author.is_you,
))
.into();
let id = label::id(&format::cob(&self.id)).into();
let title = label::default(&self.title.clone()).into();
let author = match &self.author.alias {
Some(_) => label::alias(&format_author(
&self.author.did,
&self.author.alias,
self.author.is_you,
))
.into(),
None => label::did(&format_author(
&self.author.did,
&self.author.alias,
self.author.is_you,
))
.into(),
};
let labels = label::reversed(&format_labels(&self.labels)).into();
let assignees = self
.assignees
.iter()
.map(|author| (author.did, author.alias.clone(), author.is_you))
.collect::<Vec<_>>();
let assignees = label::reversed(&format_assignees(&assignees)).into();
let opened = label::reversed(&format::timestamp(&self.timestamp)).into();
let labels = label::labels(&format_labels(&self.labels)).into();
let assignees = self
.assignees
.iter()
.map(|author| (author.did, author.alias.clone(), author.is_you))
.collect::<Vec<_>>();
let assignees = label::did(&format_assignees(&assignees)).into();
let opened = label::timestamp(&format::timestamp(&self.timestamp)).into();
[state, id, title, author, labels, assignees, opened]
} else {
let state = label::default(&icon)
.style(Style::default().fg(color))
.into();
let id = label::id(&format::cob(&self.id)).into();
let title = label::default(&self.title.clone()).into();
[state, id, title, author, labels, assignees, opened]
let author = match &self.author.alias {
Some(_) => label::alias(&format_author(
&self.author.did,
&self.author.alias,
self.author.is_you,
))
.into(),
None => label::did(&format_author(
&self.author.did,
&self.author.alias,
self.author.is_you,
))
.into(),
};
let labels = label::labels(&format_labels(&self.labels)).into();
let assignees = self
.assignees
.iter()
.map(|author| (author.did, author.alias.clone(), author.is_you))
.collect::<Vec<_>>();
let assignees = label::did(&format_assignees(&assignees)).into();
let opened = label::timestamp(&format::timestamp(&self.timestamp)).into();
[state, id, title, author, labels, assignees, opened]
}
}
}