Compare commits

...

22 Commits

Author SHA1 Message Date
filipriec
8a248cab58 working finally 2025-03-24 18:57:59 +01:00
filipriec
e6851e1fe4 small error to fix 2025-03-24 17:14:12 +01:00
filipriec
65ff1256aa canvas common needs redesign, sidebar displaying even when no profile selected 2025-03-24 16:46:02 +01:00
filipriec
36dc4302a0 sidebar if there is no profile selected 2025-03-24 16:15:55 +01:00
filipriec
938a1f16f1 form component is now in the separate component 2025-03-24 15:57:41 +01:00
filipriec
355aff3032 working perfectly well right now 2025-03-24 15:13:57 +01:00
filipriec
3bb771187a admin bug fixed, time for intro also 2025-03-24 15:09:35 +01:00
filipriec
aa3ff18f9c now for common in canvas 2025-03-24 14:54:02 +01:00
filipriec
1fc9a0e1ff reorganization, preserved functionality 2025-03-24 14:29:28 +01:00
filipriec
cdac78c1bc needs to reset the render but it finally works 2025-03-24 14:17:44 +01:00
filipriec
bdb6cd4069 modes needs more progress 2025-03-24 11:46:33 +01:00
filipriec
ec5802b3a2 works 2025-03-24 11:17:59 +01:00
filipriec
1eb2edc1df mode manager finally 2025-03-24 11:03:52 +01:00
filipriec
2da009eede marked bloat 2025-03-24 00:06:44 +01:00
filipriec
b2fd44df49 working select setting the form to true in state state.rs 2025-03-23 22:41:18 +01:00
filipriec
78e8cce08b moved to common modes 2025-03-23 22:14:24 +01:00
filipriec
2cf4cd6748 appstate for form 2025-03-23 22:08:33 +01:00
filipriec
7caa4d8c3c general mode 2025-03-23 21:00:53 +01:00
filipriec
9917195fc4 disabling modes where they shouldnt be enabled BIG UPDATE 2025-03-23 20:07:47 +01:00
filipriec
fbcea1b270 trying to make the intro and admin with general keybindings 2025-03-23 19:17:42 +01:00
filipriec
87b07db26a completely broken intro or admin 2025-03-23 15:35:57 +01:00
filipriec
4481560025 HUGE CHANGES TO MODESA 2025-03-23 15:11:43 +01:00
26 changed files with 610 additions and 320 deletions

View File

@@ -3,14 +3,15 @@
enter_command_mode = [":", "ctrl+;"] enter_command_mode = [":", "ctrl+;"]
[keybindings.intro] [keybindings.general]
next_option = ["j", "Right"] move_up = ["k", "Up"]
previous_option = ["k", "Left"] move_down = ["j", "Down"]
next_option = ["l", "Right"]
previous_option = ["h", "Left"]
select = ["Enter"] select = ["Enter"]
toggle_sidebar = ["ctrl+t"]
[keybindings.admin] next_field = ["Tab"]
move_up = ["k"] prev_field = ["Shift+Tab"]
move_down = ["j"]
[keybindings.common] [keybindings.common]
save = ["ctrl+s"] save = ["ctrl+s"]

View File

@@ -0,0 +1,4 @@
// src/components/form.rs
pub mod form;
pub use form::*;

View File

