trigger dropdown, not working at all, needs proper implementation, ready for debug

This commit is contained in:
filipriec
2025-04-11 15:40:50 +02:00
parent cf1aa4fd2a
commit a7389db674
7 changed files with 260 additions and 26 deletions

1
Cargo.lock generated
View File

@@ -428,6 +428,7 @@ dependencies = [
"crossterm", "crossterm",
"dirs 6.0.0", "dirs 6.0.0",
"dotenvy", "dotenvy",
"lazy_static",
"prost", "prost",
"ratatui", "ratatui",
"serde", "serde",

View File

@@ -11,6 +11,7 @@ common = { path = "../common" }
crossterm = "0.28.1" crossterm = "0.28.1"
dirs = "6.0.0" dirs = "6.0.0"
dotenvy = "0.15.7" dotenvy = "0.15.7"
lazy_static = "1.5.0"
prost = "0.13.5" prost = "0.13.5"
ratatui = "0.29.0" ratatui = "0.29.0"
serde = { version = "1.0.218", features = ["derive"] } serde = { version = "1.0.218", features = ["derive"] }

View File

@@ -3,13 +3,14 @@
use crate::{ use crate::{
config::colors::themes::Theme, config::colors::themes::Theme,
state::pages::auth::RegisterState, // Use RegisterState state::pages::auth::RegisterState, // Use RegisterState
components::common::dialog, components::common::{dialog, autocomplete},
state::state::AppState, state::state::AppState,
state::canvas_state::CanvasState,
}; };
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color}, style::{Style, Modifier, Color},
widgets::{Block, BorderType, Borders, Paragraph}, widgets::{Block, BorderType, Borders, Paragraph, Wrap},
Frame, Frame,
}; };
@@ -45,29 +46,69 @@ pub fn render_register(
]) ])
.split(inner_area); .split(inner_area);
// --- FORM RENDERING --- // --- FORM RENDERING (Manual) ---
crate::components::handlers::canvas::render_canvas( let form_area = chunks[0];
f, let field_labels = [
chunks[0], "Username",
state, // Pass RegisterState "Email (Optional)",
&[ // Update field labels "Password (Optional)",
"Username", "Confirm Password",
"Email (Optional)", "Role (Optional)",
"Password (Optional)", ];
"Confirm Password", let num_fields = field_labels.len();
"Role (Optional)",
], // Layout for labels and inputs within the form area
&state.current_field, let form_layout = Layout::default()
&[ // Update values from RegisterState .direction(Direction::Horizontal)
&state.username, .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
&state.email, .split(form_area);
&state.password,
&state.password_confirmation, let label_area = form_layout[0];
&state.role, let input_area = form_layout[1];
],
theme, // Calculate vertical layout for input rows
is_edit_mode, let input_rows = Layout::default()
); .direction(Direction::Vertical)
.constraints(vec![Constraint::Length(1); num_fields])
.split(input_area);
let mut role_input_rect = Rect::default(); // Store role input rect for dropdown positioning
// Render labels and inputs row by row
for i in 0..num_fields {
let is_active_field = state.current_field() == i;
// Render Label
let label = Paragraph::new(format!("{}:", field_labels[i]))
.style(Style::default().fg(theme.fg))
.alignment(Alignment::Right);
let label_rect = Rect {
x: label_area.x,
y: input_rows[i].y,
width: label_area.width.saturating_sub(1),
height: 1,
};
f.render_widget(label, label_rect);
// Render Input
let input_value = state.inputs()[i]; // Get value using CanvasState trait
let input_widget = Paragraph::new(input_value.as_str())
.style(if is_active_field {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.fg)
});
f.render_widget(input_widget, input_rows[i]);
if i == 4 { // Store the role input field's Rect
role_input_rect = input_rows[i];
}
// Set cursor for the active field
if is_active_field && is_edit_mode {
f.set_cursor(input_rows[i].x + state.current_cursor_pos() as u16, input_rows[i].y);
}
}
// --- ERROR MESSAGE --- // --- ERROR MESSAGE ---
if let Some(err) = &state.error_message { if let Some(err) = &state.error_message {
@@ -151,5 +192,32 @@ pub fn render_register(
app_state.ui.dialog.dialog_active_button_index, app_state.ui.dialog.dialog_active_button_index,
); );
} }
}
// --- AUTOCOMPLETE DROPDOWN RENDERING ---
if state.show_role_suggestions && !state.role_suggestions.is_empty() {
// Calculate dropdown area below the role input field
let dropdown_height = (state.role_suggestions.len() as u16).min(5) + 2; // Max 5 suggestions + border
let dropdown_area = Rect {
x: role_input_rect.x,
y: role_input_rect.y + 1, // Position below the input line
width: role_input_rect.width.max(20), // Ensure minimum width
height: dropdown_height,
};
// Ensure dropdown doesn't go off screen (simple vertical check)
let screen_height = f.size().height;
let clamped_dropdown_area = if dropdown_area.bottom() > screen_height {
Rect::new(dropdown_area.x, dropdown_area.y.saturating_sub(dropdown_height + 1), dropdown_area.width, dropdown_area.height)
} else {
dropdown_area
};
autocomplete::render_autocomplete_dropdown(
f,
clamped_dropdown_area,
theme,
&state.role_suggestions,
state.selected_suggestion_index,
);
}
}

