use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEvent};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout},
text::{Line, Span},
widgets::{Clear, Paragraph},
Frame,
};
use tui_input::{backend::crossterm::EventHandler, Input};
use crate::types::{Auth, BackendType, ConnectionConfig};
use crate::ui::theme::{self, raw};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormField {
BackendType,
Name,
Host,
Port,
Password,
Database,
}
impl FormField {
pub fn next(&self, backend_type: BackendType) -> Self {
match self {
FormField::BackendType => FormField::Name,
FormField::Name => FormField::Host,
FormField::Host => FormField::Port,
FormField::Port => FormField::Password,
FormField::Password => {
if matches!(backend_type, BackendType::Redis) {
FormField::Database
} else {
FormField::BackendType
}
}
FormField::Database => FormField::BackendType,
}
}
pub fn prev(&self, backend_type: BackendType) -> Self {
match self {
FormField::BackendType => {
if matches!(backend_type, BackendType::Redis) {
FormField::Database
} else {
FormField::Password
}
}
FormField::Name => FormField::BackendType,
FormField::Host => FormField::Name,
FormField::Port => FormField::Host,
FormField::Password => FormField::Port,
FormField::Database => FormField::Password,
}
}
}
pub struct ConnectionForm {
pub name: Input,
pub host: Input,
pub port: Input,
pub password: Input,
pub database: Input,
pub active_field: FormField,
pub backend_type: BackendType,
}
impl ConnectionForm {
pub fn new() -> Self {
Self {
name: Input::default(),
host: Input::default().with_value("localhost".into()),
port: Input::default().with_value("6379".into()),
password: Input::default(),
database: Input::default().with_value("0".into()),
active_field: FormField::BackendType,
backend_type: BackendType::Redis,
}
}
pub fn select_backend_type(&mut self, backend: BackendType) {
self.backend_type = backend;
self.port = Input::default().with_value(
match backend {
BackendType::Redis => "6379",
BackendType::Memcached => "11211",
BackendType::Etcd => "2379",
}
.into(),
);
}
pub fn next_backend_type(&mut self) {
let next = match self.backend_type {
BackendType::Redis => BackendType::Memcached,
BackendType::Memcached => BackendType::Etcd,
BackendType::Etcd => BackendType::Redis,
};
self.select_backend_type(next);
}
pub fn prev_backend_type(&mut self) {
let prev = match self.backend_type {
BackendType::Redis => BackendType::Etcd,
BackendType::Memcached => BackendType::Redis,
BackendType::Etcd => BackendType::Memcached,
};
self.select_backend_type(prev);
}
pub fn handle_key_event(&mut self, event: KeyEvent) {
match self.active_field {
FormField::BackendType => match event.code {
KeyCode::Left => self.prev_backend_type(),
KeyCode::Right => self.next_backend_type(),
_ => {}
},
FormField::Name => {
let _ = self.name.handle_event(&CrosstermEvent::Key(event));
}
FormField::Host => {
let _ = self.host.handle_event(&CrosstermEvent::Key(event));
}
FormField::Port => {
let _ = self.port.handle_event(&CrosstermEvent::Key(event));
}
FormField::Password => {
let _ = self.password.handle_event(&CrosstermEvent::Key(event));
}
FormField::Database => {
let _ = self.database.handle_event(&CrosstermEvent::Key(event));
}
}
}
pub fn next_field(&mut self) {
self.active_field = self.active_field.next(self.backend_type);
}
pub fn prev_field(&mut self) {
self.active_field = self.active_field.prev(self.backend_type);
}
pub fn to_config(&self, default_timeout: Duration) -> Result<ConnectionConfig, String> {
let name = self.name.value().trim();
let host = self.host.value().trim();
let port_str = self.port.value().trim();
let password = self.password.value().trim();
let database = self.database.value().trim();
if name.is_empty() {
return Err("Name is required".to_string());
}
if host.is_empty() {
return Err("Host is required".to_string());
}
let port: u16 = port_str
.parse()
.map_err(|_| "Port must be a number between 1 and 65535".to_string())?;
let auth = if !password.is_empty() {
Some(Auth::Token(password.to_string()))
} else {
None
};
let database = match self.backend_type {
BackendType::Redis => {
if !database.is_empty() {
Some(database.to_string())
} else {
Some("0".to_string())
}
}
_ => None, };
let id = format!(
"{}_{}",
name.to_lowercase().replace(' ', "_"),
self.backend_type.to_string().to_lowercase()
);
Ok(ConnectionConfig {
id,
name: name.to_string(),
backend_type: self.backend_type,
host: host.to_string(),
port,
auth,
database,
tls: None,
timeout: default_timeout,
read_only: false,
})
}
pub fn clear(&mut self) {
self.name = Input::default();
self.host = Input::default().with_value("localhost".into());
self.backend_type = BackendType::Redis;
self.port = Input::default().with_value("6379".into());
self.password = Input::default();
self.database = Input::default().with_value("0".into());
self.active_field = FormField::BackendType;
}
}
impl Default for ConnectionForm {
fn default() -> Self {
Self::new()
}
}
pub fn render_connection_form(f: &mut Frame, form: &ConnectionForm, error: Option<&str>) {
let area = theme::centered_rect(70, 70, f.area());
let show_database = matches!(form.backend_type, BackendType::Redis);
let mut constraints = vec![
Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), ];
if show_database {
constraints.push(Constraint::Length(3)); }
constraints.push(Constraint::Min(2)); constraints.push(Constraint::Length(2));
let block = raw::modal_block(format!("New {} Connection", form.backend_type));
let inner = block.inner(area);
f.render_widget(Clear, area);
f.render_widget(block, area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(inner);
let mut chunk_idx = 0;
let title = Paragraph::new(format!("Add New {} Connection", form.backend_type))
.style(raw::form_title())
.alignment(Alignment::Center);
let backends = [
(BackendType::Redis, "Redis"),
(BackendType::Memcached, "Memcached"),
(BackendType::Etcd, "etcd"),
];
let is_backend_active = form.active_field == FormField::BackendType;
let backend_spans: Vec<Span> = backends
.iter()
.enumerate()
.flat_map(|(i, (backend, label))| {
let is_selected = *backend == form.backend_type;
let style = if is_selected {
raw::selector_option_selected(is_backend_active)
} else {
raw::selector_option_unselected(is_backend_active)
};
let mut spans = vec![Span::styled(format!(" {} ", label), style)];
if i < backends.len() - 1 {
spans.push(Span::raw(" "));
}
spans
})
.collect();
let backend_type_field = Paragraph::new(Line::from(backend_spans))
.block(raw::input_block("Backend Type (←/→)", is_backend_active));
let name_scroll = form
.name
.visual_scroll((chunks[chunk_idx].width.max(2) - 2) as usize);
let name_field = Paragraph::new(form.name.value())
.scroll((0, name_scroll as u16))
.style(raw::input_text())
.block(raw::input_block(
"Name (required)",
form.active_field == FormField::Name,
));
let host_scroll = form
.host
.visual_scroll((chunks[chunk_idx].width.max(2) - 2) as usize);
let host_field = Paragraph::new(form.host.value())
.scroll((0, host_scroll as u16))
.style(raw::input_text())
.block(raw::input_block(
"Host",
form.active_field == FormField::Host,
));
let port_scroll = form
.port
.visual_scroll((chunks[chunk_idx].width.max(2) - 2) as usize);
let port_field = Paragraph::new(form.port.value())
.scroll((0, port_scroll as u16))
.style(raw::input_text())
.block(raw::input_block(
"Port",
form.active_field == FormField::Port,
));
let password_val = form.password.value();
let password_display = if password_val.is_empty() {
String::new()
} else {
"*".repeat(password_val.len())
};
let password_field = Paragraph::new(password_display)
.style(raw::input_text())
.block(raw::input_block(
"Password (optional)",
form.active_field == FormField::Password,
));
let database_scroll = form
.database
.visual_scroll((chunks[chunk_idx].width.max(2) - 2) as usize);
let database_field = Paragraph::new(form.database.value())
.scroll((0, database_scroll as u16))
.style(raw::input_text())
.block(raw::input_block(
"Database",
form.active_field == FormField::Database,
));
let mut instructions = vec![Line::from("")];
if matches!(form.backend_type, BackendType::Memcached) {
instructions.push(Line::from(vec![Span::styled(
"Note: Memcached doesn't use database field",
raw::form_note(),
)]));
} else if matches!(form.backend_type, BackendType::Etcd) {
instructions.push(Line::from(vec![Span::styled(
"Note: etcd doesn't use database field",
raw::form_note(),
)]));
}
instructions.push(Line::from(vec![
Span::styled("Tab/↓", raw::keybind_key_style()),
Span::styled(" Next ", raw::form_hint()),
Span::styled("Shift+Tab/↑", raw::keybind_key_style()),
Span::styled(" Prev ", raw::form_hint()),
Span::styled("Enter", raw::keybind_key_style()),
Span::styled(" Save ", raw::form_hint()),
Span::styled("Esc", raw::keybind_key_style()),
Span::styled(" Cancel", raw::form_hint()),
]));
let instructions_widget = Paragraph::new(instructions)
.alignment(Alignment::Center)
.style(raw::form_hint());
f.render_widget(title, chunks[chunk_idx]);
chunk_idx += 1;
f.render_widget(backend_type_field, chunks[chunk_idx]);
chunk_idx += 1;
f.render_widget(name_field, chunks[chunk_idx]);
chunk_idx += 1;
f.render_widget(host_field, chunks[chunk_idx]);
chunk_idx += 1;
f.render_widget(port_field, chunks[chunk_idx]);
chunk_idx += 1;
f.render_widget(password_field, chunks[chunk_idx]);
chunk_idx += 1;
if show_database {
f.render_widget(database_field, chunks[chunk_idx]);
chunk_idx += 1;
}
f.render_widget(instructions_widget, chunks[chunk_idx]);
chunk_idx += 1;
if let Some(err) = error {
let error_widget = Paragraph::new(err)
.style(raw::form_error())
.alignment(Alignment::Center);
f.render_widget(error_widget, chunks[chunk_idx]);
}
match form.active_field {
FormField::Name => {
let cursor_x =
chunks[2].x + 1 + (form.name.visual_cursor().saturating_sub(name_scroll) as u16);
let cursor_y = chunks[2].y + 1;
f.set_cursor_position((cursor_x, cursor_y));
}
FormField::Host => {
let cursor_x =
chunks[3].x + 1 + (form.host.visual_cursor().saturating_sub(host_scroll) as u16);
let cursor_y = chunks[3].y + 1;
f.set_cursor_position((cursor_x, cursor_y));
}
FormField::Port => {
let cursor_x =
chunks[4].x + 1 + (form.port.visual_cursor().saturating_sub(port_scroll) as u16);
let cursor_y = chunks[4].y + 1;
f.set_cursor_position((cursor_x, cursor_y));
}
FormField::Password => {
let cursor_x = chunks[5].x + 1 + (form.password.value().len() as u16);
let cursor_y = chunks[5].y + 1;
f.set_cursor_position((cursor_x, cursor_y));
}
FormField::Database if show_database => {
let cursor_x = chunks[6].x
+ 1
+ (form
.database
.visual_cursor()
.saturating_sub(database_scroll) as u16);
let cursor_y = chunks[6].y + 1;
f.set_cursor_position((cursor_x, cursor_y));
}
_ => {}
}
}