use crate::config::EnvProfile;
use crate::tui::commands;
use crate::tui::state::{
AppState, ConfirmAction, FilterTarget, Overlay, PromptAction, RenameOutcome, SaveOutcome,
};
use crate::tui::view::Tab;
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::widgets::ListState;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
None,
Quit,
Copy(String),
}
const PAGE: usize = 10;
fn ctrl(key: &KeyEvent) -> bool {
key.modifiers.contains(KeyModifiers::CONTROL)
}
fn alt(key: &KeyEvent) -> bool {
key.modifiers.contains(KeyModifiers::ALT)
}
fn ctrl_char(key: &KeyEvent, c: char) -> bool {
ctrl(key) && matches!(key.code, KeyCode::Char(k) if k.eq_ignore_ascii_case(&c))
}
pub fn handle_key(app: &mut AppState, key: KeyEvent) -> Result<Action> {
if app.overlay.is_some() {
return handle_overlay(app, key);
}
let armed = std::mem::take(&mut app.discard_armed);
if ctrl_char(&key, 'c') || ctrl_char(&key, 'q') {
return Ok(request_quit(app));
}
if ctrl_char(&key, 'p') {
commands::open_palette(app);
return Ok(Action::None);
}
if ctrl_char(&key, 's') {
save_tab(app, app.tab)?;
return Ok(Action::None);
}
if let (true, KeyCode::Char(c)) = (alt(&key), key.code) {
if let Some(tab) = Tab::from_digit(c) {
switch_tab(app, tab);
return Ok(Action::None);
}
}
if key.code == KeyCode::BackTab {
switch_tab(app, app.tab.prev());
return Ok(Action::None);
}
if key.code == KeyCode::Tab {
if app.completion.is_some() {
app.accept_completion();
return Ok(Action::None);
}
switch_tab(app, app.tab.next());
return Ok(Action::None);
}
if app.tab.is_buffer() {
handle_buffer(app, key, armed);
return Ok(Action::None);
}
match app.tab {
Tab::Profiles => handle_profiles(app, key),
Tab::Library => handle_library(app, key),
Tab::Defs => handle_defs(app, key),
Tab::Export => Ok(handle_export(app, key)),
_ => Ok(handle_help(app, key)),
}
}
pub fn handle_paste(app: &mut AppState, text: &str) {
let first = text.lines().next().unwrap_or("");
match &mut app.overlay {
Some(Overlay::Palette { input, .. })
| Some(Overlay::Prompt { input, .. })
| Some(Overlay::Picker { input, .. }) => input.push_str(first),
Some(Overlay::Filter { target }) => {
let target = target.clone();
filter_text(app, &target).push_str(first);
}
Some(Overlay::Confirm { .. }) => {}
None => {
let tab = app.tab;
let Some(buf) = app.buffer_mut(tab) else {
return;
};
buf.insert_str(text);
app.completion = None;
app.status.clear();
}
}
}
fn switch_tab(app: &mut AppState, tab: Tab) {
app.completion = None;
if app.tab != tab {
app.scroll = 0;
}
app.tab = tab;
}
pub fn request_quit(app: &mut AppState) -> Action {
let modified = app.modified_tabs();
if modified.is_empty() {
return Action::Quit;
}
commands::confirm(
app,
format!("quit without saving {}?", modified.join(", ")),
ConfirmAction::Quit,
);
Action::None
}
pub fn save_tab(app: &mut AppState, tab: Tab) -> Result<()> {
if tab != Tab::Env {
app.status = "changes here are saved right away".to_string();
return Ok(());
}
app.status = match app.save_env()? {
SaveOutcome::Saved(message) | SaveOutcome::Blocked(message) => message,
SaveOutcome::Unchanged => "nothing to save".to_string(),
SaveOutcome::Invalid { line, message } => {
app.env.goto(line);
format!("not saved, line {}: {message}", line + 1)
}
};
Ok(())
}
pub fn use_profile_checked(app: &mut AppState, index: usize) {
if app.env.is_modified() && index != app.active_profile_index {
let message = format!(
"switch to {} and discard unsaved changes in {}?",
app.profiles[index].name,
app.env_title()
);
commands::confirm(app, message, ConfirmAction::UseProfile(index));
return;
}
use_profile_now(app, index);
}
fn use_profile_now(app: &mut AppState, index: usize) {
app.use_profile(index);
app.tab = Tab::Env;
app.status = format!("using {}", app.active_profile().name);
}
fn target_profile(app: &AppState) -> usize {
match app.tab {
Tab::Profiles => app.selected_profile().unwrap_or(app.active_profile_index),
_ => app.active_profile_index,
}
}
pub fn open_profile_prompt(app: &mut AppState, duplicate: bool) {
let index = target_profile(app);
let name = app.profiles[index].name.clone();
if !duplicate {
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Rename(index),
input: name,
});
return;
}
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Duplicate(index),
input: format!("{name}-copy"),
});
}
pub fn confirm_delete_profile(app: &mut AppState) {
if app.profiles.len() <= 1 {
app.status = "cannot delete the last profile".to_string();
return;
}
let index = target_profile(app);
let message = format!("delete profile {}?", app.profiles[index].name);
commands::confirm(app, message, ConfirmAction::DeleteProfile(index));
}
fn handle_buffer(app: &mut AppState, key: KeyEvent, armed: bool) {
let tab = app.tab;
if key.code == KeyCode::Esc {
escape(app, tab, armed);
return;
}
if let Some(c) = &mut app.completion {
let len = c.items.len();
match key.code {
KeyCode::Up => {
c.selected = (c.selected + len - 1) % len;
return;
}
KeyCode::Down => {
c.selected = (c.selected + 1) % len;
return;
}
_ => {}
}
}
if ctrl_char(&key, 'l') && tab == Tab::Env {
app.completion = None;
app.overlay = Some(Overlay::Picker {
input: String::new(),
selected: 0,
});
return;
}
let indent = match (key.code, tab) {
(KeyCode::Enter, Tab::Env) => app.env_indent(),
_ => 0,
};
let Some(buf) = app.buffer_mut(tab) else {
return;
};
let edited = match (key.code, ctrl(&key), alt(&key)) {
(KeyCode::Char('k' | 'K'), true, _) => {
buf.delete_line();
true
}
(KeyCode::Char('d' | 'D'), true, _) => {
buf.duplicate_line();
true
}
(KeyCode::Char('z' | 'Z'), true, _) => buf.undo(),
(KeyCode::Up, _, true) => {
buf.move_line_up();
true
}
(KeyCode::Down, _, true) => {
buf.move_line_down();
true
}
(KeyCode::Char(c), false, false) => {
buf.insert_char(c);
true
}
(KeyCode::Enter, _, _) => {
if !buf.clear_indent_line() {
buf.newline(indent);
}
true
}
(KeyCode::Backspace, _, _) => {
buf.backspace();
true
}
(KeyCode::Delete, _, _) => {
buf.delete();
true
}
(KeyCode::Left, _, _) => {
buf.left();
false
}
(KeyCode::Right, _, _) => {
buf.right();
false
}
(KeyCode::Up, _, _) => {
buf.up(1);
false
}
(KeyCode::Down, _, _) => {
buf.down(1);
false
}
(KeyCode::PageUp, _, _) => {
buf.up(PAGE);
false
}
(KeyCode::PageDown, _, _) => {
buf.down(PAGE);
false
}
(KeyCode::Home, _, _) => {
buf.home();
false
}
(KeyCode::End, _, _) => {
buf.end();
false
}
_ => return,
};
if !edited {
app.completion = None;
return;
}
app.status.clear();
app.update_completion();
}
fn escape(app: &mut AppState, tab: Tab, armed: bool) {
if app.completion.take().is_some() {
return;
}
let modified = app.buffer(tab).is_some_and(|b| b.is_modified());
if !modified {
return;
}
if armed {
app.load_env();
app.status = "discarded unsaved changes".to_string();
return;
}
app.discard_armed = true;
app.status = "press Esc again to discard unsaved changes".to_string();
}
fn navigate(list: &mut ListState, len: usize, key: &KeyEvent) -> bool {
let selected = list.selected().unwrap_or(0);
let last = len.saturating_sub(1);
let row = match key.code {
KeyCode::Char('j') | KeyCode::Down => (selected + 1).min(last),
KeyCode::Char('k') | KeyCode::Up => selected.saturating_sub(1),
KeyCode::PageDown => (selected + PAGE).min(last),
KeyCode::PageUp => selected.saturating_sub(PAGE),
KeyCode::Char('g') | KeyCode::Home => 0,
KeyCode::Char('G') | KeyCode::End => last,
_ => return false,
};
list.select(Some(row));
true
}
fn open_filter(app: &mut AppState, target: FilterTarget) {
app.overlay = Some(Overlay::Filter { target });
}
fn prompt(app: &mut AppState, action: PromptAction, input: String) {
app.overlay = Some(Overlay::Prompt { action, input });
}
pub fn open_item_prompt(app: &mut AppState, edit: bool) {
app.tab = Tab::Library;
let Some(index) = app.selected_item().filter(|_| edit) else {
prompt(app, PromptAction::AddItem, String::new());
return;
};
let line = crate::listfiles::format_library(std::slice::from_ref(&app.items[index])).concat();
prompt(app, PromptAction::EditItem(index), line);
}
pub fn open_def_prompt(app: &mut AppState, edit: bool) {
app.tab = Tab::Defs;
let Some(index) = app.selected_def().filter(|_| edit) else {
prompt(app, PromptAction::AddDef, String::new());
return;
};
let line =
crate::listfiles::format_defs(std::slice::from_ref(&app.custom_var_defs[index])).concat();
prompt(app, PromptAction::EditDef(index), line);
}
pub fn confirm_delete_item(app: &mut AppState) {
let Some(index) = app.selected_item() else {
app.status = "the library is empty".to_string();
return;
};
let value = app.items[index].value.clone();
let message = delete_item_message(&value, &app.value_users(&value));
commands::confirm(app, message, ConfirmAction::DeleteItem(index));
}
fn delete_item_message(value: &str, users: &[String]) -> String {
if users.is_empty() {
return format!("delete {value}?");
}
format!("delete {value}? used in {}", users.join(", "))
}
pub fn confirm_delete_def(app: &mut AppState) {
let Some(index) = app.selected_def() else {
app.status = "no definitions of yours yet".to_string();
return;
};
let message = format!("delete definition {}?", app.custom_var_defs[index].name);
commands::confirm(app, message, ConfirmAction::DeleteDef(index));
}
fn handle_library(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let len = app.visible_items().len();
if navigate(&mut app.library_list, len, &key) {
return Ok(Action::None);
}
match key.code {
KeyCode::Char('a' | 'A' | 'n') => open_item_prompt(app, false),
KeyCode::Enter | KeyCode::Char('e' | 'E') | KeyCode::F(2) => open_item_prompt(app, true),
KeyCode::Char('d' | 'D') | KeyCode::Delete => confirm_delete_item(app),
KeyCode::Char('y' | 'Y') => {
let Some(index) = app.selected_item() else {
return Ok(Action::None);
};
let value = app.items[index].value.clone();
app.status = format!("copied {value}");
return Ok(Action::Copy(value));
}
KeyCode::Char('/') => open_filter(app, FilterTarget::Library),
KeyCode::Esc => {
app.library_filter.clear();
app.library_list.select(Some(0));
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return Ok(request_quit(app)),
_ => {}
}
Ok(Action::None)
}
fn handle_defs(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let len = app.visible_defs().len();
if navigate(&mut app.defs_list, len, &key) {
return Ok(Action::None);
}
match key.code {
KeyCode::Char('a' | 'A' | 'n') => open_def_prompt(app, false),
KeyCode::Enter | KeyCode::Char('e' | 'E') | KeyCode::F(2) => open_def_prompt(app, true),
KeyCode::Char('d' | 'D') | KeyCode::Delete => confirm_delete_def(app),
KeyCode::Char('/') => open_filter(app, FilterTarget::Defs),
KeyCode::Esc => {
app.defs_filter.clear();
app.defs_list.select(Some(0));
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return Ok(request_quit(app)),
_ => {}
}
Ok(Action::None)
}
fn handle_profiles(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let len = app.visible_profiles().len();
if navigate(&mut app.profile_list, len, &key) {
return Ok(Action::None);
}
match key.code {
KeyCode::Enter => {
if let Some(index) = app.selected_profile() {
use_profile_checked(app, index);
}
}
KeyCode::Char('a' | 'A' | 'n') => {
app.overlay = Some(Overlay::Prompt {
action: PromptAction::Add,
input: String::new(),
});
}
KeyCode::Char('e' | 'E' | 'r') | KeyCode::F(2) => open_profile_prompt(app, false),
KeyCode::Char('y' | 'Y') => open_profile_prompt(app, true),
KeyCode::Char('d' | 'D') | KeyCode::Delete => confirm_delete_profile(app),
KeyCode::Char('/') => open_filter(app, FilterTarget::Profiles),
KeyCode::Esc => {
app.profiles_filter.clear();
app.profile_list.select(Some(0));
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return Ok(request_quit(app)),
_ => {}
}
Ok(Action::None)
}
fn scroll(app: &mut AppState, key: &KeyEvent) -> bool {
let step = match key.code {
KeyCode::Char('j') | KeyCode::Down => 1i32,
KeyCode::Char('k') | KeyCode::Up => -1,
KeyCode::PageDown | KeyCode::Char(' ') => PAGE as i32,
KeyCode::PageUp => -(PAGE as i32),
KeyCode::Char('g') | KeyCode::Home => -(app.scroll as i32),
_ => return false,
};
app.scroll = (app.scroll as i32 + step).max(0) as u16;
true
}
fn handle_export(app: &mut AppState, key: KeyEvent) -> Action {
if scroll(app, &key) {
return Action::None;
}
match key.code {
KeyCode::Char('m') => app.cycle_export_mode(),
KeyCode::Char('y') => {
app.status = "copied export to the clipboard".to_string();
return Action::Copy(app.export_text());
}
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return request_quit(app),
_ => {}
}
Action::None
}
fn handle_help(app: &mut AppState, key: KeyEvent) -> Action {
if scroll(app, &key) {
return Action::None;
}
match key.code {
KeyCode::Char(':') => commands::open_palette(app),
KeyCode::Char('q') => return request_quit(app),
_ => {}
}
Action::None
}
fn edit_text(input: &mut String, key: &KeyEvent) -> bool {
if ctrl_char(key, 'u') {
input.clear();
return true;
}
match (key.code, ctrl(key)) {
(KeyCode::Char(c), false) => {
input.push(c);
true
}
(KeyCode::Backspace, _) => input.pop().is_some(),
_ => false,
}
}
fn handle_overlay(app: &mut AppState, key: KeyEvent) -> Result<Action> {
let Some(overlay) = app.overlay.take() else {
return Ok(Action::None);
};
if ctrl_char(&key, 'c') {
return Ok(Action::None);
}
match overlay {
Overlay::Palette { input, selected } => palette_key(app, key, input, selected),
Overlay::Prompt { action, input } => {
prompt_key(app, key, action, input)?;
Ok(Action::None)
}
Overlay::Confirm { message, action } => confirm_key(app, key, message, action),
Overlay::Picker { input, selected } => {
picker_key(app, key, input, selected);
Ok(Action::None)
}
Overlay::Filter { target } => {
filter_key(app, key, target);
Ok(Action::None)
}
}
}
fn palette_key(
app: &mut AppState,
key: KeyEvent,
mut input: String,
mut selected: usize,
) -> Result<Action> {
match key.code {
KeyCode::Esc => return Ok(Action::None),
KeyCode::Enter => {
let line = commands::pick(app, &input, selected);
return commands::execute(app, &line);
}
KeyCode::Tab => {
let list = commands::suggestions(app, &input);
if let Some(s) = list.get(commands::clamp_selection(selected, list.len())) {
input = s.text.clone();
if commands::takes_argument(&input) {
input.push(' ');
}
selected = 0;
}
}
KeyCode::Up => selected = selected.saturating_sub(1),
KeyCode::Down => selected += 1,
_ => {
if edit_text(&mut input, &key) {
selected = 0;
}
}
}
let len = commands::suggestions(app, &input).len();
selected = commands::clamp_selection(selected, len);
app.overlay = Some(Overlay::Palette { input, selected });
Ok(Action::None)
}
fn select_profile_named(app: &mut AppState, name: &str) {
app.profiles_filter.clear();
let index = app.profiles.iter().position(|p| p.name == name);
app.profile_list.select(index);
}
fn prompt_key(
app: &mut AppState,
key: KeyEvent,
action: PromptAction,
mut input: String,
) -> Result<()> {
match key.code {
KeyCode::Esc => {
app.status.clear();
return Ok(());
}
KeyCode::Enter => {
let done = submit(app, &action, &input)?;
if done {
return Ok(());
}
}
_ => {
edit_text(&mut input, &key);
}
}
app.overlay = Some(Overlay::Prompt { action, input });
Ok(())
}
fn submit(app: &mut AppState, action: &PromptAction, input: &str) -> Result<bool> {
let outcome = match action {
PromptAction::AddItem => app.save_item(None, input)?,
PromptAction::EditItem(index) => app.save_item(Some(*index), input)?,
PromptAction::AddDef => app.save_def(None, input)?,
PromptAction::EditDef(index) => app.save_def(Some(*index), input)?,
_ => return submit_profile_prompt(app, action, input.trim()),
};
let (done, message) = match outcome {
SaveOutcome::Saved(message) => (true, message),
SaveOutcome::Unchanged => (true, String::new()),
SaveOutcome::Invalid { message, .. } | SaveOutcome::Blocked(message) => (false, message),
};
app.status = message;
Ok(done)
}
fn submit_profile_prompt(app: &mut AppState, action: &PromptAction, name: &str) -> Result<bool> {
let ok = match action {
PromptAction::Add => app.add_profile(EnvProfile::new(name))?,
PromptAction::Duplicate(index) => app.duplicate_profile(*index, name)?,
PromptAction::Rename(index) => match app.update_profile(*index, name.to_string())? {
RenameOutcome::Renamed => true,
RenameOutcome::Unchanged => return Ok(true),
RenameOutcome::Rejected => false,
},
_ => return Ok(true),
};
if !ok {
app.status = format!("'{name}' is blank or already taken");
return Ok(false);
}
select_profile_named(app, name);
app.status = match action {
PromptAction::Add => format!("added profile {name}"),
PromptAction::Duplicate(index) => {
format!("copied {} to {name}", app.profiles[*index].name)
}
_ => format!("renamed to {name}"),
};
Ok(true)
}
fn confirm_key(
app: &mut AppState,
key: KeyEvent,
message: String,
action: ConfirmAction,
) -> Result<Action> {
match key.code {
KeyCode::Char('y' | 'Y') | KeyCode::Enter => {}
KeyCode::Char('n' | 'N') | KeyCode::Esc => return Ok(Action::None),
_ => {
app.overlay = Some(Overlay::Confirm { message, action });
return Ok(Action::None);
}
}
match action {
ConfirmAction::Quit => return Ok(Action::Quit),
ConfirmAction::UseProfile(index) => use_profile_now(app, index),
ConfirmAction::DeleteProfile(index) => {
let name = app.profiles[index].name.clone();
if app.delete_profile(index)? {
app.status = format!("deleted profile {name}");
}
let last = app.visible_profiles().len().saturating_sub(1);
let selected = app.profile_list.selected().unwrap_or(0).min(last);
app.profile_list.select(Some(selected));
}
ConfirmAction::DeleteItem(index) => {
if let Some(value) = app.delete_item(index)? {
app.status = format!("deleted {value}");
}
}
ConfirmAction::DeleteDef(index) => {
app.status = match app.delete_def(index)? {
SaveOutcome::Saved(message) | SaveOutcome::Blocked(message) => message,
_ => String::new(),
};
}
}
Ok(Action::None)
}
fn picker_key(app: &mut AppState, key: KeyEvent, mut input: String, mut selected: usize) {
match key.code {
KeyCode::Esc => return,
KeyCode::Enter => {
let items = app.picker_items(&input);
let Some(item) = items.get(selected.min(items.len().saturating_sub(1))) else {
return;
};
let value = item.value.clone();
app.env.insert_str(&value);
app.status = format!("inserted {value}");
return;
}
KeyCode::Up => selected = selected.saturating_sub(1),
KeyCode::Down => selected += 1,
_ => {
if edit_text(&mut input, &key) {
selected = 0;
}
}
}
let len = app.picker_items(&input).len();
selected = selected.min(len.saturating_sub(1));
app.overlay = Some(Overlay::Picker { input, selected });
}
pub fn filter_text<'a>(app: &'a mut AppState, target: &FilterTarget) -> &'a mut String {
match target {
FilterTarget::Profiles => &mut app.profiles_filter,
FilterTarget::Library => &mut app.library_filter,
FilterTarget::Defs => &mut app.defs_filter,
}
}
fn filter_list<'a>(app: &'a mut AppState, target: &FilterTarget) -> &'a mut ListState {
match target {
FilterTarget::Profiles => &mut app.profile_list,
FilterTarget::Library => &mut app.library_list,
FilterTarget::Defs => &mut app.defs_list,
}
}
fn filter_key(app: &mut AppState, key: KeyEvent, target: FilterTarget) {
filter_list(app, &target).select(Some(0));
if key.code == KeyCode::Enter {
return;
}
if key.code == KeyCode::Esc {
filter_text(app, &target).clear();
return;
}
edit_text(filter_text(app, &target), &key);
app.overlay = Some(Overlay::Filter { target });
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db;
use crate::tui::state::tests::test_app;
fn press(app: &mut AppState, code: KeyCode) -> Action {
handle_key(app, KeyEvent::new(code, KeyModifiers::NONE)).unwrap()
}
fn chord(app: &mut AppState, code: KeyCode, modifiers: KeyModifiers) -> Action {
handle_key(app, KeyEvent::new(code, modifiers)).unwrap()
}
fn type_keys(app: &mut AppState, text: &str) {
for c in text.chars() {
press(app, KeyCode::Char(c));
}
}
#[test]
fn shift_tab_cycles_back_and_alt_digit_jumps() {
let mut app = test_app(&["work"]);
press(&mut app, KeyCode::BackTab);
assert_eq!(app.tab, Tab::Help);
press(&mut app, KeyCode::BackTab);
assert_eq!(app.tab, Tab::Export);
chord(&mut app, KeyCode::Char('3'), KeyModifiers::ALT);
assert_eq!(app.tab, Tab::Library);
press(&mut app, KeyCode::Tab);
assert_eq!(app.tab, Tab::Defs);
}
#[test]
fn tab_accepts_completion_before_switching_tabs() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "PGHO");
assert!(app.completion.is_some());
press(&mut app, KeyCode::Tab);
assert_eq!(app.tab, Tab::Env);
assert_eq!(app.env.current_line(), "PGHOST = ");
}
#[test]
fn typing_q_in_env_inserts_text() {
let mut app = test_app(&["work"]);
assert_eq!(press(&mut app, KeyCode::Char('q')), Action::None);
assert_eq!(app.env.current_line(), "q");
}
#[test]
fn esc_twice_discards_changes() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Esc);
assert!(app.env.is_modified());
press(&mut app, KeyCode::Esc);
assert!(!app.env.is_modified());
}
#[test]
fn esc_then_typing_disarms_discard() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Esc);
type_keys(&mut app, "x");
press(&mut app, KeyCode::Esc);
assert!(app.env.is_modified());
}
#[test]
fn ctrl_s_saves_and_reports_errors_with_line() -> Result<()> {
let mut app = test_app(&["work"]);
type_keys(&mut app, "CC = clang");
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "PGP");
chord(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL);
assert!(app.status.contains("line 2"));
assert_eq!(app.env.row, 1);
press(&mut app, KeyCode::Backspace);
press(&mut app, KeyCode::Backspace);
press(&mut app, KeyCode::Backspace);
chord(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL);
assert_eq!(db::load_profile(&app.conn, "work")?.entries.len(), 1);
Ok(())
}
#[test]
fn quit_with_unsaved_changes_asks_first() {
let mut app = test_app(&["work"]);
assert_eq!(
chord(&mut app, KeyCode::Char('q'), KeyModifiers::CONTROL),
Action::Quit
);
type_keys(&mut app, "CC = clang");
assert_eq!(
chord(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL),
Action::None
);
assert!(matches!(app.overlay, Some(Overlay::Confirm { .. })));
assert_eq!(press(&mut app, KeyCode::Char('y')), Action::Quit);
}
#[test]
fn y_on_profiles_duplicates_with_prefilled_name() -> Result<()> {
let mut app = test_app(&["work"]);
app.tab = Tab::Profiles;
press(&mut app, KeyCode::Char('y'));
assert!(matches!(
&app.overlay,
Some(Overlay::Prompt { input, .. }) if input == "work-copy"
));
press(&mut app, KeyCode::Enter);
assert!(app.overlay.is_none());
assert_eq!(app.profiles.len(), 2);
assert!(db::load_profile(&app.conn, "work-copy").is_ok());
Ok(())
}
#[test]
fn palette_alias_opens_the_library_prompt() {
let mut app = test_app(&["work"]);
app.tab = Tab::Help;
chord(&mut app, KeyCode::Char('p'), KeyModifiers::CONTROL);
type_keys(&mut app, "ai");
press(&mut app, KeyCode::Enter);
assert_eq!(app.tab, Tab::Library);
assert!(matches!(
app.overlay,
Some(Overlay::Prompt {
action: PromptAction::AddItem,
..
})
));
}
#[test]
fn library_keys_add_edit_and_delete() -> Result<()> {
let mut app = test_app(&["work"]);
app.tab = Tab::Library;
press(&mut app, KeyCode::Char('a'));
type_keys(&mut app, "/opt/llvm/bin # llvm");
press(&mut app, KeyCode::Enter);
assert!(app.overlay.is_none());
assert_eq!(db::load_items(&app.conn)?[0].tags, vec!["llvm".to_string()]);
press(&mut app, KeyCode::Char('e'));
assert!(matches!(
&app.overlay,
Some(Overlay::Prompt { input, .. }) if input.starts_with("/opt/llvm/bin") && input.ends_with("# llvm")
));
chord(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
type_keys(&mut app, "/opt/llvm-18/bin");
press(&mut app, KeyCode::Enter);
assert_eq!(db::load_items(&app.conn)?[0].value, "/opt/llvm-18/bin");
press(&mut app, KeyCode::Char('d'));
press(&mut app, KeyCode::Char('y'));
assert!(db::load_items(&app.conn)?.is_empty());
Ok(())
}
#[test]
fn invalid_def_keeps_the_prompt_open() -> Result<()> {
let mut app = test_app(&["work"]);
app.tab = Tab::Defs;
press(&mut app, KeyCode::Char('a'));
type_keys(&mut app, "PATH list");
press(&mut app, KeyCode::Enter);
assert!(matches!(app.overlay, Some(Overlay::Prompt { .. })));
assert!(app.status.contains("built in"));
chord(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
type_keys(&mut app, "ACME list ','");
press(&mut app, KeyCode::Enter);
assert!(app.overlay.is_none());
assert_eq!(db::load_custom_var_defs(&app.conn)?.len(), 1);
Ok(())
}
#[test]
fn library_filter_narrows_the_list() -> Result<()> {
let mut app = test_app(&["work"]);
app.save_item(None, "/a # x")?;
app.save_item(None, "/b # y")?;
app.tab = Tab::Library;
press(&mut app, KeyCode::Char('/'));
type_keys(&mut app, "y");
press(&mut app, KeyCode::Enter);
assert_eq!(app.selected_item(), Some(1));
press(&mut app, KeyCode::Esc);
assert_eq!(app.visible_items().len(), 2);
Ok(())
}
#[test]
fn switching_profile_with_unsaved_env_asks_first() {
let mut app = test_app(&["a", "b"]);
type_keys(&mut app, "CC = clang");
app.tab = Tab::Profiles;
press(&mut app, KeyCode::Char('j'));
press(&mut app, KeyCode::Enter);
assert!(matches!(app.overlay, Some(Overlay::Confirm { .. })));
press(&mut app, KeyCode::Char('n'));
assert_eq!(app.active_profile_index, 0);
press(&mut app, KeyCode::Enter);
press(&mut app, KeyCode::Char('y'));
assert_eq!(app.active_profile_index, 1);
assert_eq!(app.tab, Tab::Env);
}
#[test]
fn enter_on_empty_list_line_ends_the_list() {
let mut app = test_app(&["work"]);
type_keys(&mut app, "PATH = /a");
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "/b");
press(&mut app, KeyCode::Enter);
press(&mut app, KeyCode::Enter);
type_keys(&mut app, "CC = clang");
assert_eq!(app.env.lines(), &["PATH = /a", " /b", "CC = clang"]);
}
#[test]
fn paste_inserts_multiple_lines() {
let mut app = test_app(&["work"]);
handle_paste(&mut app, "PATH = /a\n /b");
assert_eq!(app.env.lines(), &["PATH = /a", " /b"]);
}
#[test]
fn export_y_returns_copy_action() {
let mut app = test_app(&["work"]);
app.tab = Tab::Export;
assert!(matches!(
press(&mut app, KeyCode::Char('y')),
Action::Copy(_)
));
}
}