@@ -7,7 +7,7 @@ use ratatui::{
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::ui::form::FormState; use crate::ui::form::FormState;
use super::canvas::render_canvas; // Changed to canvas use crate::components::handlers::canvas::render_canvas;
pub fn render_form( pub fn render_form(
f: &mut Frame, f: &mut Frame,

View File

@@ -1,8 +1,6 @@
// src/components/handlers.rs // src/components/handlers.rs
pub mod form;
pub mod canvas; pub mod canvas;
pub mod sidebar; pub mod sidebar;
pub use form::*;
pub use canvas::*; pub use canvas::*;
pub use sidebar::*; pub use sidebar::*;

View File

@@ -9,7 +9,8 @@ use crate::config::colors::themes::Theme;
use common::proto::multieko2::table_definition::{ProfileTreeResponse}; use common::proto::multieko2::table_definition::{ProfileTreeResponse};
use ratatui::text::{Span, Line}; use ratatui::text::{Span, Line};
const SIDEBAR_WIDTH: u16 = 16; // Reduced sidebar width
const SIDEBAR_WIDTH: u16 = 12;
pub fn calculate_sidebar_layout(show_sidebar: bool, main_content_area: Rect) -> (Option<Rect>, Rect) { pub fn calculate_sidebar_layout(show_sidebar: bool, main_content_area: Rect) -> (Option<Rect>, Rect) {
if show_sidebar { if show_sidebar {
@@ -37,46 +38,72 @@ pub fn render_sidebar(
let mut items = Vec::new(); let mut items = Vec::new();
if let Some(profile_name) = selected_profile { if let Some(profile_name) = selected_profile {
if let Some(profile) = profile_tree.profiles.iter() // Existing code for when a profile is selected...
.find(|p| &p.name == profile_name) } else {
{ // Show full profile tree when no profile is selected (compact version)
// Profile header for (profile_idx, profile) in profile_tree.profiles.iter().enumerate() {
// Profile header - more compact
items.push(ListItem::new(Line::from(vec![ items.push(ListItem::new(Line::from(vec![
Span::styled("📁 ", Style::default().fg(theme.accent)), Span::styled("", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)), Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]))); ])));
// Tables // Tables with compact prefixes
for (table_idx, table) in profile.tables.iter().enumerate() { for (table_idx, table) in profile.tables.iter().enumerate() {
let is_last = table_idx == profile.tables.len() - 1; let is_last_table = table_idx == profile.tables.len() - 1;
let prefix = if is_last { "└─ " } else { "├─ " }; let is_last_profile = profile_idx == profile_tree.profiles.len() - 1;
// Shorter prefix characters
let prefix = match (is_last_profile, is_last_table) {
(true, true) => "",
(true, false) => "",
(false, true) => "│└",
(false, false) => "│├",
};
// Get table name without year prefix to save space
let display_name = if table.name.starts_with("2025_") {
&table.name[5..] // Skip "2025_" prefix
} else {
&table.name
};
let mut line = vec![ let mut line = vec![
Span::styled(format!(" {}", prefix), Style::default().fg(theme.fg)), Span::styled(prefix, Style::default().fg(theme.fg)),
Span::styled(&table.name, Style::default().fg(theme.fg)), Span::styled(display_name, Style::default().fg(theme.fg)),
]; ];
// Show a simple indicator for dependencies instead of listing them
if !table.depends_on.is_empty() { if !table.depends_on.is_empty() {
line.push(Span::styled( line.push(Span::styled(
format!("{}", table.depends_on.join(", ")), "",
Style::default().fg(theme.secondary) Style::default().fg(theme.secondary)
)); ));
} }
items.push(ListItem::new(Line::from(line))); items.push(ListItem::new(Line::from(line)));
} }
// Compact separator between profiles
if profile_idx < profile_tree.profiles.len() - 1 {
items.push(ListItem::new(Line::from(
Span::styled("", Style::default().fg(theme.secondary))
)));
}
}
if profile_tree.profiles.is_empty() {
items.push(ListItem::new(Span::styled(
"No profiles",
Style::default().fg(theme.secondary)
)));
} }
} else {
items.push(ListItem::new(Span::styled(
"No profile selected",
Style::default().fg(theme.secondary)
)));
} }
let list = List::new(items) let list = List::new(items)
.block(sidebar_block) .block(sidebar_block)
.highlight_style(Style::default().fg(theme.highlight)) .highlight_style(Style::default().fg(theme.highlight))
.highlight_symbol(">>"); .highlight_symbol(">");
f.render_widget(list, area); f.render_widget(list, area);
} }

View File

@@ -3,8 +3,10 @@ pub mod handlers;
pub mod intro; pub mod intro;
pub mod admin; pub mod admin;
pub mod common; pub mod common;
pub mod form;
pub use handlers::*; pub use handlers::*;
pub use intro::*; pub use intro::*;
pub use admin::*; pub use admin::*;
pub use common::*; pub use common::*;
pub use form::*;

View File

@@ -26,9 +26,7 @@ pub struct Config {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct ModeKeybindings { pub struct ModeKeybindings {
#[serde(default)] #[serde(default)]
pub intro: HashMap<String, Vec<String>>, pub general: HashMap<String, Vec<String>>,
#[serde(default)]
pub admin: HashMap<String, Vec<String>>,
#[serde(default)] #[serde(default)]
pub read_only: HashMap<String, Vec<String>>, pub read_only: HashMap<String, Vec<String>>,
#[serde(default)] #[serde(default)]
@@ -52,18 +50,15 @@ impl Config {
Ok(config) Ok(config)
} }
/// Gets an action for a key in Intro mode, only checking intro and global bindings
pub fn get_intro_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> { pub fn get_general_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.intro, key, modifiers) self.get_action_for_key_in_mode(&self.keybindings.general, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers)) .or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
} }
/// Gets an action for a key in Admin mode, checking common and global bindings /// Common actions for Edit/Read-only modes
pub fn get_admin_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> { pub fn get_common_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.admin, key, modifiers) self.get_action_for_key_in_mode(&self.keybindings.common, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.common, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.intro, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
} }
/// Gets an action for a key in Read-Only mode, also checking common keybindings. /// Gets an action for a key in Read-Only mode, also checking common keybindings.
@@ -92,17 +87,17 @@ impl Config {
&self, &self,
is_edit_mode: bool, is_edit_mode: bool,
command_mode: bool, command_mode: bool,
show_intro: bool,
show_admin: bool,
key: KeyCode, key: KeyCode,
modifiers: KeyModifiers modifiers: KeyModifiers
) -> Option<&str> { ) -> Option<&str> {
match (show_intro, show_admin, command_mode, is_edit_mode) { match (command_mode, is_edit_mode) {
(true, _, _, _) => self.get_intro_action(key, modifiers), (true, _) => self.get_command_action_for_key(key, modifiers),
(_, true, _, _) => self.get_admin_action(key, modifiers), (_, true) => self.get_edit_action_for_key(key, modifiers)
(_, _, true, _) => self.get_command_action_for_key(key, modifiers), .or_else(|| self.get_common_action(key, modifiers)),
(_, _, _, true) => self.get_edit_action_for_key(key, modifiers), _ => self.get_read_only_action_for_key(key, modifiers)
_ => self.get_read_only_action_for_key(key, modifiers), .or_else(|| self.get_common_action(key, modifiers))
// Add global bindings check for read-only mode
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers)),
} }
} }

