Compare commits

..

20 Commits

Author SHA1 Message Date
filipriec
d577ff6715 edit mode is like a readonly mode 2025-03-31 23:56:58 +02:00
filipriec
ca75c90ee9 changed read_only mode also 2025-03-31 23:37:02 +02:00
filipriec
8e0fae26ee we compiled 2025-03-31 22:08:39 +02:00
filipriec
bee95c3755 fixes, still 2 errors remaining 2025-03-31 20:10:53 +02:00
filipriec
306f4de14f smart way, but introduced many errors 2025-03-31 17:55:53 +02:00
filipriec
b2fc681e73 cargo fix 2025-03-31 17:16:10 +02:00
filipriec
060cff3f0f compiled 2025-03-31 17:10:51 +02:00
filipriec
07c48985e4 proper pass of the arguments 2025-03-31 16:25:11 +02:00
filipriec
3d266c2ad0 switching of the views done 2025-03-31 16:23:25 +02:00
filipriec
e2c326bf1e login gRPC 2025-03-31 16:16:07 +02:00
filipriec
7f5b671084 switch between login or form in the save request 2025-03-31 15:55:54 +02:00
filipriec
3ccf71ed0f switcher, have bugs 2025-03-31 15:42:48 +02:00
filipriec
efb59c5571 split config in modes/canvas is fixed and working properly well 2025-03-31 15:12:50 +02:00
filipriec
26cf06df14 needs fixes of the errors 2025-03-31 14:58:10 +02:00
filipriec
c82b62f72b moving modes/canvas/common.rs into the functions 2025-03-31 13:22:08 +02:00
filipriec
87cdb8048d we compiled fully, time to move grpc calls now 2025-03-31 12:07:01 +02:00
filipriec
f71498703a implementation of login 2025-03-31 10:40:34 +02:00
filipriec
94eea47b76 cargo fix 2025-03-31 10:24:20 +02:00
filipriec
ac833294c4 moved login from grpc_client 2025-03-31 10:23:23 +02:00
filipriec
81f0527085 ui.rs gRPC code removed 2025-03-31 09:54:16 +02:00
27 changed files with 964 additions and 623 deletions

View File

