Compare commits

..

23 Commits

Author SHA1 Message Date
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
filipriec
dd4d9e88c6 ready to move gRPC into a single services folder, time to do the changes now 2025-03-31 09:39:47 +02:00
filipriec
f66d67c238 grpc_service moved 2025-03-31 07:13:24 +02:00
filipriec
9cf25afa52 moving grpc_client, needs import fixes 2025-03-31 07:08:51 +02:00
filipriec
2ed2419f9e Add auth service client and auth state fields 2025-03-30 21:44:45 +02:00
filipriec
e19b30f4f4 auth dialog implemented 2025-03-30 20:38:09 +02:00
filipriec
f6e21b6a61 is edit mode passing properly 2025-03-30 19:03:58 +02:00
filipriec
2180d8decf step2 compiled 2025-03-30 18:41:27 +02:00
filipriec
12aec72141 added fields to the traits 2025-03-30 18:33:21 +02:00
filipriec
0568441e46 minor ui stuff 2025-03-30 18:29:33 +02:00
29 changed files with 580 additions and 310 deletions

View File

@@ -1,14 +1,16 @@
// src/components/auth/login.rs // src/components/auth/login.rs
use crate::{ use crate::{
config::colors::themes::Theme, config::colors::themes::Theme,
state::pages::auth::AuthState, state::pages::auth::AuthState,
components::common::dialog,
state::state::AppState, // Add this import
}; };
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Color, Style, Modifier}, style::{Style, Modifier, Color}, // Removed unused Color import
widgets::{Block, BorderType, Borders, Paragraph}, widgets::{Block, BorderType, Borders, Paragraph},
Frame, Frame, // Removed unused Span import
text::{Line, Span},
}; };
pub fn render_login( pub fn render_login(
@@ -16,6 +18,8 @@ pub fn render_login(
area: Rect, area: Rect,
theme: &Theme, theme: &Theme,
state: &AuthState, state: &AuthState,
app_state: &AppState, // Add AppState parameter
is_edit_mode: bool,
) { ) {
// Main container // Main container
let block = Block::default() let block = Block::default()
@@ -43,75 +47,33 @@ pub fn render_login(
.split(inner_area); .split(inner_area);
// --- FORM RENDERING --- // --- FORM RENDERING ---
let fields = &["Username/Email", "Password"];
let inputs = &[&state.username, &state.password];
let current_field = state.current_field;
// Create input container (store the inner area before rendering)
let input_block = Block::default() let input_block = Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_style(if !state.return_selected { .border_style(if is_edit_mode {
Style::default().fg(theme.accent) Style::default().fg(theme.accent)
} else { } else {
Style::default().fg(theme.border) Style::default().fg(theme.border)
}) })
.style(Style::default().bg(theme.bg)); .style(Style::default().bg(theme.bg));
// Calculate inner area before consuming input_block // Calculate inner area BEFORE rendering
let input_area = input_block.inner(chunks[0]); let input_area = input_block.inner(chunks[0]);
// Now render the widget
f.render_widget(input_block, chunks[0]); f.render_widget(input_block, chunks[0]);
let input_layout = Layout::default() // Use the canvas renderer for fields
.direction(Direction::Horizontal) crate::components::handlers::canvas::render_canvas(
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)]) f,
.split(input_area); input_area, // Use the pre-calculated area
state,
&["Username/Email", "Password"],
&state.current_field,
&[&state.username, &state.password],
theme,
is_edit_mode,
);
// Render field labels // --- BUTTONS --- (Keep this unchanged)
for (i, field) in fields.iter().enumerate() {
f.render_widget(
Paragraph::new(Line::from(Span::styled(
format!("{}:", field),
Style::default().fg(theme.fg),
))),
Rect {
x: input_layout[0].x,
y: input_layout[0].y + i as u16,
width: input_layout[0].width,
height: 1,
},
);
}
// Render input fields
let input_rows = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![Constraint::Length(1); fields.len()])
.split(input_layout[1]);
for (i, input) in inputs.iter().enumerate() {
let is_active = i == current_field;
let mut style = Style::default().fg(theme.fg);
if is_active {
style = style.fg(theme.highlight);
}
f.render_widget(
Paragraph::new(input.as_str()).style(style),
input_rows[i],
);
// Set cursor position if active
if is_active {
f.set_cursor_position((
input_rows[i].x + state.current_cursor_pos as u16,
input_rows[i].y,
));
}
}
// --- BUTTONS ---
let button_chunks = Layout::default() let button_chunks = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
@@ -170,4 +132,15 @@ pub fn render_login(
chunks[1], chunks[1],
); );
} }
if app_state.ui.dialog.show_dialog {
dialog::render_dialog(
f,
f.area(), // Use area() instead of deprecated size()
theme,
&app_state.ui.dialog.dialog_title,
&app_state.ui.dialog.dialog_message,
app_state.ui.dialog.dialog_button_active,
);
}
} }