View File

@@ -1,9 +1,83 @@
// src/modes/canvas/common.rs // src/modes/canvas/common.rs
use crossterm::event::{KeyEvent};
use crate::config::binds::config::Config;
use crate::tui::terminal::grpc_client::GrpcClient; use crate::tui::terminal::grpc_client::GrpcClient;
use crate::tui::terminal::core::TerminalCore;
use crate::tui::controls::commands::CommandHandler;
use crate::ui::handlers::form::FormState; use crate::ui::handlers::form::FormState;
use crate::state::state::AppState;
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest}; use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
/// Main handler for common core actions
pub async fn handle_core_action(
action: &str,
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
command_handler: &mut CommandHandler,
terminal: &mut TerminalCore,
app_state: &mut AppState,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"save" => {
let message = save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
Ok((false, message))
},
"force_quit" => {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".to_string()))
},
"save_and_quit" => {
let message = save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
terminal.cleanup()?;
Ok((true, format!("{}. Exiting application.", message)))
},
"revert" => {
let message = revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
Ok((false, message))
},
// We should never hit this case with proper filtering
_ => Ok((false, format!("Core action not handled: {}", action))),
}
}
/// Helper function to check if a key event should trigger a core action
pub fn is_core_action(config: &Config, key_code: crossterm::event::KeyCode, modifiers: crossterm::event::KeyModifiers) -> Option<String> {
// Check for core application actions (save, quit, etc.)
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" | "force_quit" | "save_and_quit" | "revert" => {
return Some(action.to_string())
},
_ => {} // Other actions are handled by their respective mode handlers
}
}
None
}
/// Shared logic for saving the current form state /// Shared logic for saving the current form state
pub async fn save( pub async fn save(
form_state: &mut FormState, form_state: &mut FormState,
@@ -65,64 +139,6 @@ pub async fn save(
Ok(message) Ok(message)
} }
/// Shared logic for force quitting the application
pub fn force_quit() -> (bool, String) {
(true, "Force quitting application".to_string())
}
/// Shared logic for saving and quitting
pub async fn save_and_quit(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
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 _ = grpc_client.post_adresar(post_request).await?;
} 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?;
}
Ok((true, "Saved and exiting application".to_string()))
}
/// Discard changes since last save /// Discard changes since last save
pub async fn revert( pub async fn revert(
form_state: &mut FormState, form_state: &mut FormState,

View File

@@ -1,5 +1,6 @@
// src/modes/canvas/edit.rs // src/modes/canvas/edit.rs
// 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::{ use crate::tui::terminal::{
grpc_client::GrpcClient, grpc_client::GrpcClient,

View File

@@ -0,0 +1,3 @@
// src/client/modes/common.rs
pub mod command_mode;
pub mod highlight;

View File

@@ -4,6 +4,8 @@ use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::grpc_client::GrpcClient; use crate::tui::terminal::grpc_client::GrpcClient;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState; use crate::ui::handlers::form::FormState;
use crate::tui::controls::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore;
use crate::modes::{ use crate::modes::{
canvas::{common}, canvas::{common},
}; };
@@ -15,7 +17,8 @@ pub async fn handle_command_event(
command_input: &mut String, command_input: &mut String,
command_message: &mut String, command_message: &mut String,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
is_saved: &mut bool, command_handler: &mut CommandHandler,
terminal: &mut TerminalCore,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> { ) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
@@ -37,7 +40,8 @@ pub async fn handle_command_event(
command_input, command_input,
command_message, command_message,
grpc_client, grpc_client,
is_saved, command_handler,
terminal,
current_position, current_position,
total_count, total_count,
).await; ).await;
@@ -68,7 +72,8 @@ async fn process_command(
command_input: &mut String, command_input: &mut String,
command_message: &mut String, command_message: &mut String,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
is_saved: &mut bool, command_handler: &mut CommandHandler,
terminal: &mut TerminalCore,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> { ) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
@@ -84,32 +89,24 @@ async fn process_command(
.unwrap_or("unknown"); .unwrap_or("unknown");
match action { match action {
"force_quit" | "save_and_quit" | "quit" => {
let (should_exit, message) = command_handler
.handle_command(action, terminal)
.await?;
command_input.clear();
Ok((should_exit, message, true))
},
"save" => { "save" => {
let message = common::save( let message = common::save(
form_state, form_state,
grpc_client, grpc_client,
is_saved, &mut command_handler.is_saved,
current_position, current_position,
total_count, total_count,
).await?; ).await?;
command_input.clear(); command_input.clear();
return Ok((false, message, true)); return Ok((false, message, true));
}, },
"force_quit" => {
let (should_exit, message) = common::force_quit();
command_input.clear();
return Ok((should_exit, message, true));
},
"save_and_quit" => {
let (should_exit, message) = common::save_and_quit(
form_state,
grpc_client,
current_position,
total_count,
).await?;
command_input.clear();
return Ok((should_exit, message, true));
},
"revert" => { "revert" => {
let message = common::revert( let message = common::revert(
form_state, form_state,

View File

@@ -0,0 +1,2 @@
// src/client/modes/general.rs
pub mod navigation;

View File

@@ -0,0 +1,175 @@
// src/modes/general/navigation.rs
use crossterm::event::KeyEvent;
use crate::config::binds::config::Config;
use crate::state::state::AppState;
use crate::ui::handlers::form::FormState;
pub async fn handle_navigation_event(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
app_state: &mut AppState,
command_mode: &mut bool,
command_input: &mut String,
command_message: &mut String,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
match action {
"move_up" => {
move_up(app_state);
return Ok((false, String::new()));
}
"move_down" => {
let item_count = if app_state.ui.show_intro {
2 // Intro options count
} else {
app_state.profile_tree.profiles.len() // Admin panel items
};
move_down(app_state, item_count);
return Ok((false, String::new()));
}
"next_option" => {
next_option(app_state, 2); // Intro has 2 options
return Ok((false, String::new()));
}
"previous_option" => {
previous_option(app_state);
return Ok((false, String::new()));
}
"select" => {
select(app_state);
return Ok((false, "Selected".to_string()));
}
"toggle_sidebar" => {
toggle_sidebar(app_state);
return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
"next_field" => {
next_field(form_state);
return Ok((false, String::new()));
}
"prev_field" => {
prev_field(form_state);
return Ok((false, String::new()));
}
"enter_command_mode" => {
handle_enter_command_mode(command_mode, command_input, command_message);
return Ok((false, String::new()));
}
_ => {}
}
}
Ok((false, String::new()))
}
pub fn move_up(app_state: &mut AppState) {
if app_state.ui.show_intro {
app_state.ui.intro_state.previous_option();
} else if app_state.ui.show_admin {
// Assuming profile_tree.profiles is the list we're navigating
let profile_count = app_state.profile_tree.profiles.len();
if profile_count == 0 {
return;
}
// Use general state for tracking selection in admin panel
if app_state.general.selected_item == 0 {
app_state.general.selected_item = profile_count - 1;
} else {
app_state.general.selected_item = app_state.general.selected_item.saturating_sub(1);
}
}
}
pub fn move_down(app_state: &mut AppState, item_count: usize) {
if app_state.ui.show_intro {
app_state.ui.intro_state.next_option();
} else if app_state.ui.show_admin {
// Assuming profile_tree.profiles is the list we're navigating
let profile_count = app_state.profile_tree.profiles.len();
if profile_count == 0 {
return;
}
app_state.general.selected_item = (app_state.general.selected_item + 1) % profile_count;
}
}
pub fn next_option(app_state: &mut AppState, option_count: usize) {
if app_state.ui.show_intro {
app_state.ui.intro_state.next_option();
} else {
// For other screens that might have options
app_state.general.current_option = (app_state.general.current_option + 1) % option_count;
}
}
pub fn previous_option(app_state: &mut AppState) {
if app_state.ui.show_intro {
app_state.ui.intro_state.previous_option();
} else {
// For other screens that might have options
if app_state.general.current_option == 0 {
// We'd need the option count here, but since it's not passed we can't wrap around correctly
// For now, just stay at 0
} else {
app_state.general.current_option -= 1;
}
}
}
pub fn select(app_state: &mut AppState) {
if app_state.ui.show_intro {
// Handle selection in intro screen
if app_state.ui.intro_state.selected_option == 0 {
// First option selected - show form
app_state.ui.show_form = true;
app_state.ui.show_admin = false;
} else {
// Second option selected - show admin
app_state.ui.show_form = false;
app_state.ui.show_admin = true;
}
app_state.ui.show_intro = false;
} else if app_state.ui.show_admin {
// Handle selection in admin panel
let profiles = &app_state.profile_tree.profiles;
if !profiles.is_empty() && app_state.general.selected_item < profiles.len() {
// Set the selected profile
app_state.selected_profile = Some(profiles[app_state.general.selected_item].name.clone());
}
}
}
pub fn toggle_sidebar(app_state: &mut AppState) {
app_state.ui.show_sidebar = !app_state.ui.show_sidebar;
}
pub fn next_field(form_state: &mut FormState) {
if !form_state.fields.is_empty() {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
}
}
pub fn prev_field(form_state: &mut FormState) {
if !form_state.fields.is_empty() {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field -= 1;
}
}
}
pub fn handle_enter_command_mode(
command_mode: &mut bool,
command_input: &mut String,
command_message: &mut String
) {
*command_mode = true;
command_input.clear();
command_message.clear();
}

View File

@@ -1,3 +1,3 @@
// src/client/modes/handlers.rs // src/client/modes/handlers.rs
pub mod event; pub mod event;
pub mod command_mode; pub mod mode_manager;

View File

@@ -1,19 +1,21 @@
// src/modes/handlers/event.rs // src/modes/handlers/event.rs
use crossterm::event::Event; use crossterm::event::{Event, KeyEvent};
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::{ use crate::tui::terminal::{
core::TerminalCore, core::TerminalCore,
grpc_client::GrpcClient, grpc_client::GrpcClient,
commands::CommandHandler,
}; };
use crate::tui::controls::commands::CommandHandler;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState; use crate::ui::handlers::form::FormState;
use crate::ui::handlers::rat_state::UiStateHandler; use crate::ui::handlers::rat_state::UiStateHandler;
use crate::modes::{ use crate::modes::{
handlers::{command_mode}, common::{command_mode},
canvas::{edit, read_only, common}, canvas::{edit, read_only, common},
general::navigation,
}; };
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::modes::handlers::mode_manager::{ModeManager, AppMode};
pub struct EventHandler { pub struct EventHandler {
pub command_mode: bool, pub command_mode: bool,
@@ -49,60 +51,112 @@ impl EventHandler {
app_state: &mut crate::state::state::AppState, app_state: &mut crate::state::state::AppState,
total_count: u64, total_count: u64,
current_position: &mut u64, current_position: &mut u64,
intro_state: &mut crate::components::intro::intro::IntroState,
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
if app_state.ui.show_intro { // Determine current mode based on app state and event handler state
if let Event::Key(key) = event { let current_mode = ModeManager::derive_mode(app_state, self);
let action = config.get_intro_action(key.code, key.modifiers); app_state.update_mode(current_mode);
match action { if let Event::Key(key) = event {
Some("previous_option") => intro_state.previous_option(), let key_code = key.code;
Some("next_option") => intro_state.next_option(), let modifiers = key.modifiers;
Some("select") => {
app_state.ui.show_intro = false; // Handle common actions across all modes
app_state.ui.show_admin = intro_state.selected_option == 1; if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) {
}, return Ok((false, format!("Sidebar {}",
_ => {} // Ignore all other keys if app_state.ui.show_sidebar { "shown" } else { "hidden" }
} )));
} }
return Ok((false, String::new()));
}
if let Event::Key(key) = event { // Mode-specific handling
let key_code = key.code; match current_mode {
let modifiers = key.modifiers; AppMode::General => {
return navigation::handle_navigation_event(
key,
config,
form_state,
app_state,
&mut self.command_mode,
&mut self.command_input,
&mut self.command_message,
).await;
},
// Handle admin panel mode AppMode::ReadOnly => {
if app_state.ui.show_admin { // Check for mode transitions first
if let Some(action) = config.get_admin_action(key_code, modifiers) { if config.is_enter_edit_mode_before(key_code, modifiers) &&
match action { ModeManager::can_enter_edit_mode(current_mode) {
"move_up" => { self.is_edit_mode = true;
// Handle up movement using app_state directly self.edit_mode_cooldown = true;
app_state.admin_selected_item = app_state.admin_selected_item.saturating_sub(1); self.command_message = "Edit mode".to_string();
} terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
"move_down" => { return Ok((false, self.command_message.clone()));
// Handle down movement using app_state
app_state.admin_selected_item = app_state.admin_selected_item.saturating_add(1);
}
_ => {}
}
return Ok((false, format!("Admin: {}", action)));
} }
return Ok((false, String::new()));
}
if UiStateHandler::toggle_sidebar(
&mut app_state.ui,
config,
key_code,
modifiers,
) {
return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
// Handle edit mode first to allow normal character input if config.is_enter_edit_mode_after(key_code, modifiers) &&
if self.is_edit_mode { ModeManager::can_enter_edit_mode(current_mode) {
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
}
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode (after cursor)".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok((false, self.command_message.clone()));
}
// Check for entering command mode
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok((false, String::new()));
}
}
// Check for core application actions (save, quit, etc.)
// ONLY handle a limited subset of core actions here
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 common::handle_core_action(
action,
form_state,
grpc_client,
command_handler,
terminal,
app_state,
current_position,
total_count,
).await;
},
_ => {} // For other actions, let the mode-specific handler take care of it
}
}
// Let read_only mode handle its own actions (including navigation from common bindings)
return read_only::handle_read_only_event(
key,
config,
form_state,
&mut self.key_sequence_tracker,
current_position,
total_count,
grpc_client,
&mut self.command_message,
&mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column,
).await;
},
AppMode::Edit => {
// Check for exiting edit mode
if config.is_exit_edit_mode(key_code, modifiers) { if config.is_exit_edit_mode(key_code, modifiers) {
if form_state.has_unsaved_changes { if form_state.has_unsaved_changes {
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string(); self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
@@ -121,6 +175,31 @@ impl EventHandler {
return Ok((false, self.command_message.clone())); return Ok((false, self.command_message.clone()));
} }
// Check for core application actions (save, quit, etc.)
// ONLY handle a limited subset of core actions here
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 common::handle_core_action(
action,
form_state,
grpc_client,
command_handler,
terminal,
app_state,
current_position,
total_count,
).await;
},
_ => {} // For other actions, let the mode-specific handler take care of it
}
}
// Let edit mode handle its own actions (including navigation from common bindings)
let result = edit::handle_edit_event_internal( let result = edit::handle_edit_event_internal(
key, key,
config, config,
@@ -135,63 +214,9 @@ impl EventHandler {
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok((false, result)); return Ok((false, result));
} },
// Global command mode activation AppMode::Command => {
let context_action = config.get_action_for_current_context(
self.is_edit_mode,
self.command_mode,
app_state.ui.show_intro,
app_state.ui.show_admin,
key_code,
modifiers
);
if let Some("enter_command_mode") = context_action {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok((false, String::new()));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" => {
let message = common::save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
return Ok((false, message));
},
"force_quit" => {
let (should_exit, message) = command_handler.handle_command("force_quit", terminal).await?;
return Ok((should_exit, message));
},
"save_and_quit" => {
let (should_exit, message) = command_handler.handle_command("save_and_quit", terminal).await?;
return Ok((should_exit, message));
},
"revert" => {
let message = common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
return Ok((false, message));
},
_ => {}
}
}
if self.command_mode {
let (should_exit, message, exit_command_mode) = command_mode::handle_command_event( let (should_exit, message, exit_command_mode) = command_mode::handle_command_event(
key, key,
config, config,
@@ -199,7 +224,8 @@ impl EventHandler {
&mut self.command_input, &mut self.command_input,
&mut self.command_message, &mut self.command_message,
grpc_client, grpc_client,
&mut app_state.ui.is_saved, command_handler,
terminal,
current_position, current_position,
total_count, total_count,
).await?; ).await?;
@@ -210,52 +236,13 @@ impl EventHandler {
return Ok((should_exit, message)); return Ok((should_exit, message));
} }
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
if action == "enter_command_mode" {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok((false, String::new()));
}
}
if config.is_enter_edit_mode_before(key_code, modifiers) {
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok((false, self.command_message.clone()));
}
if config.is_enter_edit_mode_after(key_code, modifiers) {
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
}
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode (after cursor)".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok((false, self.command_message.clone()));
}
return read_only::handle_read_only_event(
key,
config,
form_state,
&mut self.key_sequence_tracker,
current_position,
total_count,
grpc_client,
&mut self.command_message,
&mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column,
).await;
} }
}
// Non-key events or if no specific handler was matched
self.edit_mode_cooldown = false; self.edit_mode_cooldown = false;
Ok((false, self.command_message.clone())) Ok((false, self.command_message.clone()))
} }
} }

View File

@@ -0,0 +1,50 @@
// src/modes/handlers/mode_manager.rs
use crate::state::state::AppState;
use crate::modes::handlers::event::EventHandler;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
General, // For intro and admin screens
ReadOnly, // Canvas read-only mode
Edit, // Canvas edit mode
Command, // Command mode overlay
}
pub struct ModeManager;
impl ModeManager {
// Determine current mode based on app state
pub fn derive_mode(app_state: &AppState, event_handler: &EventHandler) -> AppMode {
// Command mode takes precedence if active
if event_handler.command_mode {
return AppMode::Command;
}
// Check UI state flags
if app_state.ui.show_intro || app_state.ui.show_admin {
AppMode::General
} else if app_state.ui.show_form {
if event_handler.is_edit_mode {
AppMode::Edit
} else {
AppMode::ReadOnly
}
} else {
// Fallback
AppMode::General
}
}
// Mode transition rules
pub fn can_enter_command_mode(current_mode: AppMode) -> bool {
!matches!(current_mode, AppMode::Edit) // Can't enter from Edit mode
}
pub fn can_enter_edit_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::ReadOnly) // Only from ReadOnly
}
pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::Edit | AppMode::Command)
}
}

