Skip to content

Feature/UI rework #337

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
256 changes: 191 additions & 65 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ path = "src/main.rs"
clap = { version = "4.3.22", features = ["derive"] }
# pretty dialogues in terminal
dialoguer = "0.10.3"
termion = "2.0.1"
termion = "4.0.0"
# Yaml support to save/load command pallettes
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8"
Expand All @@ -43,7 +43,10 @@ log = "0.4"
eyre = "0.6"
simple_logger = "4.1.0"
prettytable-rs = "0.10.0"
ratatui = { version = "0.22.0", features = ["termion"] }
ratatui = { version = "=0.26.2", default-features = false, features = [
'termion',
'serde',
] }
chrono = { version = "0.4", features = ["serde"] }
rand = { version = "0.8.4", features = ["std"] }
thiserror = "1.0"
Expand All @@ -59,6 +62,7 @@ chatgpt_blocking_rs = "0.1.2"
dotenv = "0.15.0"
h2 = "0.3.20"
regex = "1.10.2"
edit = "0.1.5"

[dev-dependencies]
tempfile = "3.3.0"
3 changes: 3 additions & 0 deletions src/cli_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ pub enum Commands {
name: String,
},

/// Edit the all your commands in your default editor
EditTrove {},

/// Print shell config
ShellConfig {
/// shell type to print the config for
Expand Down
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::gui::prompts::prompt_input;
use crate::control::prompts::prompt_input;
use anyhow::{anyhow, Error, Result};
use log::info;
use serde::{Deserialize, Serialize};
Expand Down
39 changes: 39 additions & 0 deletions src/control/merge.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use crate::control::prompts::prompt_select_with_options;
use enum_iterator::{all, Sequence};

#[derive(Sequence)]
pub enum ConflictResolve {
/// Describes the mode of how to handle a merge conflict by adding in a command to a trove with a name that is already present

/// Replace the old command with the new one
Replace,
/// Keep the old command and discard the new one
Keep,
/// Find a new name for the new command and keep the old one
New,
}

impl ConflictResolve {
const fn as_str(&self) -> &'static str {
match self {
Self::Replace => "Replace your local command with the new one",
Self::Keep => "Keep your local command and ignore the new one",
Self::New => "Keep both, but choose a new name",
}
}
}

pub fn with_conflict_resolve_prompt(
name: &str,
namespace: &str,
command_string: &str,
colliding_command_string: &str,
) -> ConflictResolve {
let conflict_prompt = format!(
"You already have a command with the name: {name} in namespace: {namespace}\nYour local command: {colliding_command_string}\nIncoming command: {command_string}\nWhat do you want to do?"
);
let conflict_modes = all::<ConflictResolve>().collect::<Vec<_>>();
let items: Vec<&str> = conflict_modes.iter().map(ConflictResolve::as_str).collect();
let selection = prompt_select_with_options(&conflict_prompt, &items);
conflict_modes.into_iter().nth(selection).unwrap()
}
2 changes: 2 additions & 0 deletions src/control/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod prompts;
pub mod merge;
135 changes: 135 additions & 0 deletions src/control/prompts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use dialoguer::{Input, MultiSelect, Password, Select};
pub enum Confirmation {
Yes,
No,
}

pub fn prompt_multiselect_options<F, T, S>(
question: &str,
selection_prompt: &str,
options: &[T],
text_extractor: F,
) -> Vec<T>
where
F: FnMut(&T) -> S,
T: Clone,
S: ToString,
{
let options_texts: Vec<S> = options.iter().map(text_extractor).collect();

if matches!(prompt_yes_or_no(question), Confirmation::Yes) {
let selected_indices = MultiSelect::default()
.with_prompt(selection_prompt)
.items(&options_texts)
.interact()
.unwrap();

take_elements_by_indices(options, &selected_indices)
} else {
options.to_vec()
}
}

pub fn prompt_yes_or_no(text: &str) -> Confirmation {
const YES_ANSWER: usize = 0;

let answer = Select::new()
.with_prompt(text)
.items(&["Yes", "No"])
.default(YES_ANSWER)
.interact()
.unwrap();

if answer == YES_ANSWER {
Confirmation::Yes
} else {
Confirmation::No
}
}

pub fn prompt_select_with_options(text_prompt: &str, options: &[&str]) -> usize {
Select::new()
.with_prompt(text_prompt)
.items(options)
.default(0)
.interact()
.unwrap()
}

pub fn prompt_input(text: &str, allow_empty: bool, default_value: Option<String>) -> String {
// Just calls `prompt_input_validate` to not keep on typing `None` for the validator
prompt_input_validate(
text,
allow_empty,
default_value,
None::<Box<dyn FnMut(&String) -> Result<(), String>>>,
)
}

pub fn prompt_input_validate<F>(
text: &str,
allow_empty: bool,
default_value: Option<String>,
validator: Option<F>,
) -> String
where
F: FnMut(&String) -> Result<(), String>,
{
let mut input: Input<String> = Input::new();
// Add default value to input prompt
if let Some(val) = default_value {
input.default(val);
}
// Add validator if any
if let Some(val) = validator {
input.validate_with(val);
}
input.allow_empty(allow_empty);
input.with_prompt(text).interact_text().unwrap()
}

pub fn prompt_password_repeat(text: &str) -> String {
Password::new()
.with_prompt(text)
.with_confirmation("Repeat password", "Error: the passwords don't match.")
.interact()
.unwrap()
}

pub fn prompt_password(text: &str) -> String {
Password::new()
.with_prompt(text)
.interact()
.unwrap()
}

fn take_elements_by_indices<T>(elements: &[T], indices: &[usize]) -> Vec<T>
where
T: Clone,
{
elements
.iter()
.enumerate()
.filter_map(|(i, val)| {
if indices.contains(&i) {
Some(val.clone())
} else {
None
}
})
.collect()
}

#[cfg(test)]
mod test_prompts {
use super::*;

#[test]
fn elements_by_indices() {
let items = vec!["item1", "item2", "item3", "item4"];
let indices = vec![1, 3];
let expected_items = vec![items[1], items[3]];

assert_eq!(expected_items, take_elements_by_indices(&items, &indices));
}
}
4 changes: 2 additions & 2 deletions src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ pub mod trove;

use crate::core::error::HoardErr;
use crate::core::trove::Trove;
use crate::gui::merge::{with_conflict_resolve_prompt, ConflictResolve};
use crate::gui::prompts::{prompt_input, prompt_input_validate, prompt_select_with_options};
use crate::control::merge::{with_conflict_resolve_prompt, ConflictResolve};
use crate::control::prompts::{prompt_input, prompt_input_validate, prompt_select_with_options};
use rand::distributions::Alphanumeric;
use rand::Rng;
use serde::{Deserialize, Serialize};
Expand Down
2 changes: 1 addition & 1 deletion src/core/parameters.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use regex::Regex;

use crate::core::HoardCmd;
use crate::gui::prompts::prompt_input;
use crate::control::prompts::prompt_input;

pub trait Parameterized {
/// Checks if the command string contains a specific token.
Expand Down
Loading
Loading