use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::ui::state::{AppState, InlineConnField, InlineConnMode};
use super::Action;
pub(super) fn handle_inline_conn_editor(state: &mut AppState, key: KeyEvent) -> Action {
if let Some(ed) = state.dialogs.inline_conn_editor.as_mut()
&& !ed.error_message.is_empty()
{
ed.error_message.clear();
}
if key.code == KeyCode::Char('p') && key.modifiers.contains(KeyModifiers::CONTROL) {
if let Some(ed) = state.dialogs.inline_conn_editor.as_mut() {
ed.password_visible = !ed.password_visible;
}
return Action::Render;
}
let mode = match state.dialogs.inline_conn_editor.as_ref() {
Some(ed) => ed.mode,
None => return Action::None,
};
match mode {
InlineConnMode::Normal => handle_normal(state, key),
InlineConnMode::Insert => handle_insert(state, key),
}
}
fn handle_normal(state: &mut AppState, key: KeyEvent) -> Action {
let ed = match state.dialogs.inline_conn_editor.as_mut() {
Some(e) => e,
None => return Action::None,
};
let field = ed.current_field();
match key.code {
KeyCode::Esc => {
state.dialogs.inline_conn_editor = None;
Action::Render
}
KeyCode::Char('j') | KeyCode::Down => {
ed.move_down();
Action::Render
}
KeyCode::Char('k') | KeyCode::Up => {
ed.move_up();
Action::Render
}
KeyCode::Char('i') | KeyCode::Char('a') | KeyCode::Char('o') => {
if field.is_text() {
ed.mode = InlineConnMode::Insert;
} else if matches!(field, InlineConnField::Type) {
ed.cycle_db_type();
} else if matches!(field, InlineConnField::Group) {
ed.cycle_group();
}
Action::Render
}
KeyCode::Char('l') | KeyCode::Char('h') | KeyCode::Tab | KeyCode::BackTab => {
match field {
InlineConnField::Type => ed.cycle_db_type(),
InlineConnField::Group => ed.cycle_group(),
_ => {}
}
Action::Render
}
KeyCode::Enter => {
if let Err(msg) = ed.validate() {
ed.error_message = msg.to_string();
return Action::Render;
}
ed.connecting = true;
ed.connecting_since = Some(std::time::Instant::now());
Action::InlineConnSaveAndConnect
}
KeyCode::Char('x') => {
if let Some(val) = ed.field_value_mut(field) {
val.clear();
}
Action::Render
}
_ => Action::None,
}
}
fn handle_insert(state: &mut AppState, key: KeyEvent) -> Action {
let ed = match state.dialogs.inline_conn_editor.as_mut() {
Some(e) => e,
None => return Action::None,
};
let field = ed.current_field();
match key.code {
KeyCode::Esc => {
ed.mode = InlineConnMode::Normal;
Action::Render
}
KeyCode::Enter => {
ed.mode = InlineConnMode::Normal;
ed.move_down();
Action::Render
}
KeyCode::Backspace => {
if let Some(val) = ed.field_value_mut(field) {
val.pop();
}
Action::Render
}
KeyCode::Char(c) => {
if let Some(val) = ed.field_value_mut(field) {
val.push(c);
}
Action::Render
}
KeyCode::Tab | KeyCode::Down => {
ed.mode = InlineConnMode::Normal;
ed.move_down();
Action::Render
}
KeyCode::BackTab | KeyCode::Up => {
ed.mode = InlineConnMode::Normal;
ed.move_up();
Action::Render
}
_ => Action::None,
}
}