Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d1adccec6 | ||
|
|
420ce71fb2 | ||
|
|
8e5a269ff0 | ||
|
|
f357d6f0ee | ||
|
|
a0467d17a8 | ||
|
|
ef3ecfc73f | ||
|
|
d3fcb23e22 | ||
|
|
5a029283a1 | ||
|
|
09ccad2bd4 | ||
|
|
bdcc10bd40 | ||
|
|
2a1fafc3f9 | ||
|
|
6010b9a0af | ||
|
|
11e8f87fe6 |
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -109,9 +109,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.97"
|
||||
version = "1.0.98"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
|
||||
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
@@ -423,6 +423,7 @@ dependencies = [
|
||||
name = "client"
|
||||
version = "0.3.13"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"common",
|
||||
"crossterm",
|
||||
|
||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.98"
|
||||
async-trait = "0.1.88"
|
||||
common = { path = "../common" }
|
||||
|
||||
|
||||
@@ -249,7 +249,6 @@ pub fn render_add_table(
|
||||
.iter()
|
||||
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||
let header = Row::new(header_cells).height(1).bottom_margin(1);
|
||||
let columns_highlight_symbol = if add_table_state.current_focus == AddTableFocus::InsideColumnsTable { " > " } else { " " };
|
||||
let columns_table = Table::new(
|
||||
column_rows,
|
||||
[ // Define constraints for 3 columns: Sel, Name, Type
|
||||
@@ -353,7 +352,6 @@ pub fn render_add_table(
|
||||
.iter()
|
||||
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||
let index_header = Row::new(index_header_cells).height(1).bottom_margin(1);
|
||||
let indexes_highlight_symbol = if add_table_state.current_focus == AddTableFocus::InsideIndexesTable { " > " } else { " " };
|
||||
let indexes_table =
|
||||
Table::new(index_rows, [Constraint::Percentage(100)])
|
||||
.header(index_header)
|
||||
@@ -399,7 +397,6 @@ pub fn render_add_table(
|
||||
.iter()
|
||||
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||
let link_header = Row::new(link_header_cells).height(1).bottom_margin(1);
|
||||
let links_highlight_symbol = if add_table_state.current_focus == AddTableFocus::InsideLinksTable { " > " } else { " " };
|
||||
let links_table =
|
||||
Table::new(link_rows, [Constraint::Percentage(80), Constraint::Min(5)])
|
||||
.header(link_header)
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::state::app::state::AppState;
|
||||
use crate::state::pages::admin::AdminState;
|
||||
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::Style,
|
||||
text::{Line, Span, Text},
|
||||
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
|
||||
|
||||
@@ -7,7 +7,7 @@ use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
style::Style,
|
||||
text::{Line, Span, Text}, // Added Text
|
||||
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
|
||||
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
|
||||
@@ -66,8 +66,7 @@ pub fn render_admin_panel_admin(
|
||||
.enumerate()
|
||||
.map(|(idx, profile)| {
|
||||
// Check persistent selection for prefix, navigation state for style/highlight
|
||||
let is_selected = admin_state.selected_profile_index == Some(idx); // Use persistent state for [*]
|
||||
let is_navigated = admin_state.profile_list_state.selected() == Some(idx); // Use nav state for highlight/>
|
||||
let is_selected = admin_state.selected_profile_index == Some(idx);
|
||||
let prefix = if is_selected { "[*] " } else { "[ ] " };
|
||||
let style = if is_selected { // Style based on selection too
|
||||
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
|
||||
|
||||
@@ -152,7 +152,7 @@ pub fn render_register(
|
||||
let selected = state.get_selected_suggestion_index();
|
||||
if !suggestions.is_empty() {
|
||||
if let Some(input_rect) = active_field_rect {
|
||||
autocomplete::render_autocomplete_dropdown(f, input_rect, f.size(), theme, suggestions, selected);
|
||||
autocomplete::render_autocomplete_dropdown(f, input_rect, f.area(), theme, suggestions, selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::config::colors::themes::Theme;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Rect},
|
||||
style::{Style, Stylize},
|
||||
style::Style,
|
||||
text::{Line, Span},
|
||||
widgets::Paragraph,
|
||||
Frame,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use anyhow::{Context, Result};
|
||||
use crossterm::event::{KeyCode, KeyModifiers};
|
||||
|
||||
#[derive(Debug, Deserialize, Default)]
|
||||
@@ -43,11 +44,11 @@ pub struct ModeKeybindings {
|
||||
|
||||
impl Config {
|
||||
/// Loads the configuration from "config.toml" in the client crate directory.
|
||||
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
pub fn load() -> Result<Self> {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let config_path = Path::new(manifest_dir).join("config.toml");
|
||||
let config_str = std::fs::read_to_string(&config_path)
|
||||
.map_err(|e| format!("Failed to read config file at {:?}: {}", config_path, e))?;
|
||||
.with_context(|| format!("Failed to read config file at {:?}", config_path))?;
|
||||
let config: Config = toml::from_str(&config_str)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
use crate::state::pages::canvas_state::CanvasState; // Use trait
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum CharType {
|
||||
@@ -134,7 +134,7 @@ pub async fn execute_edit_action(
|
||||
state: &mut AddTableState,
|
||||
ideal_cursor_column: &mut usize,
|
||||
// Add other params like grpc_client if needed for future actions (e.g., validation)
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
) -> Result<String> {
|
||||
// Use the CanvasState trait methods implemented for AddTableState
|
||||
match action {
|
||||
"insert_char" => {
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::state::pages::auth::RegisterState;
|
||||
use crate::tui::functions::common::form::{revert, save};
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use std::any::Any;
|
||||
use anyhow::Result;
|
||||
|
||||
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||
action: &str,
|
||||
@@ -14,7 +15,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
match action {
|
||||
"save" | "revert" => {
|
||||
if !state.has_unsaved_changes() {
|
||||
@@ -62,10 +63,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
||||
key: KeyEvent,
|
||||
state: &mut S,
|
||||
ideal_cursor_column: &mut usize,
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
match action {
|
||||
"insert_char" => {
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
@@ -120,7 +118,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
||||
let num_fields = state.fields().len();
|
||||
if num_fields > 0 {
|
||||
let current_field = state.current_field();
|
||||
let new_field = (current_field + 1) % num_fields;
|
||||
let new_field = (current_field + 1).min(num_fields - 1);
|
||||
state.set_current_field(new_field);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
@@ -135,11 +133,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
||||
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
|
||||
};
|
||||
let new_field = current_field.saturating_sub(1);
|
||||
state.set_current_field(new_field);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::tui::functions::common::form::SaveOutcome;
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use std::any::Any;
|
||||
use anyhow::Result;
|
||||
|
||||
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||
action: &str,
|
||||
@@ -15,7 +16,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
match action {
|
||||
"save" | "revert" => {
|
||||
if !state.has_unsaved_changes() {
|
||||
@@ -76,10 +77,7 @@ pub async fn execute_edit_action<S: CanvasState>(
|
||||
key: KeyEvent,
|
||||
state: &mut S,
|
||||
ideal_cursor_column: &mut usize,
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
match action {
|
||||
"insert_char" => {
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
|
||||
@@ -23,20 +23,6 @@ pub fn handle_add_table_navigation(
|
||||
let mut handled = true; // Assume handled unless logic determines otherwise
|
||||
let mut new_focus = current_focus; // Initialize new_focus
|
||||
|
||||
// Define focus groups for horizontal navigation
|
||||
let is_left_pane_block_focus = matches!(current_focus, // Focus on the table blocks
|
||||
AddTableFocus::ColumnsTable | AddTableFocus::IndexesTable | AddTableFocus::LinksTable
|
||||
);
|
||||
let is_inside_table_focus = matches!(current_focus, // Focus inside for scrolling
|
||||
AddTableFocus::InsideColumnsTable | AddTableFocus::InsideIndexesTable | AddTableFocus::InsideLinksTable
|
||||
);
|
||||
let is_right_pane_general_focus = matches!(current_focus, // Non-canvas elements in right pane
|
||||
AddTableFocus::AddColumnButton | AddTableFocus::SaveButton | AddTableFocus::DeleteSelectedButton | AddTableFocus::CancelButton
|
||||
);
|
||||
let is_canvas_input_focus = matches!(current_focus,
|
||||
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType
|
||||
);
|
||||
|
||||
match action.as_deref() {
|
||||
// --- Handle Exiting Table Scroll Mode ---
|
||||
Some("exit_table_scroll") => {
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::state::{
|
||||
app::state::AppState,
|
||||
pages::admin::{AdminFocus, AdminState},
|
||||
};
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use crossterm::event::KeyEvent;
|
||||
use crate::state::app::buffer::AppView;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
use crate::state::pages::canvas_state::CanvasState; // Use trait for common actions
|
||||
use crate::state::app::state::AppState;
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
// Re-use word navigation helpers if they are public or move them to a common module
|
||||
// For now, duplicating them here for simplicity. Consider refactoring later.
|
||||
@@ -74,7 +74,7 @@ pub async fn execute_action(
|
||||
ideal_cursor_column: &mut usize,
|
||||
key_sequence_tracker: &mut KeySequenceTracker,
|
||||
command_message: &mut String, // Keep for potential messages
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
) -> Result<String> {
|
||||
// Use the CanvasState trait methods implemented for AddTableState
|
||||
match action {
|
||||
"move_up" => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::state::app::state::AppState;
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum CharType {
|
||||
@@ -19,7 +19,7 @@ pub async fn execute_action<S: CanvasState>(
|
||||
ideal_cursor_column: &mut usize,
|
||||
key_sequence_tracker: &mut KeySequenceTracker,
|
||||
command_message: &mut String,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
) -> Result<String> {
|
||||
match action {
|
||||
"previous_entry" | "next_entry" => {
|
||||
key_sequence_tracker.reset();
|
||||
@@ -252,28 +252,6 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||
pos
|
||||
}
|
||||
|
||||
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
if chars.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let next_start = find_next_word_start(text, current_pos);
|
||||
|
||||
if next_start >= chars.len() {
|
||||
return chars.len().saturating_sub(1);
|
||||
}
|
||||
|
||||
let mut pos = next_start;
|
||||
let word_type = get_char_type(chars[pos]);
|
||||
|
||||
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len();
|
||||
@@ -282,8 +260,6 @@ fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||
}
|
||||
|
||||
let mut pos = current_pos.min(len - 1);
|
||||
let original_pos = pos;
|
||||
|
||||
let current_type = get_char_type(chars[pos]);
|
||||
if current_type != CharType::Whitespace {
|
||||
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum CharType {
|
||||
@@ -17,7 +17,7 @@ pub async fn execute_action<S: CanvasState>(
|
||||
ideal_cursor_column: &mut usize,
|
||||
key_sequence_tracker: &mut KeySequenceTracker,
|
||||
command_message: &mut String,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
) -> Result<String> {
|
||||
match action {
|
||||
"previous_entry" | "next_entry" => {
|
||||
key_sequence_tracker.reset();
|
||||
@@ -238,28 +238,6 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||
pos
|
||||
}
|
||||
|
||||
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
if chars.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let next_start = find_next_word_start(text, current_pos);
|
||||
|
||||
if next_start >= chars.len() {
|
||||
return chars.len().saturating_sub(1);
|
||||
}
|
||||
|
||||
let mut pos = next_start;
|
||||
let word_type = get_char_type(chars[pos]);
|
||||
|
||||
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len();
|
||||
@@ -268,8 +246,6 @@ fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||
}
|
||||
|
||||
let mut pos = current_pos.min(len - 1);
|
||||
let original_pos = pos;
|
||||
|
||||
let current_type = get_char_type(chars[pos]);
|
||||
if current_type != CharType::Whitespace {
|
||||
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// client/src/main.rs
|
||||
use client::run_ui;
|
||||
use dotenvy::dotenv;
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
async fn main() -> Result<()> {
|
||||
dotenv().ok();
|
||||
run_ui().await
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::services::grpc_client::GrpcClient;
|
||||
use crate::services::auth::AuthClient;
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::tui::functions::common::form::SaveOutcome;
|
||||
use anyhow::{Context, Result};
|
||||
use crate::tui::functions::common::{
|
||||
form::{save as form_save, revert as form_revert},
|
||||
login::{save as login_save, revert as login_revert},
|
||||
@@ -25,14 +26,14 @@ pub async fn handle_core_action(
|
||||
app_state: &mut AppState,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
match action {
|
||||
"save" => {
|
||||
if app_state.ui.show_login {
|
||||
let message = login_save(auth_state, login_state, auth_client, app_state).await?;
|
||||
let message = login_save(auth_state, login_state, auth_client, app_state).await.context("Login save action failed")?;
|
||||
Ok(EventOutcome::Ok(message))
|
||||
} else if app_state.ui.show_register {
|
||||
let message = register_save(register_state, auth_client, app_state).await?;
|
||||
let message = register_save(register_state, auth_client, app_state).await.context("Register save_and_quit action failed")?;
|
||||
Ok(EventOutcome::Ok(message))
|
||||
} else {
|
||||
let save_outcome = form_save(
|
||||
@@ -40,7 +41,7 @@ pub async fn handle_core_action(
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
).await.context("Register save action failed")?;
|
||||
let message = match save_outcome {
|
||||
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
||||
@@ -55,9 +56,9 @@ pub async fn handle_core_action(
|
||||
},
|
||||
"save_and_quit" => {
|
||||
let message = if app_state.ui.show_login {
|
||||
login_save(auth_state, login_state, auth_client, app_state).await?
|
||||
login_save(auth_state, login_state, auth_client, app_state).await.context("Login save n quit action failed")?
|
||||
} else if app_state.ui.show_register {
|
||||
register_save(register_state, auth_client, app_state).await?
|
||||
register_save(register_state, auth_client, app_state).await.context("Register save n quit action failed")?
|
||||
} else {
|
||||
let save_outcome = form_save(
|
||||
form_state,
|
||||
@@ -87,7 +88,7 @@ pub async fn handle_core_action(
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
).await.context("Form revert x action failed")?;
|
||||
Ok(EventOutcome::Ok(message))
|
||||
}
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::functions::modes::edit::{auth_e, form_e};
|
||||
use crate::functions::modes::edit::add_table_e;
|
||||
use crate::state::app::state::AppState;
|
||||
use anyhow::Result;
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -31,7 +32,7 @@ pub async fn handle_edit_event(
|
||||
total_count: u64,
|
||||
grpc_client: &mut GrpcClient,
|
||||
app_state: &AppState,
|
||||
) -> Result<EditEventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EditEventOutcome> {
|
||||
// Global command mode check (should ideally be handled before calling this function)
|
||||
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
|
||||
&config.keybindings.global,
|
||||
@@ -114,9 +115,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
@@ -133,9 +131,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
@@ -144,9 +139,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
@@ -160,9 +152,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?;
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
@@ -201,9 +190,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?;
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
@@ -217,9 +203,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
@@ -236,9 +219,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
@@ -247,9 +227,6 @@ pub async fn handle_edit_event(
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
@@ -257,125 +234,49 @@ pub async fn handle_edit_event(
|
||||
}
|
||||
|
||||
// --- Character insertion ---
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||
register_state.in_suggestion_mode = false;
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
}
|
||||
|
||||
let msg = if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
add_table_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
add_table_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
form_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
|
||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||
register_state.update_role_suggestions();
|
||||
}
|
||||
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||
register_state.in_suggestion_mode = false;
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
}
|
||||
|
||||
// --- Handle Backspace/Delete ---
|
||||
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
|
||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||
register_state.in_suggestion_mode = false;
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
}
|
||||
|
||||
let action_str = if key.code == KeyCode::Backspace {
|
||||
"delete_char_backward"
|
||||
} else {
|
||||
"delete_char_forward"
|
||||
};
|
||||
|
||||
let result_msg: String = if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
action_str,
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
let msg = if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
add_table_e::execute_edit_action(
|
||||
action_str,
|
||||
key,
|
||||
add_table_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
} else if app_state.ui.show_add_table {
|
||||
add_table_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
add_table_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
action_str,
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
form_e::execute_edit_action(
|
||||
action_str,
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count
|
||||
).await?
|
||||
};
|
||||
|
||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||
register_state.update_role_suggestions();
|
||||
}
|
||||
} else {
|
||||
form_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
|
||||
return Ok(EditEventOutcome::Message(result_msg));
|
||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||
register_state.update_role_suggestions();
|
||||
}
|
||||
|
||||
Ok(EditEventOutcome::Message("".to_string()))
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::state::pages::add_table::AddTableState;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::functions::modes::read_only::{auth_ro, form_ro, add_table_ro};
|
||||
use crossterm::event::KeyEvent;
|
||||
use anyhow::Result;
|
||||
|
||||
pub async fn handle_read_only_event(
|
||||
app_state: &mut AppState,
|
||||
@@ -26,7 +27,7 @@ pub async fn handle_read_only_event(
|
||||
command_message: &mut String,
|
||||
edit_mode_cooldown: &mut bool,
|
||||
ideal_cursor_column: &mut usize,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
) -> Result<(bool, String)> {
|
||||
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
|
||||
*edit_mode_cooldown = true;
|
||||
*command_message = "Entering Edit mode".to_string();
|
||||
@@ -59,10 +60,6 @@ pub async fn handle_read_only_event(
|
||||
"previous_entry",
|
||||
"next_entry",
|
||||
];
|
||||
// Add context actions specific to register if needed, otherwise reuse login/form ones
|
||||
const CONTEXT_ACTIONS_REGISTER: &[&str] = &[
|
||||
// Add actions like "next_field", "prev_field" if handled differently than general read-only
|
||||
];
|
||||
|
||||
if key.modifiers.is_empty() {
|
||||
key_sequence_tracker.add_key(key.code);
|
||||
@@ -150,7 +147,7 @@ pub async fn handle_read_only_event(
|
||||
key_sequence_tracker,
|
||||
command_message,
|
||||
).await?
|
||||
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
|
||||
} else if app_state.ui.show_register {
|
||||
auth_ro::execute_action(
|
||||
action,
|
||||
app_state,
|
||||
@@ -209,7 +206,7 @@ pub async fn handle_read_only_event(
|
||||
key_sequence_tracker,
|
||||
command_message,
|
||||
).await?
|
||||
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
|
||||
} else if app_state.ui.show_register {
|
||||
auth_ro::execute_action(
|
||||
action,
|
||||
app_state,
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::tui::terminal::core::TerminalCore;
|
||||
use crate::tui::functions::common::form::{save, revert};
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::tui::functions::common::form::SaveOutcome;
|
||||
use std::error::Error;
|
||||
use anyhow::Result;
|
||||
|
||||
pub async fn handle_command_event(
|
||||
key: KeyEvent,
|
||||
@@ -26,7 +26,7 @@ pub async fn handle_command_event(
|
||||
terminal: &mut TerminalCore,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<EventOutcome, Box<dyn Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
// Exit command mode (via configurable keybinding)
|
||||
if config.is_exit_command_mode(key.code, key.modifiers) {
|
||||
command_input.clear();
|
||||
@@ -84,7 +84,7 @@ async fn process_command(
|
||||
terminal: &mut TerminalCore,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<EventOutcome, Box<dyn Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
// Clone the trimmed command to avoid borrow issues
|
||||
let command = command_input.trim().to_string();
|
||||
if command.is_empty() {
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::tui::terminal::core::TerminalCore;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use anyhow::Result;
|
||||
|
||||
pub struct CommandHandler;
|
||||
|
||||
@@ -19,7 +20,7 @@ impl CommandHandler {
|
||||
form_state: &FormState,
|
||||
login_state: &LoginState,
|
||||
register_state: &RegisterState,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
) -> Result<(bool, String)> {
|
||||
match action {
|
||||
"quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
|
||||
"force_quit" => self.handle_force_quit(terminal).await,
|
||||
@@ -35,7 +36,7 @@ impl CommandHandler {
|
||||
form_state: &FormState,
|
||||
login_state: &LoginState,
|
||||
register_state: &RegisterState,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
) -> Result<(bool, String)> {
|
||||
// Use actual unsaved changes state instead of is_saved flag
|
||||
let has_unsaved = if app_state.ui.show_login {
|
||||
login_state.has_unsaved_changes()
|
||||
@@ -56,7 +57,7 @@ impl CommandHandler {
|
||||
async fn handle_force_quit(
|
||||
&self,
|
||||
terminal: &mut TerminalCore,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
) -> Result<(bool, String)> {
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "Force exiting without saving.".into()))
|
||||
}
|
||||
@@ -64,7 +65,7 @@ impl CommandHandler {
|
||||
async fn handle_save_quit(
|
||||
&mut self,
|
||||
terminal: &mut TerminalCore,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
) -> Result<(bool, String)> {
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "State saved. Exiting.".into()))
|
||||
}
|
||||
|
||||
@@ -5,12 +5,12 @@ use crate::config::binds::config::Config;
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use crate::state::pages::auth::AuthState;
|
||||
use crate::state::pages::auth::{LoginState, RegisterState};
|
||||
use crate::state::pages::admin::AdminState;
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::tui::functions::common::{login, register};
|
||||
use crate::tui::functions::common::add_table::handle_delete_selected_columns;
|
||||
use anyhow::Result;
|
||||
|
||||
/// Handles key events specifically when a dialog is active.
|
||||
/// Returns Some(Result<EventOutcome, Error>) if the event was handled (consumed),
|
||||
@@ -19,12 +19,11 @@ pub async fn handle_dialog_event(
|
||||
event: &Event,
|
||||
config: &Config,
|
||||
app_state: &mut AppState,
|
||||
auth_state: &mut AuthState,
|
||||
login_state: &mut LoginState,
|
||||
register_state: &mut RegisterState,
|
||||
buffer_state: &mut BufferState,
|
||||
admin_state: &mut AdminState,
|
||||
) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> {
|
||||
) -> Option<Result<EventOutcome>> {
|
||||
if let Event::Key(key) = event {
|
||||
// Always allow Esc to dismiss
|
||||
if key.code == KeyCode::Esc {
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::state::pages::admin::AdminState;
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::ui::handlers::context::UiContext;
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use anyhow::Result;
|
||||
|
||||
pub async fn handle_navigation_event(
|
||||
key: KeyEvent,
|
||||
@@ -24,7 +25,7 @@ pub async fn handle_navigation_event(
|
||||
command_mode: &mut bool,
|
||||
command_input: &mut String,
|
||||
command_message: &mut String,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
||||
match action {
|
||||
"move_up" => {
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::ui::handlers::rat_state::UiStateHandler;
|
||||
use crate::ui::handlers::context::UiContext;
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use crate::functions::common::buffer;
|
||||
use anyhow::{Context, Result};
|
||||
use crate::tui::{
|
||||
terminal::core::TerminalCore,
|
||||
functions::{
|
||||
@@ -29,7 +30,6 @@ use crate::state::{
|
||||
auth::{AuthState, LoginState, RegisterState},
|
||||
admin::AdminState,
|
||||
canvas_state::CanvasState,
|
||||
add_table::AddTableState,
|
||||
form::FormState,
|
||||
intro::IntroState,
|
||||
},
|
||||
@@ -38,11 +38,14 @@ use crate::modes::{
|
||||
common::{command_mode, commands::CommandHandler},
|
||||
handlers::mode_manager::{ModeManager, AppMode},
|
||||
canvas::{edit, read_only, common_mode},
|
||||
highlight::highlight,
|
||||
general::{navigation, dialog},
|
||||
};
|
||||
use crate::functions::modes::navigation::{admin_nav, add_table_nav};
|
||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||
use tokio::spawn;
|
||||
use tokio::sync::mpsc;
|
||||
use crate::tui::functions::common::login::LoginResult;
|
||||
use crate::tui::functions::common::register::RegisterResult;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EventOutcome {
|
||||
@@ -62,10 +65,15 @@ pub struct EventHandler {
|
||||
pub ideal_cursor_column: usize,
|
||||
pub key_sequence_tracker: KeySequenceTracker,
|
||||
pub auth_client: AuthClient,
|
||||
pub login_result_sender: mpsc::Sender<LoginResult>,
|
||||
pub register_result_sender: mpsc::Sender<RegisterResult>,
|
||||
}
|
||||
|
||||
impl EventHandler {
|
||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
pub async fn new(
|
||||
login_result_sender: mpsc::Sender<LoginResult>,
|
||||
register_result_sender: mpsc::Sender<RegisterResult>,
|
||||
) -> Result<Self> {
|
||||
Ok(EventHandler {
|
||||
command_mode: false,
|
||||
command_input: String::new(),
|
||||
@@ -76,6 +84,8 @@ impl EventHandler {
|
||||
ideal_cursor_column: 0,
|
||||
key_sequence_tracker: KeySequenceTracker::new(800),
|
||||
auth_client: AuthClient::new().await?,
|
||||
login_result_sender,
|
||||
register_result_sender,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -96,7 +106,7 @@ impl EventHandler {
|
||||
app_state: &mut AppState,
|
||||
total_count: u64,
|
||||
current_position: &mut u64,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
let current_mode = ModeManager::derive_mode(app_state, self);
|
||||
app_state.update_mode(current_mode);
|
||||
|
||||
@@ -120,7 +130,6 @@ impl EventHandler {
|
||||
&event,
|
||||
config,
|
||||
app_state,
|
||||
auth_state,
|
||||
login_state,
|
||||
register_state,
|
||||
buffer_state,
|
||||
@@ -186,17 +195,15 @@ impl EventHandler {
|
||||
}
|
||||
// --- Add Table Page Navigation ---
|
||||
if app_state.ui.show_add_table {
|
||||
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
||||
if add_table_nav::handle_add_table_navigation(
|
||||
key,
|
||||
config,
|
||||
app_state,
|
||||
&mut admin_state.add_table_state,
|
||||
&mut self.command_message,
|
||||
if add_table_nav::handle_add_table_navigation(
|
||||
key,
|
||||
config,
|
||||
app_state,
|
||||
&mut admin_state.add_table_state,
|
||||
&mut self.command_message,
|
||||
|
||||
) {
|
||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||
}
|
||||
) {
|
||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,8 +222,7 @@ impl EventHandler {
|
||||
).await;
|
||||
match nav_outcome {
|
||||
Ok(EventOutcome::ButtonSelected { context, index }) => {
|
||||
let mut message = String::from("Selected");
|
||||
match context {
|
||||
let message = match context {
|
||||
UiContext::Intro => {
|
||||
intro::handle_intro_selection(app_state, buffer_state, index);
|
||||
if app_state.ui.show_admin {
|
||||
@@ -224,40 +230,120 @@ impl EventHandler {
|
||||
admin_state.profile_list_state.select(Some(0));
|
||||
}
|
||||
}
|
||||
message = format!("Intro Option {} selected", index);
|
||||
format!("Intro Option {} selected", index)
|
||||
}
|
||||
UiContext::Login => {
|
||||
let login_action_message = match index {
|
||||
0 => { // Index 0 corresponds to the "Login" button
|
||||
match login::initiate_login(app_state, login_state).await {
|
||||
Ok(outcome) => return Ok(outcome),
|
||||
Err(e) => {
|
||||
app_state.show_dialog("Error", &format!("Failed to initiate login: {}", e), vec!["OK".to_string()], DialogPurpose::LoginFailed);
|
||||
login_state.login_request_pending = false;
|
||||
"Error initiating login".to_string()
|
||||
}
|
||||
0 => { // "Login" button pressed
|
||||
let username = login_state.username.clone();
|
||||
let password = login_state.password.clone();
|
||||
|
||||
// 1. Client-side validation
|
||||
if username.trim().is_empty() {
|
||||
app_state.show_dialog(
|
||||
"Login Failed",
|
||||
"Username/Email cannot be empty.",
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginFailed,
|
||||
);
|
||||
// Return a message, no need to modify login_state here
|
||||
// as it will be cleared when result is processed
|
||||
"Username cannot be empty.".to_string()
|
||||
} else {
|
||||
// 2. Show Loading Dialog
|
||||
app_state.show_loading_dialog("Logging In", "Please wait...");
|
||||
|
||||
// 3. Clone sender for the task (needs sender from ui.rs)
|
||||
// NOTE: We need access to login_result_sender here.
|
||||
// This requires passing it into EventHandler or handle_event.
|
||||
// Let's assume it's added to EventHandler state for now.
|
||||
let sender = self.login_result_sender.clone(); // Assumes sender is part of EventHandler state
|
||||
|
||||
// 4. Spawn the login task
|
||||
spawn(async move {
|
||||
let login_outcome = match AuthClient::new().await {
|
||||
Ok(mut auth_client) => {
|
||||
match auth_client.login(username.clone(), password).await
|
||||
.with_context(|| format!("Spawned login task failed for identifier: {}", username))
|
||||
{
|
||||
Ok(response) => login::LoginResult::Success(response),
|
||||
Err(e) => login::LoginResult::Failure(format!("{}", e)),
|
||||
}
|
||||
}
|
||||
Err(e) => login::LoginResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
|
||||
};
|
||||
let _ = sender.send(login_outcome).await; // Handle error?
|
||||
});
|
||||
|
||||
// 5. Return immediately
|
||||
"Login initiated.".to_string()
|
||||
}
|
||||
},
|
||||
1 => login::back_to_main(login_state, app_state, buffer_state).await,
|
||||
_ => "Invalid Login Option".to_string(),
|
||||
};
|
||||
message = login_action_message;
|
||||
login_action_message
|
||||
}
|
||||
UiContext::Register => {
|
||||
message = match index {
|
||||
0 => register::save(register_state, &mut self.auth_client, app_state).await?,
|
||||
let register_action_message = match index {
|
||||
0 => { // "Register" button pressed
|
||||
// Clone necessary data
|
||||
let username = register_state.username.clone();
|
||||
let email = register_state.email.clone();
|
||||
let password = register_state.password.clone();
|
||||
let password_confirmation = register_state.password_confirmation.clone();
|
||||
let role = register_state.role.clone();
|
||||
|
||||
// 1. Client-side validation (similar to register::save)
|
||||
if username.trim().is_empty() {
|
||||
app_state.show_dialog("Registration Failed", "Username cannot be empty.", vec!["OK".to_string()], DialogPurpose::RegisterFailed);
|
||||
"Username cannot be empty.".to_string()
|
||||
} else if !password.is_empty() && password != password_confirmation {
|
||||
app_state.show_dialog("Registration Failed", "Passwords do not match.", vec!["OK".to_string()], DialogPurpose::RegisterFailed);
|
||||
"Passwords do not match.".to_string()
|
||||
} else {
|
||||
// 2. Show Loading Dialog
|
||||
app_state.show_loading_dialog("Registering", "Please wait...");
|
||||
|
||||
// 3. Clone sender for the task
|
||||
let sender = self.register_result_sender.clone();
|
||||
|
||||
// 4. Spawn the registration task
|
||||
spawn(async move {
|
||||
let register_outcome = match AuthClient::new().await {
|
||||
Ok(mut auth_client) => {
|
||||
// Handle optional fields correctly for the gRPC call
|
||||
let password_opt = if password.is_empty() { None } else { Some(password) };
|
||||
let password_conf_opt = if password_confirmation.is_empty() { None } else { Some(password_confirmation) };
|
||||
let role_opt = if role.is_empty() { None } else { Some(role) };
|
||||
|
||||
match auth_client.register(username.clone(), email, password_opt, password_conf_opt, role_opt).await {
|
||||
Ok(response) => register::RegisterResult::Success(response),
|
||||
Err(e) => register::RegisterResult::Failure(format!("{}", e)),
|
||||
}
|
||||
}
|
||||
Err(e) => register::RegisterResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
|
||||
};
|
||||
let _ = sender.send(register_outcome).await;
|
||||
});
|
||||
|
||||
// 5. Return immediately
|
||||
"Registration initiated.".to_string()
|
||||
}
|
||||
},
|
||||
1 => register::back_to_login(register_state, app_state, buffer_state).await,
|
||||
_ => "Invalid Login Option".to_string(),
|
||||
};
|
||||
register_action_message
|
||||
}
|
||||
UiContext::Admin => {
|
||||
admin::handle_admin_selection(app_state, admin_state);
|
||||
message = format!("Admin Option {} selected", index);
|
||||
format!("Admin Option {} selected", index)
|
||||
}
|
||||
UiContext::Dialog => {
|
||||
message = "Internal error: Unexpected dialog state".to_string();
|
||||
"Internal error: Unexpected dialog state".to_string()
|
||||
}
|
||||
}
|
||||
}; // Semicolon added here
|
||||
return Ok(EventOutcome::Ok(message));
|
||||
}
|
||||
other => return other,
|
||||
@@ -499,7 +585,7 @@ impl EventHandler {
|
||||
}
|
||||
Err(e) => {
|
||||
// Handle error from the edit handler
|
||||
return Err(e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}, // End AppMode::Edit
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::modes::handlers::event::EventHandler;
|
||||
use crate::state::app::highlight::HighlightState;
|
||||
use crate::state::pages::add_table::AddTableFocus;
|
||||
use crate::state::pages::admin::AdminState;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AppMode {
|
||||
|
||||
@@ -9,8 +9,9 @@ use crate::state::pages::auth::{LoginState, RegisterState};
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::modes::read_only; // Import the ReadOnly handler
|
||||
use crate::modes::read_only;
|
||||
use crossterm::event::KeyEvent;
|
||||
use anyhow::Result;
|
||||
|
||||
/// Handles events when in Highlight mode.
|
||||
/// Currently, it mostly delegates to the read_only handler for movement.
|
||||
@@ -30,7 +31,7 @@ pub async fn handle_highlight_event(
|
||||
command_message: &mut String,
|
||||
edit_mode_cooldown: &mut bool,
|
||||
ideal_cursor_column: &mut usize,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
) -> Result<EventOutcome> {
|
||||
// Delegate movement and other actions to the read_only handler
|
||||
// The rendering logic will use the highlight_anchor to draw the selection
|
||||
let (should_exit, message) = read_only::handle_read_only_event(
|
||||
|
||||
@@ -9,4 +9,3 @@ pub use handlers::*;
|
||||
pub use canvas::*;
|
||||
pub use general::*;
|
||||
pub use common::*;
|
||||
pub use highlight::*;
|
||||
|
||||
@@ -5,19 +5,22 @@ use common::proto::multieko2::auth::{
|
||||
LoginRequest, LoginResponse,
|
||||
RegisterRequest, AuthResponse,
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
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?;
|
||||
pub async fn new() -> Result<Self> {
|
||||
let client = AuthServiceClient::connect("http://[::1]:50051")
|
||||
.await
|
||||
.context("Failed to connect to auth service")?;
|
||||
Ok(Self { client })
|
||||
}
|
||||
|
||||
/// Login user via gRPC.
|
||||
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
|
||||
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse> {
|
||||
let request = tonic::Request::new(LoginRequest { identifier, password });
|
||||
let response = self.client.login(request).await?.into_inner();
|
||||
Ok(response)
|
||||
@@ -31,7 +34,7 @@ impl AuthClient {
|
||||
password: Option<String>,
|
||||
password_confirmation: Option<String>,
|
||||
role: Option<String>,
|
||||
) -> Result<AuthResponse, Box<dyn std::error::Error>> {
|
||||
) -> Result<AuthResponse> {
|
||||
let request = tonic::Request::new(RegisterRequest {
|
||||
username,
|
||||
email,
|
||||
|
||||
@@ -10,6 +10,7 @@ use common::proto::multieko2::table_definition::{
|
||||
table_definition_client::TableDefinitionClient,
|
||||
ProfileTreeResponse
|
||||
};
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GrpcClient {
|
||||
@@ -19,7 +20,7 @@ pub struct GrpcClient {
|
||||
}
|
||||
|
||||
impl GrpcClient {
|
||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
pub async fn new() -> Result<Self> {
|
||||
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?;
|
||||
@@ -31,37 +32,37 @@ impl GrpcClient {
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_adresar_count(&mut self) -> Result<u64, Box<dyn std::error::Error>> {
|
||||
pub async fn get_adresar_count(&mut self) -> Result<u64> {
|
||||
let request = tonic::Request::new(Empty::default());
|
||||
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
|
||||
Ok(response.count as u64)
|
||||
}
|
||||
|
||||
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse, Box<dyn std::error::Error>> {
|
||||
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse> {
|
||||
let request = tonic::Request::new(PositionRequest { position: position as i64 });
|
||||
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
|
||||
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
||||
let request = tonic::Request::new(request);
|
||||
let response = self.adresar_client.post_adresar(request).await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
|
||||
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
||||
let request = tonic::Request::new(request);
|
||||
let response = self.adresar_client.put_adresar(request).await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse, Box<dyn std::error::Error>> {
|
||||
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse> {
|
||||
let request = tonic::Request::new(Empty::default());
|
||||
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
|
||||
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse, Box<dyn std::error::Error>> {
|
||||
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse> {
|
||||
let request = tonic::Request::new(Empty::default());
|
||||
let response = self.table_definition_client.get_profile_tree(request).await?;
|
||||
Ok(response.into_inner())
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::services::grpc_client::GrpcClient;
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::tui::functions::common::form::SaveOutcome;
|
||||
use crate::state::app::state::AppState;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
pub struct UiService;
|
||||
|
||||
@@ -11,9 +12,9 @@ impl UiService {
|
||||
pub async fn initialize_app_state(
|
||||
grpc_client: &mut GrpcClient,
|
||||
app_state: &mut AppState,
|
||||
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
||||
) -> Result<Vec<String>> {
|
||||
// Fetch profile tree
|
||||
let profile_tree = grpc_client.get_profile_tree().await?;
|
||||
let profile_tree = grpc_client.get_profile_tree().await.context("Failed to get profile tree")?;
|
||||
app_state.profile_tree = profile_tree;
|
||||
|
||||
// Fetch table structure
|
||||
@@ -32,8 +33,8 @@ impl UiService {
|
||||
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?;
|
||||
) -> Result<()> {
|
||||
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar count")?;
|
||||
app_state.update_total_count(total_count);
|
||||
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
||||
Ok(())
|
||||
@@ -42,18 +43,18 @@ impl UiService {
|
||||
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?;
|
||||
) -> Result<()> {
|
||||
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar by position")?;
|
||||
app_state.update_total_count(total_count);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn load_adresar_by_position(
|
||||
grpc_client: &mut GrpcClient,
|
||||
app_state: &mut AppState,
|
||||
_app_state: &mut AppState,
|
||||
form_state: &mut FormState,
|
||||
position: u64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
match grpc_client.get_adresar_by_position(position).await {
|
||||
Ok(response) => {
|
||||
// Set the ID properly
|
||||
@@ -92,8 +93,8 @@ impl UiService {
|
||||
save_outcome: SaveOutcome,
|
||||
grpc_client: &mut GrpcClient,
|
||||
app_state: &mut AppState,
|
||||
form_state: &mut FormState, // Needed to potentially update position/ID
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
form_state: &mut FormState,
|
||||
) -> Result<()> {
|
||||
match save_outcome {
|
||||
SaveOutcome::CreatedNew(new_id) => {
|
||||
// A new record was created, update the count!
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::env;
|
||||
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||
use crate::modes::handlers::mode_manager::AppMode;
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use anyhow::Result;
|
||||
|
||||
pub struct DialogState {
|
||||
pub dialog_show: bool,
|
||||
@@ -43,7 +44,7 @@ pub struct AppState {
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
pub fn new() -> Result<Self> {
|
||||
let current_dir = env::current_dir()?
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::state::pages::form::FormState;
|
||||
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SaveOutcome {
|
||||
@@ -17,7 +18,7 @@ pub async fn save(
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<SaveOutcome, Box<dyn std::error::Error>> { // <-- Return SaveOutcome
|
||||
) -> Result<SaveOutcome> { // <-- Return SaveOutcome
|
||||
if !form_state.has_unsaved_changes {
|
||||
return Ok(SaveOutcome::NoChange); // Early exit if no changes
|
||||
}
|
||||
@@ -78,7 +79,7 @@ pub async fn revert(
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
let is_new = *current_position == total_count + 1;
|
||||
|
||||
if is_new {
|
||||
|
||||
@@ -7,26 +7,49 @@ use crate::state::app::state::AppState;
|
||||
use crate::state::app::buffer::{AppView, BufferState};
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use crate::modes::handlers::event::EventOutcome; // Make sure this is imported
|
||||
use common::proto::multieko2::auth::LoginResponse;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LoginResult {
|
||||
Success(LoginResponse),
|
||||
Failure(String),
|
||||
ConnectionError(String),
|
||||
}
|
||||
|
||||
/// Attempts to log the user in using the provided credentials via gRPC.
|
||||
/// Updates AuthState and AppState on success or failure.
|
||||
/// (This is your existing function - remains unchanged)
|
||||
pub async fn save(
|
||||
auth_state: &mut AuthState,
|
||||
login_state: &mut LoginState,
|
||||
auth_client: &mut AuthClient,
|
||||
app_state: &mut AppState,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
let identifier = login_state.username.clone();
|
||||
let password = login_state.password.clone();
|
||||
|
||||
// --- Client-side validation ---
|
||||
// Prevent login attempt if the identifier field is empty or whitespace.
|
||||
if identifier.trim().is_empty() {
|
||||
let error_message = "Username/Email cannot be empty.".to_string();
|
||||
app_state.show_dialog(
|
||||
"Login Failed",
|
||||
&error_message,
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginFailed,
|
||||
);
|
||||
login_state.error_message = Some(error_message.clone());
|
||||
return Err(anyhow::anyhow!(error_message));
|
||||
}
|
||||
|
||||
// Clear previous error/dialog state before attempting
|
||||
login_state.error_message = None;
|
||||
app_state.hide_dialog(); // Hide any previous dialog
|
||||
|
||||
// Call the gRPC login method
|
||||
match auth_client.login(identifier, password).await {
|
||||
match auth_client.login(identifier.clone(), password).await
|
||||
.with_context(|| format!("gRPC login attempt failed for identifier: {}", identifier))
|
||||
{
|
||||
Ok(response) => {
|
||||
// Store authentication details using correct field names
|
||||
auth_state.auth_token = Some(response.access_token.clone());
|
||||
@@ -54,6 +77,7 @@ pub async fn save(
|
||||
DialogPurpose::LoginSuccess,
|
||||
);
|
||||
login_state.password.clear();
|
||||
login_state.username.clear();
|
||||
login_state.current_cursor_pos = 0;
|
||||
Ok("Login successful, details shown in dialog.".to_string())
|
||||
}
|
||||
@@ -67,28 +91,13 @@ pub async fn save(
|
||||
);
|
||||
login_state.error_message = Some(error_message.clone());
|
||||
login_state.set_has_unsaved_changes(true);
|
||||
Ok(format!("Login failed: {}", error_message))
|
||||
login_state.username.clear();
|
||||
login_state.password.clear();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Add this new function ---
|
||||
/// Sets the stage for login: shows loading dialog and sets the pending flag.
|
||||
/// Call this from the event handler when login is triggered.
|
||||
pub async fn initiate_login(
|
||||
app_state: &mut AppState,
|
||||
login_state: &mut LoginState,
|
||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||
// Show the loading dialog immediately
|
||||
app_state.show_loading_dialog("Logging In", "Please wait...");
|
||||
// Set the flag in LoginState to indicate the actual save should run next loop
|
||||
login_state.login_request_pending = true;
|
||||
// Return immediately to allow redraw
|
||||
Ok(EventOutcome::Ok("Login initiated.".to_string()))
|
||||
}
|
||||
// --- End of new function ---
|
||||
|
||||
|
||||
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
|
||||
pub async fn revert(
|
||||
login_state: &mut LoginState,
|
||||
|
||||
@@ -8,6 +8,15 @@ use crate::state::{
|
||||
};
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use crate::state::app::buffer::{AppView, BufferState};
|
||||
use common::proto::multieko2::auth::AuthResponse;
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RegisterResult {
|
||||
Success(AuthResponse),
|
||||
Failure(String),
|
||||
ConnectionError(String),
|
||||
}
|
||||
|
||||
/// Attempts to register the user using the provided details via gRPC.
|
||||
/// Updates RegisterState and AppState on success or failure.
|
||||
@@ -15,7 +24,7 @@ pub async fn save(
|
||||
register_state: &mut RegisterState,
|
||||
auth_client: &mut AuthClient,
|
||||
app_state: &mut AppState,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
let username = register_state.username.clone();
|
||||
let email = register_state.email.clone();
|
||||
// Handle optional passwords: send None if empty, Some(value) otherwise
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use anyhow::{anyhow, Result};
|
||||
|
||||
pub async fn handle_action(
|
||||
action: &str,
|
||||
@@ -10,7 +11,7 @@ pub async fn handle_action(
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
ideal_cursor_column: &mut usize,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String> {
|
||||
// TODO store unsaved changes without deleting form state values
|
||||
// First check for unsaved changes in both cases
|
||||
if form_state.has_unsaved_changes() {
|
||||
@@ -84,6 +85,7 @@ pub async fn handle_action(
|
||||
Ok("Already at last entry".into())
|
||||
}
|
||||
}
|
||||
_ => Err("Unknown form action".into())
|
||||
_ => Err(anyhow!("Unknown form action: {}", action))
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// src/tui/functions/login.rs
|
||||
|
||||
pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::Error>> {
|
||||
use anyhow::{anyhow, Result};
|
||||
|
||||
pub async fn handle_action(action: &str,) -> Result<String> {
|
||||
match action {
|
||||
"previous_entry" => {
|
||||
Ok("Previous entry at tui/functions/login.rs not implemented".into())
|
||||
@@ -8,6 +10,6 @@ pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::
|
||||
"next_entry" => {
|
||||
Ok("Next entry at tui/functions/login.rs not implemented".into())
|
||||
}
|
||||
_ => Err("Unknown login action".into())
|
||||
_ => Err(anyhow!("Unknown login action: {}", action))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,14 @@ use crossterm::{
|
||||
};
|
||||
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||
use std::io::{self, stdout, Write};
|
||||
use anyhow::Result;
|
||||
|
||||
pub struct TerminalCore {
|
||||
terminal: Terminal<CrosstermBackend<io::Stdout>>,
|
||||
}
|
||||
|
||||
impl TerminalCore {
|
||||
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
pub fn new() -> Result<Self> {
|
||||
enable_raw_mode()?;
|
||||
let mut stdout = stdout();
|
||||
execute!(
|
||||
@@ -27,7 +28,7 @@ impl TerminalCore {
|
||||
Ok(Self { terminal })
|
||||
}
|
||||
|
||||
pub fn draw<F>(&mut self, f: F) -> Result<(), Box<dyn std::error::Error>>
|
||||
pub fn draw<F>(&mut self, f: F) -> Result<()>
|
||||
where
|
||||
F: FnOnce(&mut ratatui::Frame),
|
||||
{
|
||||
@@ -35,7 +36,7 @@ impl TerminalCore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cleanup(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn cleanup(&mut self) -> Result<()> {
|
||||
let backend = self.terminal.backend_mut();
|
||||
execute!(
|
||||
backend,
|
||||
@@ -56,7 +57,7 @@ impl TerminalCore {
|
||||
pub fn set_cursor_style(
|
||||
&mut self,
|
||||
style: SetCursorStyle,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
) -> Result<()> {
|
||||
execute!(
|
||||
self.terminal.backend_mut(),
|
||||
style,
|
||||
@@ -65,7 +66,7 @@ impl TerminalCore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn show_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn show_cursor(&mut self) -> Result<()> {
|
||||
execute!(
|
||||
self.terminal.backend_mut(),
|
||||
Show
|
||||
@@ -73,7 +74,7 @@ impl TerminalCore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn hide_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn hide_cursor(&mut self) -> Result<()> {
|
||||
execute!(
|
||||
self.terminal.backend_mut(),
|
||||
Hide
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// src/tui/terminal/event_reader.rs
|
||||
|
||||
use crossterm::event::{self, Event};
|
||||
use anyhow::Result;
|
||||
|
||||
pub struct EventReader;
|
||||
|
||||
@@ -9,7 +10,7 @@ impl EventReader {
|
||||
Self
|
||||
}
|
||||
|
||||
pub fn read_event(&self) -> Result<Event, Box<dyn std::error::Error>> {
|
||||
pub fn read_event(&self) -> Result<Event> {
|
||||
Ok(event::read()?)
|
||||
}
|
||||
}
|
||||
|
||||
34
client/src/ui/docs/ui_redraws.md
Normal file
34
client/src/ui/docs/ui_redraws.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# UI Redraw Logic (`needs_redraw` Flag)
|
||||
|
||||
## Problem
|
||||
|
||||
The main UI loop in `client/src/ui/handlers/ui.rs` uses `crossterm_event::poll` with a short timeout to remain responsive to both user input and asynchronous operations (like login results arriving via channels). However, calling `terminal.draw()` unconditionally in every loop iteration caused constant UI refreshes and high CPU usage, even when idle.
|
||||
|
||||
## Solution
|
||||
|
||||
A boolean flag, `needs_redraw`, was introduced in the main loop scope to control when the UI is actually redrawn.
|
||||
|
||||
## Mechanism
|
||||
|
||||
1. **Initialization:** `needs_redraw` is initialized to `true` before the loop starts to ensure the initial UI state is drawn.
|
||||
2. **Conditional Drawing:** The `terminal.draw(...)` call is wrapped in an `if needs_redraw { ... }` block.
|
||||
3. **Flag Reset:** Immediately after a successful `terminal.draw(...)` call, `needs_redraw` is set back to `false`.
|
||||
4. **Triggering Redraws:** The `needs_redraw` flag is explicitly set to `true` only when a redraw is actually required.
|
||||
|
||||
## When `needs_redraw` Must Be Set to `true`
|
||||
|
||||
To ensure the UI stays up-to-date without unnecessary refreshes, `needs_redraw = true;` **must** be set in the following situations:
|
||||
|
||||
1. **After Handling User Input:** When `crossterm_event::poll` returns `true`, indicating a keyboard/mouse event was received and processed by `event_handler.handle_event`.
|
||||
2. **During Active Loading States:** If an asynchronous operation is in progress and a visual indicator (like a loading dialog) is active (e.g., checking `if app_state.ui.dialog.is_loading`). This keeps the loading state visible while waiting for the result.
|
||||
3. **After Processing Async Results:** When the result of an asynchronous operation (e.g., received from an `mpsc::channel` like `login_result_receiver`) is processed and the application state is updated (e.g., dialog content changed, data updated).
|
||||
4. **After Internal State Changes:** If any logic *outside* the direct event handling block modifies state that needs to be visually reflected (e.g., the position change logic loading new data into the form).
|
||||
|
||||
## Rationale
|
||||
|
||||
This approach balances UI responsiveness for asynchronous tasks and user input with CPU efficiency by avoiding redraws when the application state is static.
|
||||
|
||||
## Maintenance Note
|
||||
|
||||
When adding new asynchronous operations or internal logic that modifies UI-relevant state outside the main event handler, developers **must remember** to set `needs_redraw = true` at the appropriate point after the state change to ensure the UI updates correctly. Failure to do so can result in a stale UI.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::config::colors::themes::Theme;
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::services::auth::AuthClient; // <-- Add AuthClient import
|
||||
// <-- Add AuthClient import
|
||||
use crate::services::ui_service::UiService;
|
||||
use crate::modes::common::commands::CommandHandler;
|
||||
use crate::modes::handlers::event::{EventHandler, EventOutcome};
|
||||
@@ -18,24 +18,34 @@ use crate::state::pages::intro::IntroState;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use crate::state::app::buffer::AppView;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::ui::handlers::context::DialogPurpose; // <-- Add DialogPurpose import
|
||||
// Import SaveOutcome
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use crate::tui::terminal::{EventReader, TerminalCore};
|
||||
use crate::ui::handlers::render::render_ui;
|
||||
use crate::tui::functions::common::login; // <-- Add login module import
|
||||
use crate::tui::functions::common::login::LoginResult;
|
||||
use crate::tui::functions::common::register::RegisterResult;
|
||||
use std::time::Instant;
|
||||
use anyhow::{Context, Result};
|
||||
use crossterm::cursor::SetCursorStyle;
|
||||
use crossterm::event as crossterm_event;
|
||||
use tracing::{info, error};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = Config::load()?;
|
||||
pub async fn run_ui() -> Result<()> {
|
||||
let config = Config::load().context("Failed to load configuration")?;
|
||||
let theme = Theme::from_str(&config.colors.theme);
|
||||
let mut terminal = TerminalCore::new()?;
|
||||
let mut terminal = TerminalCore::new().context("Failed to initialize terminal")?;
|
||||
let mut grpc_client = GrpcClient::new().await?;
|
||||
let mut command_handler = CommandHandler::new();
|
||||
|
||||
let mut event_handler = EventHandler::new().await?;
|
||||
// --- Channel for Login Results ---
|
||||
let (login_result_sender, mut login_result_receiver) =
|
||||
mpsc::channel::<LoginResult>(1);
|
||||
let (register_result_sender, mut register_result_receiver) =
|
||||
mpsc::channel::<RegisterResult>(1);
|
||||
let mut event_handler = EventHandler::new(
|
||||
login_result_sender.clone(),
|
||||
register_result_sender.clone(),
|
||||
).await.context("Failed to create event handler")?;
|
||||
let event_reader = EventReader::new();
|
||||
|
||||
let mut auth_state = AuthState::default();
|
||||
@@ -44,22 +54,22 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut intro_state = IntroState::default();
|
||||
let mut admin_state = AdminState::default();
|
||||
let mut buffer_state = BufferState::default();
|
||||
let mut app_state = AppState::new()?;
|
||||
let mut app_state = AppState::new().context("Failed to create initial app state")?;
|
||||
|
||||
// Initialize app state with profile tree and table structure
|
||||
let column_names =
|
||||
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
||||
.await?;
|
||||
.await.context("Failed to initialize app state from UI service")?;
|
||||
let mut form_state = FormState::new(column_names);
|
||||
|
||||
// Fetch the total count of Adresar entries
|
||||
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state)
|
||||
.await?;
|
||||
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
|
||||
form_state.reset_to_empty();
|
||||
|
||||
// --- FPS Calculation State ---
|
||||
let mut last_frame_time = Instant::now();
|
||||
let mut current_fps = 0.0;
|
||||
let mut needs_redraw = true;
|
||||
|
||||
loop {
|
||||
// --- Synchronize UI View from Active Buffer ---
|
||||
@@ -93,29 +103,32 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Draw the current state *first*. This ensures the loading dialog
|
||||
// set in the *previous* iteration gets rendered before the pending
|
||||
// action check below.
|
||||
terminal.draw(|f| {
|
||||
render_ui(
|
||||
f,
|
||||
&mut form_state,
|
||||
&mut auth_state,
|
||||
&login_state,
|
||||
®ister_state,
|
||||
&intro_state,
|
||||
&mut admin_state,
|
||||
&buffer_state,
|
||||
&theme,
|
||||
event_handler.is_edit_mode, // Use event_handler's state
|
||||
&event_handler.highlight_state,
|
||||
app_state.total_count,
|
||||
app_state.current_position,
|
||||
&app_state.current_dir,
|
||||
&event_handler.command_input,
|
||||
event_handler.command_mode,
|
||||
&event_handler.command_message,
|
||||
current_fps,
|
||||
&app_state,
|
||||
);
|
||||
})?;
|
||||
if needs_redraw {
|
||||
terminal.draw(|f| {
|
||||
render_ui(
|
||||
f,
|
||||
&mut form_state,
|
||||
&mut auth_state,
|
||||
&login_state,
|
||||
®ister_state,
|
||||
&intro_state,
|
||||
&mut admin_state,
|
||||
&buffer_state,
|
||||
&theme,
|
||||
event_handler.is_edit_mode, // Use event_handler's state
|
||||
&event_handler.highlight_state,
|
||||
app_state.total_count,
|
||||
app_state.current_position,
|
||||
&app_state.current_dir,
|
||||
&event_handler.command_input,
|
||||
event_handler.command_mode,
|
||||
&event_handler.command_message,
|
||||
current_fps,
|
||||
&app_state,
|
||||
);
|
||||
}).context("Terminal draw call failed")?;
|
||||
needs_redraw = false;
|
||||
}
|
||||
|
||||
// --- Cursor Visibility Logic ---
|
||||
// (Keep existing cursor logic here - depends on state drawn above)
|
||||
@@ -126,66 +139,30 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
AppMode::ReadOnly => {
|
||||
if !app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; }
|
||||
else { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; }
|
||||
terminal.show_cursor()?;
|
||||
terminal.show_cursor().context("Failed to show cursor in ReadOnly mode")?;
|
||||
}
|
||||
AppMode::General => {
|
||||
if app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor()?; }
|
||||
else { terminal.hide_cursor()?; }
|
||||
}
|
||||
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor()?; }
|
||||
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor().context("Failed to show cursor in Command mode")?; }
|
||||
}
|
||||
// --- End Cursor Visibility Logic ---
|
||||
|
||||
// --- 2. Check for Pending Login Action ---
|
||||
if login_state.login_request_pending {
|
||||
// Reset the flag *before* calling save
|
||||
login_state.login_request_pending = false;
|
||||
|
||||
// Create AuthClient and call save
|
||||
match AuthClient::new().await {
|
||||
Ok(mut auth_client_instance) => {
|
||||
// Call the ORIGINAL save function from the login module
|
||||
let save_result = login::save(
|
||||
&mut auth_state,
|
||||
&mut login_state,
|
||||
&mut auth_client_instance, // Pass the new client instance
|
||||
&mut app_state,
|
||||
).await;
|
||||
|
||||
// Use tracing for logging the outcome
|
||||
match save_result {
|
||||
// save returns Result<String, Error>, Ok contains the message
|
||||
Ok(msg) => info!(message = %msg, "Login save result"), // Use tracing::info!
|
||||
Err(e) => error!(error = %e, "Error during login save"), // Use tracing::error!
|
||||
}
|
||||
// Note: save already handles showing the final dialog (success/failure)
|
||||
}
|
||||
Err(e) => {
|
||||
// Handle client connection error - show dialog directly
|
||||
// Ensure flag is already false here
|
||||
app_state.show_dialog( // Use show_dialog, not update_dialog_content
|
||||
"Login Failed",
|
||||
&format!("Connection Error: {}", e),
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginFailed, // Use appropriate purpose
|
||||
);
|
||||
login_state.error_message = Some(format!("Connection Error: {}", e));
|
||||
error!(error = %e, "Failed to create AuthClient"); // Use tracing::error!
|
||||
}
|
||||
}
|
||||
// After save runs, the state (dialog content, etc.) is updated.
|
||||
// The *next* iteration's draw call will show the final result.
|
||||
} // --- End Pending Login Check ---
|
||||
|
||||
let total_count = app_state.total_count;
|
||||
let mut current_position = app_state.current_position;
|
||||
let position_before_event = current_position;
|
||||
// --- Determine if redraw is needed based on active login ---
|
||||
// Always redraw if the loading dialog is currently showing.
|
||||
if app_state.ui.dialog.is_loading {
|
||||
needs_redraw = true;
|
||||
}
|
||||
|
||||
// --- 1. Handle Terminal Events ---
|
||||
let mut event_outcome_result = Ok(EventOutcome::Ok(String::new()));
|
||||
// Poll for events *after* drawing and checking pending actions
|
||||
if crossterm_event::poll(std::time::Duration::from_millis(20))? {
|
||||
let event = event_reader.read_event()?;
|
||||
if crossterm_event::poll(std::time::Duration::from_millis(1))? {
|
||||
let event = event_reader.read_event().context("Failed to read terminal event")?;
|
||||
event_outcome_result = event_handler
|
||||
.handle_event(
|
||||
event,
|
||||
@@ -205,12 +182,117 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
&mut current_position,
|
||||
)
|
||||
.await;
|
||||
needs_redraw = true;
|
||||
}
|
||||
|
||||
// Update position based on handler's modification
|
||||
// This happens *after* the event is handled
|
||||
app_state.current_position = current_position;
|
||||
|
||||
// --- Check for Login Results from Channel ---
|
||||
match login_result_receiver.try_recv() {
|
||||
Ok(login_result) => {
|
||||
// A result arrived from the login task!
|
||||
match login_result {
|
||||
LoginResult::Success(response) => {
|
||||
// Update AuthState
|
||||
auth_state.auth_token = Some(response.access_token.clone());
|
||||
auth_state.user_id = Some(response.user_id.clone());
|
||||
auth_state.role = Some(response.role.clone());
|
||||
auth_state.decoded_username = Some(response.username.clone());
|
||||
|
||||
// Update Dialog
|
||||
let success_message = format!(
|
||||
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
|
||||
response.username, response.user_id, response.role
|
||||
);
|
||||
// Use update_dialog_content if loading dialog is shown, otherwise show_dialog
|
||||
app_state.update_dialog_content( // Assuming loading dialog was shown
|
||||
&success_message,
|
||||
vec!["Menu".to_string(), "Exit".to_string()],
|
||||
DialogPurpose::LoginSuccess,
|
||||
);
|
||||
info!(message = %success_message, "Login successful");
|
||||
}
|
||||
LoginResult::Failure(err_msg) => {
|
||||
app_state.update_dialog_content( // Update loading dialog
|
||||
&err_msg,
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginFailed,
|
||||
);
|
||||
login_state.error_message = Some(err_msg.clone()); // Keep error message
|
||||
error!(error = %err_msg, "Login failed");
|
||||
}
|
||||
LoginResult::ConnectionError(err_msg) => {
|
||||
app_state.update_dialog_content( // Update loading dialog
|
||||
&err_msg, // Show connection error
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginFailed,
|
||||
);
|
||||
login_state.error_message = Some(err_msg.clone());
|
||||
error!(error = %err_msg, "Login connection error");
|
||||
}
|
||||
}
|
||||
// Clear login form state regardless of outcome now that it's processed
|
||||
login_state.username.clear();
|
||||
login_state.password.clear();
|
||||
login_state.set_has_unsaved_changes(false);
|
||||
login_state.current_cursor_pos = 0;
|
||||
needs_redraw = true;
|
||||
}
|
||||
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
error!("Login result channel disconnected unexpectedly.");
|
||||
// Optionally show an error dialog here
|
||||
}
|
||||
}
|
||||
|
||||
// --- Check for Register Results from Channel ---
|
||||
match register_result_receiver.try_recv() {
|
||||
Ok(register_result) => {
|
||||
// A result arrived from the register task!
|
||||
match register_result {
|
||||
RegisterResult::Success(response) => {
|
||||
// Update Dialog
|
||||
let success_message = format!(
|
||||
"Registration Successful!\n\nUser ID: {}\nUsername: {}\nEmail: {}\nRole: {}",
|
||||
response.id, response.username, response.email, response.role
|
||||
);
|
||||
app_state.update_dialog_content( // Update loading dialog
|
||||
&success_message,
|
||||
vec!["OK".to_string()], // Simple OK for now
|
||||
DialogPurpose::RegisterSuccess,
|
||||
);
|
||||
info!(message = %success_message, "Registration successful");
|
||||
}
|
||||
RegisterResult::Failure(err_msg) => {
|
||||
app_state.update_dialog_content( // Update loading dialog
|
||||
&err_msg,
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::RegisterFailed,
|
||||
);
|
||||
register_state.error_message = Some(err_msg.clone()); // Keep error message
|
||||
error!(error = %err_msg, "Registration failed");
|
||||
}
|
||||
RegisterResult::ConnectionError(err_msg) => {
|
||||
app_state.update_dialog_content( // Update loading dialog
|
||||
&err_msg, // Show connection error
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::RegisterFailed, // Still a failure from user perspective
|
||||
);
|
||||
register_state.error_message = Some(err_msg.clone());
|
||||
error!(error = %err_msg, "Registration connection error");
|
||||
}
|
||||
}
|
||||
register_state.set_has_unsaved_changes(false); // Clear unsaved changes flag after processing
|
||||
needs_redraw = true; // Set flag: Register result processed, UI state (dialog) changed
|
||||
}
|
||||
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
error!("Register result channel disconnected unexpectedly.");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Centralized Consequence Handling ---
|
||||
let mut should_exit = false;
|
||||
match event_outcome_result {
|
||||
@@ -256,6 +338,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// --- Position Change Handling (after outcome processing and pending actions) ---
|
||||
let position_changed = app_state.current_position != position_before_event;
|
||||
let current_total_count = app_state.total_count;
|
||||
let mut position_logic_needs_redraw = false;
|
||||
if app_state.ui.show_form {
|
||||
if position_changed && !event_handler.is_edit_mode {
|
||||
let current_input = form_state.get_current_input();
|
||||
@@ -266,6 +349,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
};
|
||||
form_state.current_cursor_pos =
|
||||
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||
position_logic_needs_redraw = true;
|
||||
|
||||
// Ensure position never exceeds total_count + 1
|
||||
if app_state.current_position > current_total_count + 1 {
|
||||
@@ -286,7 +370,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
&mut form_state,
|
||||
current_position_to_load,
|
||||
)
|
||||
.await?;
|
||||
.await.with_context(|| format!("Failed to load adresar by position: {}", current_position_to_load))?;
|
||||
|
||||
let current_input = form_state.get_current_input();
|
||||
let max_cursor_pos = if !event_handler.is_edit_mode
|
||||
@@ -346,6 +430,9 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
||||
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||
}
|
||||
}
|
||||
if position_logic_needs_redraw {
|
||||
needs_redraw = true;
|
||||
}
|
||||
// --- End Position Change Handling ---
|
||||
|
||||
// Check exit condition *after* all processing for the iteration
|
||||
|
||||
Reference in New Issue
Block a user