View File

@@ -2,7 +2,9 @@
pub mod command_line; pub mod command_line;
pub mod status_line; pub mod status_line;
pub mod background; pub mod background;
pub mod dialog;
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::*;

View File

@@ -0,0 +1,101 @@
// src/components/common/dialog.rs
use ratatui::{
layout::{Constraint, Direction, Layout, Rect, Margin},
style::{Modifier, Style},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
text::{Text, Line, Span}
};
use ratatui::prelude::Alignment;
use crate::config::colors::themes::Theme;
pub fn render_dialog(
f: &mut Frame,
area: Rect,
theme: &Theme,
title: &str,
message: &str,
is_active: bool,
) {
// Create a centered rect for the dialog
let dialog_area = centered_rect(60, 25, area);
// Main dialog container
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.title(title)
.style(Style::default().bg(theme.bg));
f.render_widget(&block, dialog_area);
// Inner content area
let inner_area = block.inner(dialog_area).inner(Margin {
horizontal: 2,
vertical: 1,
});
// Split into message and button areas
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(3), // Message content
Constraint::Length(3), // Button
])
.split(inner_area);
// Message text
let message_text = Text::from(message.lines().map(|l| Line::from(Span::styled(
l,
Style::default().fg(theme.fg)
))).collect::<Vec<_>>());
let message_paragraph = Paragraph::new(message_text)
.alignment(Alignment::Center);
f.render_widget(message_paragraph, chunks[0]);
// OK Button
let button_style = if is_active {
Style::default()
.fg(theme.highlight)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.fg)
};
let button_block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(Style::default().fg(theme.accent))
.style(Style::default().bg(theme.bg));
f.render_widget(
Paragraph::new("OK")
.block(button_block)
.style(button_style)
.alignment(Alignment::Center),
chunks[1],
);
}
/// Helper function to center a rect with given percentage values
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}

View File

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

View File

@@ -5,6 +5,7 @@ pub mod config;
pub mod state; pub mod state;
pub mod components; pub mod components;
pub mod modes; pub mod modes;
pub mod services;
pub use ui::run_ui; pub use ui::run_ui;

View File