@@ -10,8 +10,7 @@ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color}, // Removed unused Color import
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
text::Line, // Removed unused Span import
Frame, // Removed unused Span import
};
pub fn render_login(

View File

@@ -1,7 +1,7 @@
// src/components/common/dialog.rs
use ratatui::{
layout::{Constraint, Direction, Layout, Rect, Margin},
style::{Color, Modifier, Style},
style::{Modifier, Style},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
text::{Text, Line, Span}

View File

@@ -9,7 +9,6 @@ use crate::config::colors::themes::Theme;
use crate::state::canvas_state::CanvasState;
use crate::components::handlers::canvas::render_canvas;
// Original form renderer (keep for backward compatibility)
pub fn render_form(
f: &mut Frame,
area: Rect,

View File

@@ -1,18 +1,21 @@
// src/modes/canvas/common.rs
use crate::config::binds::config::Config;
use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::form::FormState;
use crate::state::pages::{form::FormState, auth::AuthState};
use crate::state::state::AppState;
use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::tui::functions::common::{
form::{save as form_save, revert as form_revert},
login::{save as login_save, revert as login_revert}
};
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
/// Main handler for common core actions
pub async fn handle_core_action(
action: &str,
form_state: &mut FormState,
auth_state: &mut AuthState,
grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient,
terminal: &mut TerminalCore,
app_state: &mut AppState,
current_position: &mut u64,
@@ -20,160 +23,53 @@ pub async fn handle_core_action(
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"save" => {
let message = save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
Ok((false, message))
if app_state.ui.show_login {
let message = login_save(auth_state, auth_client, app_state).await?;
Ok((false, message))
} else {
let message = form_save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
Ok((false, message))
}
},
"force_quit" => {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".to_string()))
},
"save_and_quit" => {
let message = save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
let message = if app_state.ui.show_login {
login_save(auth_state, auth_client, app_state).await?
} else {
form_save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?
};
terminal.cleanup()?;
Ok((true, format!("{}. Exiting application.", message)))
},
"revert" => {
let message = revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
Ok((false, message))
if app_state.ui.show_login {
let message = login_revert(auth_state, app_state).await;
Ok((false, message))
} else {
let message = form_revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
Ok((false, message))
}
},
// We should never hit this case with proper filtering
_ => Ok((false, format!("Core action not handled: {}", action))),
}
}
/// Helper function to check if a key event should trigger a core action
pub fn is_core_action(config: &Config, key_code: crossterm::event::KeyCode, modifiers: crossterm::event::KeyModifiers) -> Option<String> {
// Check for core application actions (save, quit, etc.)
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" | "force_quit" | "save_and_quit" | "revert" => {
return Some(action.to_string())
},
_ => {} // Other actions are handled by their respective mode handlers
}
}
None
}
/// Shared logic for saving the current form state
pub async fn save(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
let message = if is_new {
let post_request = PostAdresarRequest {
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let response = grpc_client.post_adresar(post_request).await?;
let new_total = grpc_client.get_adresar_count().await?;
*current_position = new_total;
form_state.id = response.into_inner().id;
"New entry created".to_string()
} else {
let put_request = PutAdresarRequest {
id: form_state.id,
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let _ = grpc_client.put_adresar(put_request).await?;
"Entry updated".to_string()
};
*is_saved = true;
form_state.has_unsaved_changes = false;
Ok(message)
}
/// Discard changes since last save
pub async fn revert(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
if is_new {
// Clear all fields for new entries
form_state.values.iter_mut().for_each(|v| *v = String::new());
form_state.has_unsaved_changes = false;
return Ok("New entry cleared".to_string());
}
let data = grpc_client.get_adresar_by_position(*current_position).await?;
// Update form fields with saved values
form_state.values = vec![
data.firma,
data.kz,
data.drc,
data.ulica,
data.psc,
data.mesto,
data.stat,
data.banka,
data.ucet,
data.skladm,
data.ico,
data.kontakt,
data.telefon,
data.skladu,
data.fax,
];
form_state.has_unsaved_changes = false;
Ok("Changes discarded, reloaded last saved version".to_string())
}

View File

@@ -1,17 +1,19 @@
// src/modes/canvas/edit.rs
// TODO THIS is freaking bloated with functions it never uses REFACTOR 200 LOC can be gone
use std::any::Any;
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::config::binds::config::Config;
use crate::state::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::modes::canvas::common;
use crate::services::grpc_client::GrpcClient;
use crate::tui::functions::common::form::{save, revert};
pub async fn handle_edit_event_internal(
pub async fn handle_edit_event_internal<S: CanvasState + Any>(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
state: &mut S,
ideal_cursor_column: &mut usize,
command_message: &mut String,
is_saved: &mut bool,
@@ -20,16 +22,14 @@ pub async fn handle_edit_event_internal(
grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> {
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(&config.keybindings.global, key.code, key.modifiers) {
// Ignore in edit mode and process as normal input
handle_edit_specific_input(key, form_state, ideal_cursor_column);
handle_edit_specific_input(key, state, ideal_cursor_column);
return Ok(command_message.clone());
}
// Check common actions first
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.common, key.code, key.modifiers) {
return execute_common_action(
action,
form_state,
state,
grpc_client,
is_saved,
current_position,
@@ -40,302 +40,340 @@ pub async fn handle_edit_event_internal(
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
return execute_edit_action(
action,
form_state,
state,
ideal_cursor_column,
grpc_client, // Changed from AppTerminal
grpc_client,
is_saved,
current_position,
total_count,
).await;
}
handle_edit_specific_input(
key,
form_state,
ideal_cursor_column,
);
handle_edit_specific_input(key, state, ideal_cursor_column);
Ok(command_message.clone())
}
async fn execute_common_action(
async fn execute_common_action<S: CanvasState + Any>(
action: &str,
form_state: &mut FormState,
state: &mut S,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client,
is_saved,
current_position,
total_count,
).await
},
"revert" => {
common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await
},
"save" | "revert" if state.has_unsaved_changes() => {
if let Some(form_state) = (state as &mut dyn Any).downcast_mut::<FormState>() {
return match action {
"save" => save(form_state, grpc_client, is_saved, current_position, total_count).await,
"revert" => revert(form_state, grpc_client, current_position, total_count).await,
_ => unreachable!(),
};
}
Ok("Action not available in this context".to_string())
}
"move_up" | "move_down" => {
// Reuse edit mode's existing logic
execute_edit_action(
action,
form_state,
&mut 0, // Dummy ideal_cursor_column (not used here)
state,
&mut 0,
grpc_client,
is_saved,
current_position,
total_count,
).await
},
}
_ => Ok(format!("Common action not handled: {}", action)),
}
}
fn handle_edit_specific_input(
fn handle_edit_specific_input<S: CanvasState>( // No Any needed here
key: KeyEvent,
form_state: &mut FormState,
state: &mut S,
ideal_cursor_column: &mut usize,
) {
match key.code {
KeyCode::Char(c) => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos + 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
// Use trait setters
state.set_current_cursor_pos(cursor_pos + 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos(); // Update ideal column
}
}
KeyCode::Backspace => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
// Use trait setters
state.set_current_cursor_pos(cursor_pos - 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos(); // Update ideal column
}
}
}
KeyCode::Delete => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
// Use trait setter
state.set_has_unsaved_changes(true);
// Cursor position doesn't change, but ideal might if text changed
*ideal_cursor_column = state.current_cursor_pos();
}
}
KeyCode::Tab => {
if key.modifiers.contains(KeyModifiers::SHIFT) {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
let num_fields = state.fields().len();
if num_fields > 0 { // Avoid panic on empty fields
let current_field = state.current_field();
let new_field = if key.modifiers.contains(KeyModifiers::SHIFT) {
if current_field == 0 { num_fields - 1 } else { current_field - 1 }
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
} else {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
(current_field + 1) % num_fields
};
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_cursor_pos));
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
KeyCode::Enter => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
let num_fields = state.fields().len();
if num_fields > 0 { // Avoid panic on empty fields
let new_field = (state.current_field() + 1) % num_fields;
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_cursor_pos));
}
}
_ => {}
}
}
async fn execute_edit_action(
async fn execute_edit_action<S: CanvasState>( // No Any needed here
action: &str,
form_state: &mut FormState,
state: &mut S,
ideal_cursor_column: &mut usize,
grpc_client: &mut GrpcClient, // Changed from AppTerminal
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
// These parameters are unused if save/revert aren't handled here,
// but keep them for now if execute_common_action calls this
_grpc_client: &mut GrpcClient,
_is_saved: &mut bool,
_current_position: &mut u64,
_total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client, // Changed from AppTerminal
is_saved,
current_position,
total_count,
).await
},
"move_left" => {
form_state.current_cursor_pos = form_state.current_cursor_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = state.current_cursor_pos().saturating_sub(1);
// Use trait setter
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
if form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
// Allow moving cursor to position *after* last character
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
// Use trait setter
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_up" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = if current_field == 0 { num_fields - 1 } else { current_field - 1 };
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_down" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.current_field() + 1) % num_fields;
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
// Use trait setter
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
form_state.current_cursor_pos = current_input.len();
*ideal_cursor_column = form_state.current_cursor_pos;
let current_input = state.get_current_input();
let new_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_first_line" => {
form_state.current_field = 0;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
let num_fields = state.fields().len();
if num_fields > 0 {
// Use trait setter
state.set_current_field(0);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("Moved to first line".to_string())
}
"move_last_line" => {
form_state.current_field = form_state.fields.len() - 1;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = num_fields - 1;
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("Moved to last line".to_string())
}
// Word movement actions
"move_word_next" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len());
// Use trait setter
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_word_end(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len());
// Use trait setter
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
// Use trait setter
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
// Use trait setter
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
Ok("Moved to previous word end".to_string())
}
// Edit-specific actions that can be bound to keys
"delete_char_forward" => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect(); // Use mut for modification
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
chars.remove(cursor_pos);
*field_value = chars.into_iter().collect();
// Use trait setter
state.set_has_unsaved_changes(true);
// Cursor position doesn't change
*ideal_cursor_column = cursor_pos;
}
Ok("".to_string())
}
"delete_char_backward" => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect(); // Use mut
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
let new_pos = cursor_pos - 1;
// Use trait setters
state.set_current_cursor_pos(new_pos);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = new_pos;
}
}
Ok("".to_string())
}
"insert_char" => {
// This could be expanded to allow configurable character insertion
// For now, it's a placeholder that would need additional parameters
Ok("Character insertion requires configuration".to_string())
// This action doesn't make sense here as char insertion is handled
// directly in handle_edit_specific_input
Ok("Character insertion handled directly".to_string())
}
"next_field" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.current_field() + 1) % num_fields;
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"prev_field" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = if current_field == 0 { num_fields - 1 } else { current_field - 1 };
// Use trait setter
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
// Use trait setter
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
// Fallback for unrecognized actions
_ => Ok(format!("Unknown action: {}", action)),
_ => Ok(format!("Unknown edit action: {}", action)),
}
}
// Reuse these character and word navigation helper functions
#[derive(PartialEq)]
enum CharType {
Whitespace,

View File

@@ -1,12 +1,12 @@
// src/modes/canvas/read_only.rs
use crossterm::event::{KeyEvent};
use crate::config::binds::config::Config;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
use crate::services::grpc_client::GrpcClient;
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; // Import the trait
use crate::state::pages::auth::AuthState;
use crate::state::pages::form::FormState;
use crossterm::event::KeyEvent;
#[derive(PartialEq)]
enum CharType {
@@ -19,12 +19,12 @@ pub async fn handle_read_only_event(
app_state: &crate::state::state::AppState,
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
auth_state: &mut AuthState,
form_state: &mut FormState, // Keep specific types here for routing
auth_state: &mut AuthState, // Keep specific types here for routing
key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
current_position: &mut u64, // Needed for form actions
total_count: u64, // Needed for form actions
grpc_client: &mut GrpcClient, // Needed for form actions
command_message: &mut String,
edit_mode_cooldown: &mut bool,
ideal_cursor_column: &mut usize,
@@ -33,17 +33,37 @@ pub async fn handle_read_only_event(
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode".to_string();
// The actual mode switch happens in event.rs based on this return
return Ok((false, command_message.clone()));
}
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
// Use the correct state based on context
let (current_input, current_pos) = if app_state.ui.show_login {
(
auth_state.get_current_input(),
auth_state.current_cursor_pos(),
)
} else {
(
form_state.get_current_input(),
form_state.current_cursor_pos(),
)
};
if !current_input.is_empty() && current_pos < current_input.len() {
// Update the correct state
if app_state.ui.show_login {
auth_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = auth_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = form_state.current_cursor_pos();
}
}
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode (after cursor)".to_string();
// The actual mode switch happens in event.rs based on this return
return Ok((false, command_message.clone()));
}
@@ -53,9 +73,13 @@ pub async fn handle_read_only_event(
let sequence = key_sequence_tracker.get_sequence();
// Try to match the current sequence against Read-Only mode bindings
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
let result = if (action == "previous_entry" || action == "next_entry" ||
action == "move_up" || action == "move_down") && app_state.ui.show_form {
if let Some(action) = config.matches_key_sequence_generalized(&sequence)
{
// Handle context-specific actions first
let result = if app_state.ui.show_form
&& (action == "previous_entry" || action == "next_entry")
{
// Form-specific navigation
crate::tui::functions::form::handle_action(
action,
form_state,
@@ -63,24 +87,52 @@ pub async fn handle_read_only_event(
current_position,
total_count,
ideal_cursor_column,
).await?
} else if (action == "move_up" || action == "move_down") && app_state.ui.show_login {
)
.await?
} else if app_state.ui.show_login
&& (action == "move_up" || action == "move_down")
{
// Login-specific field navigation
crate::tui::functions::login::handle_action(
action,
auth_state,
ideal_cursor_column,
).await?
} else {
execute_action(
)
.await?
} else if app_state.ui.show_form
&& (action == "move_up" || action == "move_down")
{
// Form-specific field navigation (can reuse login handler logic if identical)
crate::tui::functions::form::handle_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
grpc_client, // Might not be needed for simple up/down
current_position,
total_count,
grpc_client,
).await?
ideal_cursor_column,
)
.await?
} else {
// Handle common navigation actions generically
if app_state.ui.show_login {
execute_action(
action,
auth_state, // Pass AuthState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
execute_action(
action,
form_state, // Pass FormState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
}
};
key_sequence_tracker.reset();
return Ok((false, result));
@@ -93,8 +145,14 @@ pub async fn handle_read_only_event(
// Since it's not part of a multi-key sequence, check for a direct action
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if action == "previous_entry" && app_state.ui.show_form {
if let Some(action) =
config.get_read_only_action_for_key(key.code, key.modifiers)
{
// Handle context-specific actions first
let result = if app_state.ui.show_form
&& action == "previous_entry"
{
// Form-specific navigation
crate::tui::functions::form::handle_action(
action,
form_state,
@@ -102,18 +160,29 @@ pub async fn handle_read_only_event(
current_position,
total_count,
ideal_cursor_column,
).await?
)
.await?
} else {
execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
current_position,
total_count,
grpc_client,
).await?
// Handle common navigation actions generically
if app_state.ui.show_login {
execute_action(
action,
auth_state, // Pass AuthState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
execute_action(
action,
form_state, // Pass FormState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
}
};
key_sequence_tracker.reset();
return Ok((false, result));
@@ -123,8 +192,14 @@ pub async fn handle_read_only_event(
// If modifiers are pressed, check for direct key bindings
key_sequence_tracker.reset();
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if action == "previous_entry" && app_state.ui.show_form {
if let Some(action) =
config.get_read_only_action_for_key(key.code, key.modifiers)
{
// Handle context-specific actions first
let result = if app_state.ui.show_form
&& action == "previous_entry"
{
// Form-specific navigation
crate::tui::functions::form::handle_action(
action,
form_state,
@@ -132,18 +207,29 @@ pub async fn handle_read_only_event(
current_position,
total_count,
ideal_cursor_column,
).await?
)
.await?
} else {
execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
current_position,
total_count,
grpc_client,
).await?
// Handle common navigation actions generically
if app_state.ui.show_login {
execute_action(
action,
auth_state, // Pass AuthState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
execute_action(
action,
form_state, // Pass FormState
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
}
};
return Ok((false, result));
}
@@ -152,7 +238,10 @@ pub async fn handle_read_only_event(
// Show a helpful message when no binding was found
if !*edit_mode_cooldown {
let default_key = "i".to_string();
let edit_key = config.keybindings.read_only.get("enter_edit_mode_before")
let edit_key = config
.keybindings
.read_only
.get("enter_edit_mode_before")
.and_then(|keys| keys.first())
.unwrap_or(&default_key);
*command_message = format!("Read-only mode - press {} to edit", edit_key);
@@ -161,133 +250,155 @@ pub async fn handle_read_only_event(
Ok((false, command_message.clone()))
}
async fn execute_action(
// Make this function generic over CanvasState
async fn execute_action<S: CanvasState>(
action: &str,
form_state: &mut FormState,
state: &mut S, // Use generic state
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
key_sequence_tracker: &mut KeySequenceTracker, // Keep for resetting
command_message: &mut String, // Keep for clearing
) -> Result<String, Box<dyn std::error::Error>> {
match action {
// These actions are handled outside now based on context
"previous_entry" | "next_entry" => {
// This will only be called when no component is active
key_sequence_tracker.reset();
Ok(format!("Navigation prev/next only available in form mode"))
Ok(format!(
"Action '{}' should be handled by context-specific logic",
action
))
}
// These actions are handled outside now based on context
"move_up" | "move_down" => {
// This will only be called when no component is active
key_sequence_tracker.reset();
Ok(format!("Navigation up/down only available in form mode"))
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
Ok(format!(
"Action '{}' should be handled by context-specific logic",
action
))
}
"exit_edit_mode" => {
// This action is primarily for Edit mode, but might be bound here too
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = form_state.current_cursor_pos;
form_state.current_cursor_pos = current_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
let current_pos = state.current_cursor_pos();
let new_pos = current_pos.saturating_sub(1);
state.set_current_cursor_pos(new_pos); // Use trait setter
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
let current_pos = form_state.current_cursor_pos;
if !current_input.is_empty() && current_pos < current_input.len() - 1 {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
// In read-only, cursor stops AT the last character, not after
if !current_input.is_empty()
&& current_pos < current_input.len().saturating_sub(1)
{
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos); // Use trait setter
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos =
find_next_word_start(current_input, state.current_cursor_pos());
// Clamp to last valid character index in read-only
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
state.set_current_cursor_pos(final_pos); // Use trait setter
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos =
find_word_end(current_input, state.current_cursor_pos());
// Clamp to last valid character index in read-only
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
state.set_current_cursor_pos(final_pos); // Use trait setter
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos); // Use trait setter
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos); // Use trait setter
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
state.set_current_cursor_pos(0); // Use trait setter
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
let current_input = state.get_current_input();
if !current_input.is_empty() {
form_state.current_cursor_pos = current_input.len() - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
let new_pos = current_input.len().saturating_sub(1);
state.set_current_cursor_pos(new_pos); // Use trait setter
*ideal_cursor_column = new_pos;
} else {
state.set_current_cursor_pos(0); // Handle empty input case
*ideal_cursor_column = 0;
}
Ok("".to_string())
}
"move_first_line" => {
// Change field first
form_state.current_field = 0;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
// Field change is handled outside based on context
// Just set cursor position based on ideal column
let current_input = state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
current_input.len().saturating_sub(1)
} else {
current_input.len()
0
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to first line".to_string())
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_cursor_pos),
);
Ok("Moved to first line".to_string()) // Message might be inaccurate now
}
"move_last_line" => {
// Change field first
form_state.current_field = form_state.fields.len() - 1;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
// Field change is handled outside based on context
// Just set cursor position based on ideal column
let current_input = state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
current_input.len().saturating_sub(1)
} else {
current_input.len()
0
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to last line".to_string())
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_cursor_pos),
);
Ok("Moved to last line".to_string()) // Message might be inaccurate now
}
_ => Ok(format!("Unknown action: {}", action)),
_ => Ok(format!("Unknown read-only action: {}", action)),
}
}
// Helper functions remain unchanged as they operate on &str
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
@@ -305,11 +416,18 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
}
let mut pos = current_pos;
// Handle edge case where current_pos might be out of bounds after edits
if pos >= chars.len() {
return chars.len();
}
let initial_type = get_char_type(chars[pos]);
// Move past characters of the same type
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
// Move past whitespace
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
@@ -317,36 +435,29 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
// Handle edge case where current_pos might be out of bounds
let mut pos = current_pos.min(chars.len().saturating_sub(1));
if current_pos >= chars.len() - 1 {
return chars.len() - 1;
}
let mut pos = current_pos;
// If starting on whitespace, move to the next non-whitespace
if get_char_type(chars[pos]) == CharType::Whitespace {
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == CharType::Whitespace {
pos += 1;
}
} else {
let current_type = get_char_type(chars[pos]);
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
pos += 1;
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
// If we are still on whitespace (meaning end of string or only whitespace left), return current pos
if pos + 1 >= chars.len() || get_char_type(chars[pos + 1]) == CharType::Whitespace {
return pos;
}
// Move to the start of the next word
pos += 1;
}
if pos >= chars.len() {
return chars.len() - 1;
}
// Now we are on a non-whitespace character
let word_type = get_char_type(chars[pos]);
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
pos += 1;
@@ -355,6 +466,7 @@ fn find_word_end(text: &str, current_pos: usize) -> usize {
pos
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
@@ -363,56 +475,64 @@ fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let mut pos = current_pos.saturating_sub(1);
// Move past whitespace
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
// Now on a non-whitespace or at the beginning
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
// Move to the beginning of the word
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
pos
// If pos is 0 and it's whitespace, keep it at 0. Otherwise, it's the start of the word.
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
0
} else {
pos
}
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 { // Need at least 2 chars to find a *previous* word end
return 0;
}
let mut pos = current_pos.saturating_sub(1);
let mut pos = current_pos.saturating_sub(1); // Start looking one char back
// Skip trailing whitespace from the current position
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 && get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos -= 1;
let prev_word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
pos -= 1;
}
while pos < chars.len() - 1 &&
get_char_type(chars[pos + 1]) == prev_word_type {
pos += 1;
}
}
// Now we are at the end of the word the cursor was in/after, or at the start
if pos == 0 {
return 0; // Reached the beginning
}
pos
// Skip the word itself
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
// Skip whitespace before that word
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
// Now pos is at the beginning of the word *or* the end of the *previous* word.
// If we moved back, pos-1 is the index we want.
if pos > 0 {
pos - 1
} else {
0 // We were at the first word
}
}

View File

@@ -4,11 +4,9 @@ use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use crate::tui::controls::commands::CommandHandler;
use crate::tui::functions::common::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore;
use crate::modes::{
canvas::{common},
};
use crate::tui::functions::common::form::{save, revert};
pub async fn handle_command_event(
key: KeyEvent,
@@ -97,7 +95,7 @@ async fn process_command(
Ok((should_exit, message, true))
},
"save" => {
let message = common::save(
let message = save(
form_state,
grpc_client,
&mut command_handler.is_saved,
@@ -108,7 +106,7 @@ async fn process_command(
return Ok((false, message, true));
},
"revert" => {
let message = common::revert(
let message = revert(
form_state,
grpc_client,
current_position,

View File

@@ -5,7 +5,8 @@ use crate::tui::terminal::{
core::TerminalCore,
};
use crate::services::grpc_client::GrpcClient;
use crate::tui::controls::commands::CommandHandler;
use crate::services::auth::AuthClient;
use crate::tui::functions::common::commands::CommandHandler;
use crate::config::binds::config::Config;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
@@ -27,11 +28,12 @@ pub struct EventHandler {
pub ideal_cursor_column: usize,
pub key_sequence_tracker: KeySequenceTracker,
pub auth_state: AuthState,
pub auth_client: AuthClient,
}
impl EventHandler {
pub fn new() -> Self {
EventHandler {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
Ok(EventHandler {
command_mode: false,
command_input: String::new(),
command_message: String::new(),
@@ -40,7 +42,8 @@ impl EventHandler {
ideal_cursor_column: 0,
key_sequence_tracker: KeySequenceTracker::new(800),
auth_state: AuthState::new(),
}
auth_client: AuthClient::new().await?,
})
}
pub async fn handle_event(
@@ -131,7 +134,9 @@ impl EventHandler {
return common::handle_core_action(
action,
form_state,
&mut self.auth_state,
grpc_client,
&mut self.auth_client,
terminal,
app_state,
current_position,
@@ -191,7 +196,9 @@ impl EventHandler {
return common::handle_core_action(
action,
form_state,
&mut self.auth_state,
grpc_client,
&mut self.auth_client,
terminal,
app_state,
current_position,
@@ -203,17 +210,31 @@ impl EventHandler {
}
// Let edit mode handle its own actions (including navigation from common bindings)
let result = edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?;
let result = if app_state.ui.show_login {
edit::handle_edit_event_internal(
key,
config,
&mut self.auth_state, // Use auth_state instead of form_state
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?
} else {
edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?
};
self.key_sequence_tracker.reset();
return Ok((false, result));

View File

@@ -1 +0,0 @@
// src/services/adresar.rs

View File

@@ -0,0 +1,23 @@
// src/services/auth.rs
use tonic::transport::Channel;
use common::proto::multieko2::auth::{
auth_service_client::AuthServiceClient,
LoginRequest, LoginResponse
};
pub struct AuthClient {
client: AuthServiceClient<Channel>,
}
impl AuthClient {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
let client = AuthServiceClient::connect("http://[::1]:50051").await?;
Ok(Self { client })
}
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(LoginRequest { identifier, password });
let response = self.client.login(request).await?.into_inner();
Ok(response)
}
}

View File

@@ -10,17 +10,12 @@ use common::proto::multieko2::table_definition::{
table_definition_client::TableDefinitionClient,
ProfileTreeResponse
};
use common::proto::multieko2::auth::{
auth_service_client::AuthServiceClient,
LoginRequest, LoginResponse
};
#[derive(Clone)]
pub struct GrpcClient {
adresar_client: AdresarClient<Channel>,
table_structure_client: TableStructureServiceClient<Channel>,
table_definition_client: TableDefinitionClient<Channel>,
auth_client: AuthServiceClient<Channel>,
}
impl GrpcClient {
@@ -28,13 +23,11 @@ impl GrpcClient {
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
let table_definition_client = TableDefinitionClient::connect("http://[::1]:50051").await?;
let auth_client = AuthServiceClient::connect("http://[::1]:50051").await?;
Ok(Self {
adresar_client,
table_structure_client,
table_definition_client,
auth_client,
})
}
@@ -73,10 +66,4 @@ impl GrpcClient {
let response = self.table_definition_client.get_profile_tree(request).await?;
Ok(response.into_inner())
}
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(LoginRequest { identifier, password });
let response = self.auth_client.login(request).await?.into_inner();
Ok(response)
}
}

View File

@@ -1,13 +1,9 @@
// services/mod.rs
pub mod grpc_client;
pub mod adresar;
pub mod table;
pub mod profile;
pub mod auth;
pub mod ui_service;
pub use grpc_client::*;
pub use adresar::*;
pub use table::*;
pub use profile::*;
pub use ui_service::*;
pub use auth::*;

View File

@@ -1 +0,0 @@
// src/services/profile.rs

View File

@@ -1 +0,0 @@
// src/services/table.rs

View File

@@ -0,0 +1,89 @@
// src/services/ui_service.rs
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use crate::state::state::AppState;
pub struct UiService;
impl UiService {
pub async fn initialize_app_state(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
// Fetch profile tree
let profile_tree = grpc_client.get_profile_tree().await?;
app_state.profile_tree = profile_tree;
// Fetch table structure
let table_structure = grpc_client.get_table_structure().await?;
// Extract the column names from the response
let column_names: Vec<String> = table_structure
.columns
.iter()
.map(|col| col.name.clone())
.collect();
Ok(column_names)
}
pub async fn initialize_adresar_count(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<(), Box<dyn std::error::Error>> {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
Ok(())
}
pub async fn update_adresar_count(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<(), Box<dyn std::error::Error>> {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
Ok(())
}
pub async fn load_adresar_by_position(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
form_state: &mut FormState,
position: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match grpc_client.get_adresar_by_position(position).await {
Ok(response) => {
// Set the ID properly
form_state.id = response.id;
// Update form values dynamically
form_state.values = vec![
response.firma,
response.kz,
response.drc,
response.ulica,
response.psc,
response.mesto,
response.stat,
response.banka,
response.ucet,
response.skladm,
response.ico,
response.kontakt,
response.telefon,
response.skladu,
response.fax,
];
form_state.has_unsaved_changes = false;
Ok(format!("Loaded entry {}", position))
}
Err(e) => {
Ok(format!("Error loading entry: {}", e))
}
}
}
}

View File

@@ -10,40 +10,8 @@ pub trait CanvasState {
fn get_current_input(&self) -> &str;
fn get_current_input_mut(&mut self) -> &mut String;
fn fields(&self) -> Vec<&str>;
}
// Implement for FormState (keep existing form.rs code and add this)
impl CanvasState for FormState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
self.current_cursor_pos
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
self.values.iter().collect()
}
fn get_current_input(&self) -> &str {
self.values
.get(self.current_field)
.map(|s| s.as_str())
.unwrap_or("")
}
fn get_current_input_mut(&mut self) -> &mut String {
self.values
.get_mut(self.current_field)
.expect("Invalid current_field index")
}
fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect()
}
fn set_current_field(&mut self, index: usize);
fn set_current_cursor_pos(&mut self, pos: usize);
fn set_has_unsaved_changes(&mut self, changed: bool);
}

View File

@@ -67,4 +67,21 @@ impl CanvasState for AuthState {
fn fields(&self) -> Vec<&str> {
vec!["Username/Email", "Password"]
}
// --- Implement the setter methods ---
fn set_current_field(&mut self, index: usize) {
// AuthState only has 2 fields (0 and 1)
if index < 2 {
self.current_field = index;
}
}
fn set_current_cursor_pos(&mut self, pos: usize) {
// Optional: Add validation based on current input length if needed
self.current_cursor_pos = pos;
}
fn set_has_unsaved_changes(&mut self, _changed: bool) {
// Auth form doesn't track unsaved changes, so do nothing
}
}

View File

@@ -2,6 +2,7 @@
use crate::config::colors::themes::Theme;
use ratatui::layout::Rect;
use ratatui::Frame;
use crate::state::canvas_state::CanvasState;
pub struct FormState {
pub id: i64,
@@ -82,3 +83,54 @@ impl FormState {
];
}
}
impl CanvasState for FormState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
self.current_cursor_pos
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
self.values.iter().collect()
}
fn get_current_input(&self) -> &str {
self.values
.get(self.current_field)
.map(|s| s.as_str())
.unwrap_or("")
}
fn get_current_input_mut(&mut self) -> &mut String {
self.values
.get_mut(self.current_field)
.expect("Invalid current_field index")
}
fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect()
}
// --- Implement the setter methods ---
fn set_current_field(&mut self, index: usize) {
if index < self.fields.len() { // Basic bounds check
self.current_field = index;
}
}
fn set_current_cursor_pos(&mut self, pos: usize) {
// Optional: Add validation based on current input length if needed
self.current_cursor_pos = pos;
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
}

View File

@@ -1,5 +0,0 @@
// src/tui/controls.rs
pub mod commands;
pub use commands::*;

View File

@@ -4,7 +4,9 @@ pub mod admin;
pub mod intro;
pub mod login;
pub mod form;
pub mod common;
pub use admin::*;
pub use intro::*;
pub use form::*;
pub use common::*;

View File

@@ -0,0 +1,8 @@
// src/tui/functions/common.rs
pub mod commands;
pub mod form;
pub mod login;
pub use commands::*;
pub use form::{revert as form_revert, save as form_save};
pub use login::{revert as login_revert, save as login_save};

View File

@@ -0,0 +1,107 @@
// src/tui/functions/common/form.rs
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
/// Shared logic for saving the current form state
pub async fn save(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
let message = if is_new {
let post_request = PostAdresarRequest {
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let response = grpc_client.post_adresar(post_request).await?;
let new_total = grpc_client.get_adresar_count().await?;
*current_position = new_total;
form_state.id = response.into_inner().id;
"New entry created".to_string()
} else {
let put_request = PutAdresarRequest {
id: form_state.id,
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let _ = grpc_client.put_adresar(put_request).await?;
"Entry updated".to_string()
};
*is_saved = true;
form_state.has_unsaved_changes = false;
Ok(message)
}
/// Discard changes since last save
pub async fn revert(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
if is_new {
// Clear all fields for new entries
form_state.values.iter_mut().for_each(|v| *v = String::new());
form_state.has_unsaved_changes = false;
return Ok("New entry cleared".to_string());
}
let data = grpc_client.get_adresar_by_position(*current_position).await?;
// Update form fields with saved values
form_state.values = vec![
data.firma,
data.kz,
data.drc,
data.ulica,
data.psc,
data.mesto,
data.stat,
data.banka,
data.ucet,
data.skladm,
data.ico,
data.kontakt,
data.telefon,
data.skladu,
data.fax,
];
form_state.has_unsaved_changes = false;
Ok("Changes discarded, reloaded last saved version".to_string())
}

View File

@@ -0,0 +1,62 @@
// src/tui/functions/common/login.rs
use crate::services::auth::AuthClient;
use crate::state::pages::auth::AuthState;
use crate::state::state::AppState;
use crate::state::canvas_state::CanvasState;
/// Attempts to log the user in using the provided credentials via gRPC.
/// Updates AuthState and AppState on success or failure.
pub async fn save(
auth_state: &mut AuthState,
auth_client: &mut AuthClient,
app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> {
let identifier = auth_state.username.clone();
let password = auth_state.password.clone();
// Call the gRPC login method
match auth_client.login(identifier, password).await {
Ok(response) => {
// Store authentication details on success
auth_state.auth_token = Some(response.access_token);
auth_state.user_id = Some(response.user_id);
auth_state.role = Some(response.role);
auth_state.error_message = None;
auth_state.set_has_unsaved_changes(false); // Mark as "saved"
// Update app state to transition from login to the main form view
app_state.ui.show_login = false;
app_state.ui.show_form = true; // Assuming form is the next view
Ok("Login successful!".to_string())
}
Err(e) => {
// Store error message on failure
let error_message = format!("Login failed: {}", e);
auth_state.error_message = Some(error_message.clone());
// Keep unsaved changes true if login fails, allowing retry/revert
auth_state.set_has_unsaved_changes(true);
Ok(error_message) // Return error message to display
}
}
}
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
/// This function is now named 'revert' to match the 'form' counterpart.
pub async fn revert(
auth_state: &mut AuthState,
app_state: &mut AppState,
) -> String {
// Clear the input fields
auth_state.username.clear();
auth_state.password.clear();
auth_state.error_message = None; // Clear any previous error
auth_state.set_has_unsaved_changes(false); // Fields are cleared, no unsaved changes
// Update app state to hide login and show the previous screen (Intro)
app_state.ui.show_login = false;
app_state.ui.show_intro = true; // Assuming Intro is the screen before login
"Login reverted".to_string()
}

View File

@@ -1,7 +1,6 @@
// src/tui/functions/form.rs
use crate::state::pages::form::FormState;
use crate::services::grpc_client::GrpcClient;
use common::proto::multieko2::adresar::AdresarResponse;
pub async fn handle_action(
action: &str,

View File

@@ -1,5 +1,5 @@
// src/tui/mod.rs
pub mod terminal;
pub mod controls;
pub mod functions;
pub use functions::*;

View File

@@ -2,8 +2,10 @@
use crate::tui::terminal::TerminalCore;
use crate::services::grpc_client::GrpcClient;
use crate::tui::controls::CommandHandler;
use crate::services::auth::AuthClient;
use crate::services::ui_service::UiService; // Add this import
use crate::tui::terminal::EventReader;
use crate::tui::functions::common::CommandHandler;
use crate::config::colors::themes::Theme;
use crate::config::binds::config::Config;
use crate::ui::handlers::render::render_ui;
@@ -16,6 +18,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?;
let auth_client = AuthClient::new().await?;
let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme);
let mut auth_state = AuthState::default();
@@ -23,36 +26,22 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// Initialize app_state first
let mut app_state = AppState::new()?;
// Fetch profile tree and table structure
let profile_tree = grpc_client.get_profile_tree().await?;
app_state.profile_tree = profile_tree;
// Fetch table structure at startup (one-time)
let table_structure = grpc_client.get_table_structure().await?;
// Extract the column names from the response
let column_names: Vec<String> = table_structure
.columns
.iter()
.map(|col| col.name.clone())
.collect();
// Initialize app state with profile tree and table structure
let column_names = UiService::initialize_app_state(&mut grpc_client, &mut app_state).await?;
// Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names);
// The rest of your UI initialization remains the same
let mut event_handler = EventHandler::new();
let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new();
// Fetch the total count of Adresar entries
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
form_state.reset_to_empty();
loop {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
UiService::update_adresar_count(&mut grpc_client, &mut app_state).await?;
terminal.draw(|f| {
render_ui(
@@ -109,44 +98,22 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
form_state.current_field = 0;
} else if app_state.current_position >= 1 && app_state.current_position <= total_count {
// Existing entry - load data
match grpc_client.get_adresar_by_position(app_state.current_position).await {
Ok(response) => {
// Set the ID properly
form_state.id = response.id;
let current_position = app_state.current_position;
let message = UiService::load_adresar_by_position(
&mut grpc_client,
&mut app_state,
&mut form_state,
current_position
).await?;
// Update form values dynamically
form_state.values = vec![
response.firma,
response.kz,
response.drc,
response.ulica,
response.psc,
response.mesto,
response.stat,
response.banka,
response.ucet,
response.skladm,
response.ico,
response.kontakt,
response.telefon,
response.skladu,
response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
current_input.len() - 1 // In readonly mode, limit to last character
} else {
current_input.len()
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
form_state.has_unsaved_changes = false;
event_handler.command_message = format!("Loaded entry {}", app_state.current_position);
}
Err(e) => {
event_handler.command_message = format!("Error loading entry: {}", e);
}
}
let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
current_input.len() - 1 // In readonly mode, limit to last character
} else {
current_input.len()
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
event_handler.command_message = message;
} else {
// Invalid position - reset to first entry
app_state.current_position = 1;
@@ -159,3 +126,4 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
}
}
}