View File

@@ -3,8 +3,10 @@ pub mod command_line;
pub mod status_line; pub mod status_line;
pub mod background; pub mod background;
pub mod dialog; pub mod dialog;
pub mod autocomplete;
pub use command_line::*; pub use command_line::*;
pub use status_line::*; pub use status_line::*;
pub use background::*; pub use background::*;
pub use dialog::*; pub use dialog::*;
pub use autocomplete::*;

View File

@@ -0,0 +1,50 @@
// src/components/common/autocomplete.rs
use crate::config::colors::themes::Theme;
use ratatui::{
layout::Rect,
style::{Modifier, Style},
widgets::{Block, Borders, List, ListItem, ListState},
Frame,
};
/// Renders a bordered list dropdown for autocomplete suggestions.
pub fn render_autocomplete_dropdown(
f: &mut Frame,
area: Rect, // The area where the dropdown should be rendered
theme: &Theme,
suggestions: &[String],
selected_index: Option<usize>,
) {
if suggestions.is_empty() {
return; // Don't render if no suggestions
}
let items: Vec<ListItem> = suggestions
.iter()
.map(|s| ListItem::new(s.as_str()))
.collect();
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(ratatui::widgets::BorderType::Plain)
.border_style(Style::default().fg(theme.accent)) // Highlight border
.style(Style::default().bg(theme.bg).fg(theme.fg)),
)
.highlight_style(
Style::default()
.add_modifier(Modifier::BOLD)
.bg(theme.highlight) // Highlight background for selected item
.fg(theme.bg), // Text color for selected item
)
.highlight_symbol("> "); // Symbol for selected item
// Create a state for the list to handle selection highlighting
let mut list_state = ListState::default();
list_state.select(selected_index);
f.render_stateful_widget(list, area, &mut list_state);
}

View File

