use crate::tui::daisyui_themes;
use crate::tui::input::{self, Action};
use crate::tui::state::{AppState, ConfirmAction, Overlay, PromptAction};
use crate::tui::view::Tab;
use anyhow::Result;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
Goto(Tab),
AddVar,
AddItem,
AddDef,
AddProfile,
Remove,
Use,
Duplicate,
Rename,
Save,
Theme,
Quit,
}
pub struct Spec {
pub names: &'static [&'static str],
pub command: Command,
pub help: &'static str,
}
pub const COMMANDS: &[Spec] = &[
Spec {
names: &["env", "edit"],
command: Command::Goto(Tab::Env),
help: "edit the active profile",
},
Spec {
names: &["profiles"],
command: Command::Goto(Tab::Profiles),
help: "list profiles",
},
Spec {
names: &["library", "lib", "items"],
command: Command::Goto(Tab::Library),
help: "values you reuse across profiles",
},
Spec {
names: &["defs"],
command: Command::Goto(Tab::Defs),
help: "your variable definitions",
},
Spec {
names: &["export", "preview"],
command: Command::Goto(Tab::Export),
help: "shell output for the active profile",
},
Spec {
names: &["help"],
command: Command::Goto(Tab::Help),
help: "keys and commands",
},
Spec {
names: &["add-var", "new-var", "av"],
command: Command::AddVar,
help: "add a line to the env file",
},
Spec {
names: &["add-item", "new-item", "ai"],
command: Command::AddItem,
help: "add a value to the library",
},
Spec {
names: &["add-def", "new-def", "ad"],
command: Command::AddDef,
help: "add a variable definition",
},
Spec {
names: &["add-profile", "new-profile", "ap"],
command: Command::AddProfile,
help: "create an empty profile",
},
Spec {
names: &["rm", "del", "delete"],
command: Command::Remove,
help: "rm [VAR]: remove a var, line or profile",
},
Spec {
names: &["use", "switch"],
command: Command::Use,
help: "use <profile>",
},
Spec {
names: &["dup", "duplicate", "copy"],
command: Command::Duplicate,
help: "copy the selected profile",
},
Spec {
names: &["rename", "mv"],
command: Command::Rename,
help: "rename the selected profile",
},
Spec {
names: &["save", "w"],
command: Command::Save,
help: "save the current tab",
},
Spec {
names: &["theme"],
command: Command::Theme,
help: "theme <name>",
},
Spec {
names: &["quit", "q", "exit"],
command: Command::Quit,
help: "quit bath",
},
];
pub fn lookup(name: &str) -> Option<Command> {
COMMANDS
.iter()
.find(|s| s.names.contains(&name))
.map(|s| s.command)
}
pub fn is_command(name: &str) -> bool {
lookup(name).is_some()
}
pub fn takes_argument(name: &str) -> bool {
matches!(
lookup(name),
Some(Command::Use | Command::Theme | Command::Remove)
)
}
pub fn is_known_argument(app: &AppState, command: &str, argument: &str) -> bool {
match lookup(command) {
Some(Command::Use) => app.profiles.iter().any(|p| p.name == argument),
Some(Command::Theme) => daisyui_themes::get(argument).is_some(),
Some(Command::Remove) => app.parse_env().vars.iter().any(|v| v.name == argument),
_ => false,
}
}
pub const MAX_VISIBLE_SUGGESTIONS: usize = 8;
pub fn clamp_selection(selected: usize, len: usize) -> usize {
selected.min(len.saturating_sub(1))
}
pub fn suggestion_window(selected: usize, len: usize, visible: usize) -> (usize, usize) {
if len == 0 || visible == 0 {
return (0, 0);
}
let selected = clamp_selection(selected, len);
let start = selected
.saturating_sub(visible - 1)
.min(len.saturating_sub(visible));
(start, selected - start)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Suggestion {
pub text: String,
pub help: String,
}
fn argument_suggestions(prefix: &str, query: &str, names: Vec<String>) -> Vec<Suggestion> {
let q = query.to_lowercase();
names
.into_iter()
.filter(|n| n.to_lowercase().contains(&q))
.map(|n| Suggestion {
text: format!("{prefix} {n}"),
help: String::new(),
})
.collect()
}
pub fn suggestions(app: &AppState, input: &str) -> Vec<Suggestion> {
let input = input.trim_start();
if let Some((word, rest)) = input.split_once(' ') {
let names = match lookup(word) {
Some(Command::Use) => app.profiles.iter().map(|p| p.name.clone()).collect(),
Some(Command::Theme) => daisyui_themes::names()
.into_iter()
.map(str::to_string)
.collect(),
Some(Command::Remove) => app.parse_env().vars.into_iter().map(|v| v.name).collect(),
_ => Vec::new(),
};
return argument_suggestions(word, rest.trim(), names);
}
let q = input.to_lowercase();
let matches = |s: &&Spec| q.is_empty() || s.names.iter().any(|n| n.starts_with(&q));
COMMANDS
.iter()
.filter(matches)
.map(|s| {
let name = s
.names
.iter()
.find(|n| n.starts_with(&q))
.unwrap_or(&s.names[0]);
Suggestion {
text: name.to_string(),
help: format!("{:<28}{}", s.names.join(" "), s.help),
}
})
.collect()
}
pub fn pick(app: &AppState, input: &str, selected: usize) -> String {
let typed = input.trim();
let (word, arg) = typed.split_once(' ').unwrap_or((typed, ""));
let arg = arg.trim();
let complete = match (is_command(word), takes_argument(word)) {
(false, _) => false,
(true, false) => true,
(true, true) => arg.is_empty() || is_known_argument(app, word, arg),
};
if complete {
return typed.to_string();
}
let list = suggestions(app, typed);
list.get(clamp_selection(selected, list.len()))
.map(|s| s.text.clone())
.unwrap_or_else(|| typed.to_string())
}
fn goto_new_line(app: &mut AppState, tab: Tab) {
app.tab = tab;
let Some(buf) = app.buffer_mut(tab) else {
return;
};
buf.append_line("");
}
pub fn execute(app: &mut AppState, line: &str) -> Result<Action> {
let line = line.trim();
let (word, arg) = line.split_once(' ').unwrap_or((line, ""));
let arg = arg.trim();
let Some(command) = lookup(word) else {
if !line.is_empty() {
app.status = format!("unknown command: {word}");
}
return Ok(Action::None);
};
match command {
Command::Goto(tab) => app.tab = tab,
Command::AddVar => goto_new_line(app, Tab::Env),
Command::AddItem => goto_new_line(app, Tab::Library),
Command::AddDef => goto_new_line(app, Tab::Defs),
Command::AddProfile => {
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Add,
input: String::new(),
});
}
Command::Remove => remove(app, arg),
Command::Use => use_named(app, arg),
Command::Duplicate => input::open_profile_prompt(app, true),
Command::Rename => input::open_profile_prompt(app, false),
Command::Save => input::save_tab(app, app.tab)?,
Command::Theme => theme(app, arg)?,
Command::Quit => return Ok(input::request_quit(app)),
}
Ok(Action::None)
}
fn remove_named(app: &mut AppState, var: &str) {
app.tab = Tab::Env;
if !app.remove_env_var(var) {
app.status = format!("{var} is not in {}", app.env_title());
return;
}
app.status = format!("removed {var} (Ctrl+S saves, Ctrl+Z undoes)");
}
fn remove(app: &mut AppState, arg: &str) {
if !arg.is_empty() {
remove_named(app, arg);
return;
}
match app.tab {
Tab::Env => {
let Some(var) = app.env_var_at_cursor() else {
app.env.delete_line();
return;
};
app.remove_env_var(&var);
app.status = format!("removed {var} (Ctrl+S saves, Ctrl+Z undoes)");
}
Tab::Library | Tab::Defs => {
if let Some(buf) = app.buffer_mut(app.tab) {
buf.delete_line();
}
}
Tab::Profiles => input::confirm_delete_profile(app),
_ => app.status = "nothing to remove here".to_string(),
}
}
fn use_named(app: &mut AppState, name: &str) {
let Some(index) = app.profiles.iter().position(|p| p.name == name) else {
app.status = format!("profile not found: {name}");
return;
};
input::use_profile_checked(app, index);
}
fn theme(app: &mut AppState, name: &str) -> Result<()> {
if name.is_empty() {
app.status = format!(
"theme <name>: {} themes, current {}",
daisyui_themes::THEMES.len(),
app.theme_preset
);
return Ok(());
}
if !app.set_theme_preset(name, true)? {
app.status = format!("theme not found: {name}");
return Ok(());
}
app.status = format!("theme: {}", app.theme.name);
Ok(())
}
pub fn open_palette(app: &mut AppState) {
app.completion = None;
app.overlay = Some(Overlay::Palette {
input: String::new(),
selected: 0,
});
}
pub fn confirm(app: &mut AppState, message: String, action: ConfirmAction) {
app.overlay = Some(Overlay::Confirm { message, action });
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::state::tests::test_app;
#[test]
fn aliases_resolve_to_the_same_command() {
for name in ["add-var", "new-var", "av"] {
assert_eq!(lookup(name), Some(Command::AddVar));
}
for name in ["add-item", "new-item", "ai"] {
assert_eq!(lookup(name), Some(Command::AddItem));
}
for name in ["rm", "del"] {
assert_eq!(lookup(name), Some(Command::Remove));
}
for name in ["use", "switch"] {
assert_eq!(lookup(name), Some(Command::Use));
}
for name in ["q", "quit", "exit"] {
assert_eq!(lookup(name), Some(Command::Quit));
}
}
#[test]
fn no_alias_is_listed_twice() {
let mut names: Vec<&str> = COMMANDS
.iter()
.flat_map(|s| s.names.iter().copied())
.collect();
let total = names.len();
names.sort();
names.dedup();
assert_eq!(names.len(), total);
}
#[test]
fn suggestions_match_aliases_and_arguments() {
let app = test_app(&["work", "home"]);
let texts: Vec<String> = suggestions(&app, "new")
.into_iter()
.map(|s| s.text)
.collect();
assert!(texts.contains(&"new-var".to_string()));
assert!(texts.contains(&"new-item".to_string()));
let texts: Vec<String> = suggestions(&app, "switch h")
.into_iter()
.map(|s| s.text)
.collect();
assert_eq!(texts, vec!["switch home".to_string()]);
}
#[test]
fn pick_prefers_typed_complete_commands() {
let app = test_app(&["work"]);
assert_eq!(pick(&app, "q", 0), "q");
assert_eq!(pick(&app, "use work", 0), "use work");
assert_eq!(pick(&app, "use wo", 0), "use work");
assert_eq!(pick(&app, "lib", 0), "lib");
assert_eq!(pick(&app, "libr", 0), "library");
}
#[test]
fn add_var_appends_a_line_in_env() -> Result<()> {
let mut app = test_app(&["work"]);
app.env.insert_str("CC = clang");
app.tab = Tab::Help;
execute(&mut app, "av")?;
assert_eq!(app.tab, Tab::Env);
assert_eq!(app.env.lines(), &["CC = clang", ""]);
assert_eq!(app.env.row, 1);
Ok(())
}
#[test]
fn rm_with_name_removes_the_var() -> Result<()> {
let mut app = test_app(&["work"]);
app.env.insert_str("PATH = /a\n /b\nCC = clang");
execute(&mut app, "del PATH")?;
assert_eq!(app.env.lines(), &["CC = clang"]);
Ok(())
}
#[test]
fn clamp_selection_clamps_to_last_index_and_zero_when_empty() {
assert_eq!(clamp_selection(0, 14), 0);
assert_eq!(clamp_selection(20, 14), 13);
assert_eq!(clamp_selection(5, 0), 0);
}
#[test]
fn suggestion_window_start_plus_row_is_the_clamped_selection() {
for len in 1..20usize {
for sel in 0..25usize {
for vis in 1..10usize {
let (start, row) = suggestion_window(sel, len, vis);
assert_eq!(start + row, clamp_selection(sel, len));
assert!(row < vis);
assert!(start + vis.min(len) <= len);
}
}
}
}
}