@@ -1,17 +1,21 @@
// src/modes/canvas/common.rs // src/modes/canvas/common.rs
use crate::config::binds::config::Config;
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::tui::terminal::core::TerminalCore; 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::state::state::AppState;
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest}; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::tui::functions::common::{
form::{save as form_save, revert},
login::{save as login_save, cancel}
};
/// Main handler for common core actions
pub async fn handle_core_action( pub async fn handle_core_action(
action: &str, action: &str,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient,
terminal: &mut TerminalCore, terminal: &mut TerminalCore,
app_state: &mut AppState, app_state: &mut AppState,
current_position: &mut u64, current_position: &mut u64,
@@ -19,160 +23,53 @@ pub async fn handle_core_action(
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action { match action {
"save" => { "save" => {
let message = save( if app_state.ui.show_login {
form_state, let message = login_save(auth_state, auth_client, app_state).await?;
grpc_client, Ok((false, message))
&mut app_state.ui.is_saved, } else {
current_position, let message = form_save(
total_count, form_state,
).await?; grpc_client,
Ok((false, message)) &mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
Ok((false, message))
}
}, },
"force_quit" => { "force_quit" => {
terminal.cleanup()?; terminal.cleanup()?;
Ok((true, "Force exiting without saving.".to_string())) Ok((true, "Force exiting without saving.".to_string()))
}, },
"save_and_quit" => { "save_and_quit" => {
let message = save( let message = if app_state.ui.show_login {
form_state, login_save(auth_state, auth_client, app_state).await?
grpc_client, } else {
&mut app_state.ui.is_saved, form_save(
current_position, form_state,
total_count, grpc_client,
).await?; &mut app_state.ui.is_saved,
current_position,
total_count,
).await?
};
terminal.cleanup()?; terminal.cleanup()?;
Ok((true, format!("{}. Exiting application.", message))) Ok((true, format!("{}. Exiting application.", message)))
}, },
"revert" => { "revert" => {
let message = revert( if app_state.ui.show_login {
form_state, let message = cancel(auth_state, app_state).await;
grpc_client, Ok((false, message))
current_position, } else {
total_count, let message = revert(
).await?; form_state,
Ok((false, message)) 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))), _ => 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

@@ -2,12 +2,10 @@
// TODO THIS is freaking bloated with functions it never uses REFACTOR 200 LOC can be gone // TODO THIS is freaking bloated with functions it never uses REFACTOR 200 LOC can be gone
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers}; use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::{
grpc_client::GrpcClient,
};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState; 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(
key: KeyEvent, key: KeyEvent,
@@ -69,7 +67,7 @@ async fn execute_common_action(
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
match action { match action {
"save" => { "save" => {
common::save( save(
form_state, form_state,
grpc_client, grpc_client,
is_saved, is_saved,
@@ -78,7 +76,7 @@ async fn execute_common_action(
).await ).await
}, },
"revert" => { "revert" => {
common::revert( revert(
form_state, form_state,
grpc_client, grpc_client,
current_position, current_position,
@@ -179,7 +177,7 @@ async fn execute_edit_action(
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
match action { match action {
"save" => { "save" => {
common::save( save(
form_state, form_state,
grpc_client, // Changed from AppTerminal grpc_client, // Changed from AppTerminal
is_saved, is_saved,

View File

@@ -1,12 +1,11 @@
// src/modes/canvas/read_only.rs // src/modes/canvas/read_only.rs
use crossterm::event::{KeyEvent}; use crossterm::event::{KeyEvent};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::services::grpc_client::GrpcClient;
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::tui::terminal::grpc_client::GrpcClient;
#[derive(PartialEq)] #[derive(PartialEq)]
enum CharType { enum CharType {
@@ -187,11 +186,6 @@ async fn execute_action(
command_message.clear(); command_message.clear();
Ok("".to_string()) Ok("".to_string())
} }
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => { "move_left" => {
let current_pos = form_state.current_cursor_pos; let current_pos = form_state.current_cursor_pos;
form_state.current_cursor_pos = current_pos.saturating_sub(1); form_state.current_cursor_pos = current_pos.saturating_sub(1);

View File

@@ -1,14 +1,12 @@
// src/modes/handlers/command_mode.rs // src/modes/handlers/command_mode.rs
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers}; use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState; 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::tui::terminal::core::TerminalCore;
use crate::modes::{ use crate::tui::functions::common::form::{save, revert};
canvas::{common},
};
pub async fn handle_command_event( pub async fn handle_command_event(
key: KeyEvent, key: KeyEvent,
@@ -97,7 +95,7 @@ async fn process_command(
Ok((should_exit, message, true)) Ok((should_exit, message, true))
}, },
"save" => { "save" => {
let message = common::save( let message = save(
form_state, form_state,
grpc_client, grpc_client,
&mut command_handler.is_saved, &mut command_handler.is_saved,
@@ -108,7 +106,7 @@ async fn process_command(
return Ok((false, message, true)); return Ok((false, message, true));
}, },
"revert" => { "revert" => {
let message = common::revert( let message = revert(
form_state, form_state,
grpc_client, grpc_client,
current_position, current_position,

View File

@@ -3,9 +3,10 @@ use crossterm::event::Event;
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::{ use crate::tui::terminal::{
core::TerminalCore, core::TerminalCore,
grpc_client::GrpcClient,
}; };
use crate::tui::controls::commands::CommandHandler; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::tui::functions::common::commands::CommandHandler;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
@@ -27,11 +28,12 @@ pub struct EventHandler {
pub ideal_cursor_column: usize, pub ideal_cursor_column: usize,
pub key_sequence_tracker: KeySequenceTracker, pub key_sequence_tracker: KeySequenceTracker,
pub auth_state: AuthState, pub auth_state: AuthState,
pub auth_client: AuthClient,
} }
impl EventHandler { impl EventHandler {
pub fn new() -> Self { pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
EventHandler { Ok(EventHandler {
command_mode: false, command_mode: false,
command_input: String::new(), command_input: String::new(),
command_message: String::new(), command_message: String::new(),
@@ -40,7 +42,8 @@ impl EventHandler {
ideal_cursor_column: 0, ideal_cursor_column: 0,
key_sequence_tracker: KeySequenceTracker::new(800), key_sequence_tracker: KeySequenceTracker::new(800),
auth_state: AuthState::new(), auth_state: AuthState::new(),
} auth_client: AuthClient::new().await?,
})
} }
pub async fn handle_event( pub async fn handle_event(
@@ -131,7 +134,9 @@ impl EventHandler {
return common::handle_core_action( return common::handle_core_action(
action, action,
form_state, form_state,
&mut self.auth_state,
grpc_client, grpc_client,
&mut self.auth_client,
terminal, terminal,
app_state, app_state,
current_position, current_position,
@@ -191,7 +196,9 @@ impl EventHandler {
return common::handle_core_action( return common::handle_core_action(
action, action,
form_state, form_state,
&mut self.auth_state,
grpc_client, grpc_client,
&mut self.auth_client,
terminal, terminal,
app_state, app_state,
current_position, current_position,

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

@@ -1,4 +1,4 @@
// src/tui/terminal/grpc_client.rs // src/services/grpc_client.rs
use tonic::transport::Channel; use tonic::transport::Channel;
use common::proto::multieko2::adresar::adresar_client::AdresarClient; use common::proto::multieko2::adresar::adresar_client::AdresarClient;
@@ -11,6 +11,7 @@ use common::proto::multieko2::table_definition::{
ProfileTreeResponse ProfileTreeResponse
}; };
#[derive(Clone)]
pub struct GrpcClient { pub struct GrpcClient {
adresar_client: AdresarClient<Channel>, adresar_client: AdresarClient<Channel>,
table_structure_client: TableStructureServiceClient<Channel>, table_structure_client: TableStructureServiceClient<Channel>,

View File

@@ -0,0 +1,9 @@
// services/mod.rs
pub mod grpc_client;
pub mod auth;
pub mod ui_service;
pub use grpc_client::*;
pub use ui_service::*;
pub use auth::*;

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

@@ -9,6 +9,7 @@ pub trait CanvasState {
fn inputs(&self) -> Vec<&String>; fn inputs(&self) -> Vec<&String>;
fn get_current_input(&self) -> &str; fn get_current_input(&self) -> &str;
fn get_current_input_mut(&mut self) -> &mut String; 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) // Implement for FormState (keep existing form.rs code and add this)
@@ -41,4 +42,8 @@ impl CanvasState for FormState {
.get_mut(self.current_field) .get_mut(self.current_field)
.expect("Invalid current_field index") .expect("Invalid current_field index")
} }
fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect()
}
} }

View File

@@ -9,6 +9,9 @@ pub struct AuthState {
pub error_message: Option<String>, pub error_message: Option<String>,
pub current_field: usize, pub current_field: usize,
pub current_cursor_pos: usize, pub current_cursor_pos: usize,
pub auth_token: Option<String>,
pub user_id: Option<String>,
pub role: Option<String>,
} }
impl AuthState { impl AuthState {
@@ -20,6 +23,9 @@ impl AuthState {
error_message: None, error_message: None,
current_field: 0, current_field: 0,
current_cursor_pos: 0, current_cursor_pos: 0,
auth_token: None,
user_id: None,
role: None,
} }
} }
} }
@@ -57,4 +63,8 @@ impl CanvasState for AuthState {
_ => panic!("Invalid current_field index in AuthState"), _ => panic!("Invalid current_field index in AuthState"),
} }
} }
fn fields(&self) -> Vec<&str> {
vec!["Username/Email", "Password"]
}
} }

View File

@@ -5,6 +5,14 @@ use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::components::IntroState; use crate::components::IntroState;
use crate::modes::handlers::mode_manager::AppMode; use crate::modes::handlers::mode_manager::AppMode;
#[derive(Default)]
pub struct DialogState {
pub show_dialog: bool,
pub dialog_title: String,
pub dialog_message: String,
pub dialog_button_active: bool,
}
pub struct UiState { pub struct UiState {
pub show_sidebar: bool, pub show_sidebar: bool,
pub is_saved: bool, pub is_saved: bool,
@@ -13,6 +21,7 @@ pub struct UiState {
pub show_form: bool, pub show_form: bool,
pub show_login: bool, pub show_login: bool,
pub intro_state: IntroState, pub intro_state: IntroState,
pub dialog: DialogState, // Add dialog state here
} }
pub struct GeneralState { pub struct GeneralState {
@@ -66,6 +75,24 @@ impl AppState {
pub fn update_mode(&mut self, mode: AppMode) { pub fn update_mode(&mut self, mode: AppMode) {
self.current_mode = mode; self.current_mode = mode;
} }
// Add dialog helper methods
pub fn show_dialog(&mut self, title: &str, message: &str) {
self.ui.dialog.show_dialog = true;
self.ui.dialog.dialog_title = title.to_string();
self.ui.dialog.dialog_message = message.to_string();
self.ui.dialog.dialog_button_active = true;
}
pub fn hide_dialog(&mut self) {
self.ui.dialog.show_dialog = false;
self.ui.dialog.dialog_title.clear();
self.ui.dialog.dialog_message.clear();
}
pub fn set_dialog_button_active(&mut self, active: bool) {
self.ui.dialog.dialog_button_active = active;
}
} }
impl Default for UiState { impl Default for UiState {
@@ -78,6 +105,7 @@ impl Default for UiState {
show_form: false, show_form: false,
show_login: false, show_login: false,
intro_state: IntroState::new(), intro_state: IntroState::new(),
dialog: DialogState::default(),
} }
} }
} }

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 intro;
pub mod login; pub mod login;
pub mod form; pub mod form;
pub mod common;
pub use admin::*; pub use admin::*;
pub use intro::*; pub use intro::*;
pub use form::*; 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, save as form_save};
pub use login::{cancel, 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,45 @@
// src/tui/functions/common/login.rs
use crate::services::auth::AuthClient;
use crate::state::pages::auth::AuthState;
use crate::state::state::AppState;
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();
match auth_client.login(identifier, password).await {
Ok(response) => {
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;
// Update app state to show main interface
app_state.ui.show_login = false;
app_state.ui.show_form = true;
Ok("Login successful!".to_string())
}
Err(e) => {
let error_message = format!("Login failed: {}", e);
auth_state.error_message = Some(error_message.clone());
Ok(error_message)
}
}
}
pub async fn cancel(
auth_state: &mut AuthState,
app_state: &mut AppState,
) -> String {
auth_state.username.clear();
auth_state.password.clear();
auth_state.error_message = None;
app_state.ui.show_login = false;
app_state.ui.show_intro = true;
"Login canceled".to_string()
}

View File

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

View File

@@ -19,10 +19,13 @@ pub async fn handle_action(
} else if auth_state.current_field == 0 { } else if auth_state.current_field == 0 {
// Username -> Password (wrap around fields only) // Username -> Password (wrap around fields only)
auth_state.current_field = 1; auth_state.current_field = 1;
} else if auth_state.current_field == 2 {
// From Login button to Password field
auth_state.current_field = 1;
} }
// Update cursor position // Update cursor position only when in a field
if !auth_state.return_selected { if auth_state.current_field < 2 {
let current_input = auth_state.get_current_input(); let current_input = auth_state.get_current_input();
let max_cursor_pos = current_input.len(); let max_cursor_pos = current_input.len();
auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos); auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
@@ -39,12 +42,16 @@ pub async fn handle_action(
// Username -> Password // Username -> Password
auth_state.current_field = 1; auth_state.current_field = 1;
} else if auth_state.current_field == 1 { } else if auth_state.current_field == 1 {
// Password -> Buttons (Login button) // Password -> Login button
auth_state.current_field = 2;
auth_state.return_selected = false; auth_state.return_selected = false;
} else if auth_state.current_field == 2 {
// Login button -> Return button
auth_state.return_selected = true;
} }
// Update cursor position when in a field // Update cursor position only when in a field
if !auth_state.return_selected { if auth_state.current_field < 2 {
let current_input = auth_state.get_current_input(); let current_input = auth_state.get_current_input();
let max_cursor_pos = current_input.len(); let max_cursor_pos = current_input.len();
auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos); auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
@@ -55,4 +62,3 @@ pub async fn handle_action(
_ => Err("Unknown login action".into()) _ => Err("Unknown login action".into())
} }
} }

View File

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

View File

@@ -1,9 +1,7 @@
// src/tui/terminal.rs // src/tui/terminal.rs
pub mod core; pub mod core;
pub mod grpc_client;
pub mod event_reader; pub mod event_reader;
pub use core::TerminalCore; pub use core::TerminalCore;
pub use grpc_client::GrpcClient;
pub use event_reader::EventReader; pub use event_reader::EventReader;

View File

@@ -47,7 +47,14 @@ pub fn render_ui(
// Use app_state's intro_state directly // Use app_state's intro_state directly
app_state.ui.intro_state.render(f, main_content_area, theme); app_state.ui.intro_state.render(f, main_content_area, theme);
}else if app_state.ui.show_login { }else if app_state.ui.show_login {
render_login(f, main_content_area, theme, auth_state); render_login(
f,
main_content_area,
theme,
auth_state,
app_state, // Add AppState reference here
auth_state.current_field < 2
);
} else if app_state.ui.show_admin { } else if app_state.ui.show_admin {
// Create temporary AdminPanelState for rendering // Create temporary AdminPanelState for rendering
let mut admin_state = AdminPanelState::new( let mut admin_state = AdminPanelState::new(

View File

@@ -1,9 +1,11 @@
// src/ui/handlers/ui.rs // src/ui/handlers/ui.rs
use crate::tui::terminal::TerminalCore; use crate::tui::terminal::TerminalCore;
use crate::tui::terminal::GrpcClient; 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::terminal::EventReader;
use crate::tui::functions::common::CommandHandler;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::ui::handlers::render::render_ui; 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 config = Config::load()?;
let mut terminal = TerminalCore::new()?; let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?; let mut grpc_client = GrpcClient::new().await?;
let mut auth_client = AuthClient::new().await?;
let mut command_handler = CommandHandler::new(); let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme); let theme = Theme::from_str(&config.colors.theme);
let mut auth_state = AuthState::default(); 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 // Initialize app_state first
let mut app_state = AppState::new()?; let mut app_state = AppState::new()?;
// Fetch profile tree and table structure // Initialize app state with profile tree and table structure
let profile_tree = grpc_client.get_profile_tree().await?; let column_names = UiService::initialize_app_state(&mut grpc_client, &mut app_state).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 FormState with dynamic fields // Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names); let mut form_state = FormState::new(column_names);
// The rest of your UI initialization remains the same // 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(); let event_reader = EventReader::new();
// Fetch the total count of Adresar entries // Fetch the total count of Adresar entries
let total_count = grpc_client.get_adresar_count().await?; UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
app_state.update_total_count(total_count);
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
form_state.reset_to_empty(); form_state.reset_to_empty();
loop { loop {
let total_count = grpc_client.get_adresar_count().await?; UiService::update_adresar_count(&mut grpc_client, &mut app_state).await?;
app_state.update_total_count(total_count);
terminal.draw(|f| { terminal.draw(|f| {
render_ui( render_ui(
@@ -109,44 +98,22 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
form_state.current_field = 0; form_state.current_field = 0;
} else if app_state.current_position >= 1 && app_state.current_position <= total_count { } else if app_state.current_position >= 1 && app_state.current_position <= total_count {
// Existing entry - load data // Existing entry - load data
match grpc_client.get_adresar_by_position(app_state.current_position).await { let current_position = app_state.current_position;
Ok(response) => { let message = UiService::load_adresar_by_position(
// Set the ID properly &mut grpc_client,
form_state.id = response.id; &mut app_state,
&mut form_state,
current_position
).await?;
// Update form values dynamically let current_input = form_state.get_current_input();
form_state.values = vec![ let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
response.firma, current_input.len() - 1 // In readonly mode, limit to last character
response.kz, } else {
response.drc, current_input.len()
response.ulica, };
response.psc, form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
response.mesto, event_handler.command_message = message;
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);
}
}
} else { } else {
// Invalid position - reset to first entry // Invalid position - reset to first entry
app_state.current_position = 1; app_state.current_position = 1;
@@ -159,3 +126,4 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
} }
} }
} }