View File

@@ -1,6 +1,10 @@
// src/client/modes/mod.rs // src/client/modes/mod.rs
pub mod handlers; pub mod handlers;
pub mod canvas; pub mod canvas;
pub mod general;
pub mod common;
pub use handlers::*; pub use handlers::*;
pub use canvas::*; pub use canvas::*;
pub use general::*;
pub use common::*;

View File

@@ -2,12 +2,21 @@
use std::env; use std::env;
use common::proto::multieko2::table_definition::ProfileTreeResponse; use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::components::IntroState;
use crate::modes::handlers::mode_manager::AppMode;
pub struct UiState { pub struct UiState {
pub show_sidebar: bool, pub show_sidebar: bool,
pub is_saved: bool, pub is_saved: bool,
pub show_intro: bool, pub show_intro: bool,
pub show_admin: bool, pub show_admin: bool,
pub show_form: bool,
pub intro_state: IntroState,
}
pub struct GeneralState {
pub selected_item: usize,
pub current_option: usize,
} }
pub struct AppState { pub struct AppState {
@@ -17,11 +26,11 @@ pub struct AppState {
pub current_position: u64, pub current_position: u64,
pub profile_tree: ProfileTreeResponse, pub profile_tree: ProfileTreeResponse,
pub selected_profile: Option<String>, pub selected_profile: Option<String>,
pub admin_selected_item: usize, // Tracks selection in admin panel pub current_mode: AppMode,
pub admin_profiles: Vec<String>, // Stores admin panel data
// UI preferences // UI preferences
pub ui: UiState, pub ui: UiState,
pub general: GeneralState,
} }
impl AppState { impl AppState {
@@ -35,9 +44,12 @@ impl AppState {
current_position: 0, current_position: 0,
profile_tree: ProfileTreeResponse::default(), profile_tree: ProfileTreeResponse::default(),
selected_profile: None, selected_profile: None,
admin_selected_item: 0, current_mode: AppMode::General,
admin_profiles: Vec::new(),
ui: UiState::default(), ui: UiState::default(),
general: GeneralState {
selected_item: 0,
current_option: 0,
},
}) })
} }
@@ -49,6 +61,10 @@ impl AppState {
pub fn update_current_position(&mut self, current_position: u64) { pub fn update_current_position(&mut self, current_position: u64) {
self.current_position = current_position; self.current_position = current_position;
} }
pub fn update_mode(&mut self, mode: AppMode) {
self.current_mode = mode;
}
} }
impl Default for UiState { impl Default for UiState {
@@ -58,6 +74,8 @@ impl Default for UiState {
is_saved: false, is_saved: false,
show_intro: true, show_intro: true,
show_admin: false, show_admin: false,
show_form: false,
intro_state: IntroState::new(),
} }
} }
} }