@@ -3,6 +3,7 @@
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::pages::{auth::{AuthState, RegisterState}}; use crate::state::pages::{auth::{AuthState, RegisterState}};
use crate::state::canvas_state::CanvasState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::functions::modes::edit::{auth_e, form_e}; use crate::functions::modes::edit::{auth_e, form_e};
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
@@ -79,6 +80,46 @@ pub async fn handle_edit_event(
// Edit-specific actions // Edit-specific actions
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
// --- Autocomplete Handling for Role Field ---
if app_state.ui.show_register && register_state.current_field() == 4 {
match action {
"suggestion_down" if register_state.show_role_suggestions => {
let max_index = register_state.role_suggestions.len() - 1;
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index >= max_index { 0 } else { current_index + 1 });
return Ok("Suggestion changed".to_string());
}
"suggestion_up" if register_state.show_role_suggestions => {
let max_index = register_state.role_suggestions.len() - 1;
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index == 0 { max_index } else { current_index - 1 });
return Ok("Suggestion changed".to_string());
}
"select_suggestion" if register_state.show_role_suggestions => {
if let Some(selected_index) = register_state.selected_suggestion_index {
if let Some(selected_role) = register_state.role_suggestions.get(selected_index) {
register_state.role = selected_role.clone();
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
register_state.role_suggestions.clear();
// Optionally move to next field or exit edit mode here
return Ok(format!("Selected role: {}", register_state.role));
}
}
return Ok("No suggestion selected".to_string());
}
"hide_suggestions" => {
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
return Ok("Suggestions hidden".to_string());
}
// Let other edit actions (like move_*) fall through for the role field if desired
// Or explicitly handle them here if they should behave differently
_ => {}
}
}
// --- End Autocomplete Handling ---
return if app_state.ui.show_login { return if app_state.ui.show_login {
auth_e::execute_edit_action( auth_e::execute_edit_action(
action, action,
@@ -114,6 +155,11 @@ pub async fn handle_edit_event(
// Character insertion // Character insertion
if let KeyCode::Char(_) = key.code { if let KeyCode::Char(_) = key.code {
// --- Autocomplete Trigger on Char Insert ---
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
let result = // Store result before potential update
// --- End Autocomplete Trigger ---
return if app_state.ui.show_login { return if app_state.ui.show_login {
auth_e::execute_edit_action( auth_e::execute_edit_action(
"insert_char", "insert_char",
@@ -145,6 +191,39 @@ pub async fn handle_edit_event(
total_count total_count
).await ).await
}; };
// After character insertion/deletion, update suggestions if it was the role field
if is_role_field {
register_state.update_role_suggestions();
}
return result; // Return the result from execute_edit_action
}
// Handle Backspace/Delete for Autocomplete Trigger
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
// Execute the action first
let result = if app_state.ui.show_register {
auth_e::execute_edit_action(
action_str,
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else {
// Handle for login/form if needed, assuming auth_e covers RegisterState
Ok("Action not applicable here".to_string()) // Placeholder
}?;
if is_role_field {
register_state.update_role_suggestions();
}
return Ok(result);
} }
Ok(command_message.clone()) Ok(command_message.clone())

View File

@@ -1,5 +1,13 @@
// src/state/pages/auth.rs // src/state/pages/auth.rs
use crate::state::canvas_state::CanvasState; use crate::state::canvas_state::CanvasState;
use lazy_static::lazy_static;
lazy_static! {
pub static ref AVAILABLE_ROLES: Vec<String> = vec![
"accountant".to_string(),
"admin".to_string(),
];
}
#[derive(Default)] #[derive(Default)]
pub struct AuthState { pub struct AuthState {
@@ -26,6 +34,9 @@ pub struct RegisterState {
pub current_field: usize, pub current_field: usize,
pub current_cursor_pos: usize, pub current_cursor_pos: usize,
pub has_unsaved_changes: bool, pub has_unsaved_changes: bool,
pub show_role_suggestions: bool,
pub role_suggestions: Vec<String>,
pub selected_suggestion_index: Option<usize>,
} }
impl AuthState { impl AuthState {
@@ -57,10 +68,32 @@ impl RegisterState {
current_field: 0, current_field: 0,
current_cursor_pos: 0, current_cursor_pos: 0,
has_unsaved_changes: false, has_unsaved_changes: false,
show_role_suggestions: false,
role_suggestions: Vec::new(),
selected_suggestion_index: None,
}
}
/// Updates role suggestions based on current input.
pub fn update_role_suggestions(&mut self) {
let current_input = self.role.to_lowercase();
if current_input.is_empty() {
self.role_suggestions = Vec::new(); // Or show all? For now, clear.
self.show_role_suggestions = false;
self.selected_suggestion_index = None;
} else {
self.role_suggestions = AVAILABLE_ROLES
.iter()
.filter(|r| r.to_lowercase().starts_with(&current_input))
.cloned()
.collect();
self.show_role_suggestions = !self.role_suggestions.is_empty();
self.selected_suggestion_index = if self.show_role_suggestions { Some(0) } else { None }; // Default to first suggestion selected
} }
} }
} }
impl CanvasState for AuthState { impl CanvasState for AuthState {
fn current_field(&self) -> usize { fn current_field(&self) -> usize {
self.current_field self.current_field