View File

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

View File

@@ -1,9 +1,8 @@
// src/tui/terminal/commands.rs // src/tui/controls/commands.rs
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
pub struct CommandHandler { pub struct CommandHandler {
is_saved: bool, pub is_saved: bool,
} }
impl CommandHandler { impl CommandHandler {
@@ -24,7 +23,10 @@ impl CommandHandler {
} }
} }
async fn handle_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> { async fn handle_quit(
&self,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
if self.is_saved { if self.is_saved {
terminal.cleanup()?; terminal.cleanup()?;
Ok((true, "Exiting.".into())) Ok((true, "Exiting.".into()))
@@ -33,12 +35,18 @@ impl CommandHandler {
} }
} }
async fn handle_force_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> { async fn handle_force_quit(
&self,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
terminal.cleanup()?; terminal.cleanup()?;
Ok((true, "Force exiting without saving.".into())) Ok((true, "Force exiting without saving.".into()))
} }
async fn handle_save_quit(&mut self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> { async fn handle_save_quit(
&mut self,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
self.is_saved = true; self.is_saved = true;
terminal.cleanup()?; terminal.cleanup()?;
Ok((true, "State saved. Exiting.".into())) Ok((true, "State saved. Exiting.".into()))

View File

@@ -1,2 +1,4 @@
// src/tui/mod.rs // src/tui/mod.rs
pub mod terminal; pub mod terminal;
pub mod controls;

View File

@@ -2,10 +2,8 @@
pub mod core; pub mod core;
pub mod grpc_client; pub mod grpc_client;
pub mod commands;
pub mod event_reader; pub mod event_reader;
pub use core::TerminalCore; pub use core::TerminalCore;
pub use grpc_client::GrpcClient; pub use grpc_client::GrpcClient;
pub use commands::CommandHandler;
pub use event_reader::EventReader; pub use event_reader::EventReader;

View File

@@ -38,7 +38,7 @@ impl FormState {
let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect(); let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect();
let values: Vec<&String> = self.values.iter().collect(); let values: Vec<&String> = self.values.iter().collect();
crate::components::handlers::form::render_form( crate::components::form::form::render_form(
f, f,
area, area,
self, self,

View File

@@ -4,7 +4,8 @@ use crate::components::{
render_background, render_background,
render_command_line, render_command_line,
render_status_line, render_status_line,
handlers::{sidebar::{self, calculate_sidebar_layout}, form::render_form}, handlers::sidebar::{self, calculate_sidebar_layout},
form::form::render_form,
intro::{intro}, intro::{intro},
admin::{admin_panel::AdminPanelState}, admin::{admin_panel::AdminPanelState},
}; };
@@ -26,7 +27,7 @@ pub fn render_ui(
command_mode: bool, command_mode: bool,
command_message: &str, command_message: &str,
app_state: &AppState, app_state: &AppState,
intro_state: &intro::IntroState, // intro_state parameter removed
) { ) {
render_background(f, f.area(), theme); render_background(f, f.area(), theme);
@@ -41,25 +42,24 @@ pub fn render_ui(
let main_content_area = root[0]; let main_content_area = root[0];
if app_state.ui.show_intro { if app_state.ui.show_intro {
intro_state.render(f, main_content_area, theme); // Use app_state's intro_state directly
app_state.ui.intro_state.render(f, main_content_area, theme);
} 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(
if app_state.admin_profiles.is_empty() { app_state.profile_tree.profiles
// Fallback if admin_profiles is empty .iter()
app_state.profile_tree.profiles .map(|p| p.name.clone())
.iter() .collect()
.map(|p| p.name.clone())
.collect()
} else {
app_state.admin_profiles.clone()
}
); );
// Set the selected item // Set the selected item - FIXED
if !admin_state.profiles.is_empty() { if !admin_state.profiles.is_empty() {
let safe_index = app_state.admin_selected_item.min(admin_state.profiles.len() - 1); let selected_index = std::cmp::min(
admin_state.list_state.select(Some(safe_index)); app_state.general.selected_item,
admin_state.profiles.len() - 1
);
admin_state.list_state.select(Some(selected_index));
} }
admin_state.render( admin_state.render(
@@ -69,7 +69,7 @@ pub fn render_ui(
&app_state.profile_tree, &app_state.profile_tree,
&app_state.selected_profile, &app_state.selected_profile,
); );
} else { } else if app_state.ui.show_form {
let (sidebar_area, form_area) = calculate_sidebar_layout( let (sidebar_area, form_area) = calculate_sidebar_layout(
app_state.ui.show_sidebar, app_state.ui.show_sidebar,
main_content_area main_content_area
@@ -81,7 +81,7 @@ pub fn render_ui(
sidebar_rect, sidebar_rect,
theme, theme,
&app_state.profile_tree, &app_state.profile_tree,
&app_state.selected_profile // Remove trailing comma &app_state.selected_profile
); );
} }
@@ -125,6 +125,8 @@ pub fn render_ui(
total_count, total_count,
current_position, current_position,
); );
} else{
} }
render_status_line(f, root[1], current_dir, theme, is_edit_mode); render_status_line(f, root[1], current_dir, theme, is_edit_mode);

View File

@@ -2,7 +2,7 @@
use crate::tui::terminal::TerminalCore; use crate::tui::terminal::TerminalCore;
use crate::tui::terminal::GrpcClient; use crate::tui::terminal::GrpcClient;
use crate::tui::terminal::CommandHandler; use crate::tui::controls::CommandHandler;
use crate::tui::terminal::EventReader; use crate::tui::terminal::EventReader;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
@@ -30,11 +30,8 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// Now create admin panel with profiles from app_state // Now create admin panel with profiles from app_state
if intro_state.selected_option == 1 { if intro_state.selected_option == 1 {
app_state.ui.show_admin = true; app_state.ui.show_admin = true;
app_state.admin_profiles = app_state.profile_tree.profiles app_state.general.selected_item = 0;
.iter() app_state.general.current_option = 0;
.map(|p| p.name.clone())
.collect();
app_state.admin_selected_item = 0;
} }
// Fetch table structure at startup (one-time) // Fetch table structure at startup (one-time)
@@ -77,7 +74,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
event_handler.command_mode, event_handler.command_mode,
&event_handler.command_message, &event_handler.command_message,
&app_state, &app_state,
&intro_state,
); );
})?; })?;
@@ -95,7 +91,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
&mut app_state, &mut app_state,
total_count, total_count,
&mut current_position, &mut current_position,
&mut intro_state,
).await?; ).await?;
app_state.current_position = current_position; app_state.current_position = current_position;