Compare commits

..

18 Commits

Author SHA1 Message Date
filipriec
b1b3cf6136 changes for revert save in the readonly mode and not only the edit mode finished. 2025-04-07 12:18:03 +02:00
filipriec
173c4c98b8 feat: Prevent form navigation with unsaved changes 2025-04-07 12:03:17 +02:00
filipriec
5a3067c8e5 edit to read_only mode without save 2025-04-07 10:13:39 +02:00
filipriec
803c748738 only to the top and to the bottom in the canvas, cant jump around anymore 2025-04-06 23:16:15 +02:00
filipriec
5879b40e8c exit menu buttons upon success 2025-04-05 19:42:29 +02:00
filipriec
c3decdac13 working dialog now better 2025-04-05 19:37:51 +02:00
filipriec
1baf89dde6 login with dialog menu 2025-04-05 17:52:37 +02:00
filipriec
0219dc0ede border fixed 2025-04-05 17:34:26 +02:00
filipriec
1c662888c6 minor changes 2025-04-05 17:21:07 +02:00
filipriec
7fd1c1e41d working inputting characters 2025-04-05 13:34:38 +02:00
filipriec
1eaa716f42 working now, able to switch between form_e and auth_e 2025-04-05 00:42:56 +02:00
filipriec
704bb7401a copied form_e to auth_e 2025-04-04 23:37:19 +02:00
filipriec
b0c3fdbdc6 added in here src/functions/modes/read_only/auth_ro.rs missing functions, not working tho 2025-04-04 23:34:56 +02:00
filipriec
1d0ceb7045 minor changes 2025-04-04 23:28:30 +02:00
filipriec
ce85a050d3 command mode handler moved 2025-04-04 22:34:04 +02:00
filipriec
94ecbcd639 moved common to common_mode 2025-04-04 20:49:12 +02:00
filipriec
ef1d8bcc9c fully moved now 2025-04-04 20:39:23 +02:00
filipriec
1a7bbdc541 moving back to tui nonmode functions for now 2025-04-04 20:37:02 +02:00
26 changed files with 1134 additions and 398 deletions

6
Cargo.lock generated
View File

@@ -421,7 +421,7 @@ dependencies = [
[[package]] [[package]]
name = "client" name = "client"
version = "0.2.5" version = "0.3.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"common", "common",
@@ -458,7 +458,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "0.2.5" version = "0.3.0"
dependencies = [ dependencies = [
"prost", "prost",
"serde", "serde",
@@ -2589,7 +2589,7 @@ dependencies = [
[[package]] [[package]]
name = "server" name = "server"
version = "0.2.5" version = "0.3.0"
dependencies = [ dependencies = [
"bcrypt", "bcrypt",
"chrono", "chrono",

View File

@@ -5,7 +5,7 @@ resolver = "2"
[workspace.package] [workspace.package]
# TODO: idk how to do the name, fix later # TODO: idk how to do the name, fix later
# name = "Multieko2" # name = "Multieko2"
version = "0.2.5" version = "0.3.0"
edition = "2021" edition = "2021"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
authors = ["Filip Priečinský <filippriec@gmail.com>"] authors = ["Filip Priečinský <filippriec@gmail.com>"]

View File

@@ -4,13 +4,13 @@ use crate::{
config::colors::themes::Theme, config::colors::themes::Theme,
state::pages::auth::AuthState, state::pages::auth::AuthState,
components::common::dialog, components::common::dialog,
state::state::AppState, // Add this import state::state::AppState,
}; };
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color}, // Removed unused Color import style::{Style, Modifier, Color},
widgets::{Block, BorderType, Borders, Paragraph}, widgets::{Block, BorderType, Borders, Paragraph},
Frame, // Removed unused Span import Frame,
}; };
pub fn render_login( pub fn render_login(
@@ -18,7 +18,7 @@ pub fn render_login(
area: Rect, area: Rect,
theme: &Theme, theme: &Theme,
state: &AuthState, state: &AuthState,
app_state: &AppState, // Add AppState parameter app_state: &AppState,
is_edit_mode: bool, is_edit_mode: bool,
) { ) {
// Main container // Main container
@@ -47,24 +47,9 @@ pub fn render_login(
.split(inner_area); .split(inner_area);
// --- FORM RENDERING --- // --- FORM RENDERING ---
let input_block = Block::default()
.borders(Borders::ALL)
.border_style(if is_edit_mode {
Style::default().fg(theme.accent)
} else {
Style::default().fg(theme.border)
})
.style(Style::default().bg(theme.bg));
// Calculate inner area BEFORE rendering
let input_area = input_block.inner(chunks[0]);
f.render_widget(input_block, chunks[0]);
// Use the canvas renderer for fields
crate::components::handlers::canvas::render_canvas( crate::components::handlers::canvas::render_canvas(
f, f,
input_area, // Use the pre-calculated area chunks[0],
state, state,
&["Username/Email", "Password"], &["Username/Email", "Password"],
&state.current_field, &state.current_field,
@@ -73,7 +58,17 @@ pub fn render_login(
is_edit_mode, is_edit_mode,
); );
// --- BUTTONS --- (Keep this unchanged) // --- ERROR MESSAGE ---
if let Some(err) = &state.error_message {
f.render_widget(
Paragraph::new(err.as_str())
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center),
chunks[1],
);
}
// --- BUTTONS ---
let button_chunks = Layout::default() let button_chunks = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
@@ -123,24 +118,18 @@ pub fn render_login(
button_chunks[1], button_chunks[1],
); );
// Error message // --- DIALOG ---
if let Some(err) = &state.error_message { // Check the correct field name for showing the dialog
f.render_widget( if app_state.ui.dialog.dialog_show {
Paragraph::new(err.as_str()) // Pass all 7 arguments correctly
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center),
chunks[1],
);
}
if app_state.ui.dialog.show_dialog {
dialog::render_dialog( dialog::render_dialog(
f, f,
f.area(), // Use area() instead of deprecated size() f.area(),
theme, theme,
&app_state.ui.dialog.dialog_title, &app_state.ui.dialog.dialog_title,
&app_state.ui.dialog.dialog_message, &app_state.ui.dialog.dialog_message,
app_state.ui.dialog.dialog_button_active, &app_state.ui.dialog.dialog_buttons, // Pass buttons slice
app_state.ui.dialog.dialog_active_button_index, // Pass active index
); );
} }
} }

View File

@@ -1,101 +1,146 @@
// src/components/common/dialog.rs // src/components/common/dialog.rs
use ratatui::{
layout::{Constraint, Direction, Layout, Rect, Margin},
style::{Modifier, Style},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
text::{Text, Line, Span}
};
use ratatui::prelude::Alignment;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use ratatui::{
layout::{Constraint, Direction, Layout, Margin, Rect},
prelude::Alignment,
style::{Modifier, Style},
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Paragraph, Clear}, // Added Clear
Frame,
};
pub fn render_dialog( pub fn render_dialog(
f: &mut Frame, f: &mut Frame,
area: Rect, area: Rect,
theme: &Theme, theme: &Theme,
title: &str, dialog_title: &str,
message: &str, dialog_message: &str,
is_active: bool, dialog_buttons: &[String],
dialog_active_button_index: usize,
) { ) {
// Create a centered rect for the dialog let message_lines: Vec<_> = dialog_message.lines().collect();
let dialog_area = centered_rect(60, 25, area); let message_height = message_lines.len() as u16;
let button_row_height = if dialog_buttons.is_empty() { 0 } else { 3 };
let vertical_padding = 2; // Block borders (top/bottom)
let inner_vertical_margin = 2; // Margin inside block (top/bottom)
let required_inner_height =
message_height + button_row_height + inner_vertical_margin;
// Add block border height
let required_total_height = required_inner_height + vertical_padding;
// Use a fixed percentage width, clamped to min/max
let width_percentage: u16 = 60;
let dialog_width = (area.width * width_percentage / 100)
.max(20) // Minimum width
.min(area.width); // Maximum width
// Ensure height doesn't exceed available area
let dialog_height = required_total_height.min(area.height);
// Calculate centered area manually
let dialog_x = area.x + (area.width.saturating_sub(dialog_width)) / 2;
let dialog_y = area.y + (area.height.saturating_sub(dialog_height)) / 2;
let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
// Clear the area first before drawing the dialog
f.render_widget(Clear, dialog_area);
// Main dialog container
let block = Block::default() let block = Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent)) .border_style(Style::default().fg(theme.accent))
.title(title) .title(format!(" {} ", dialog_title)) // Add padding to title
.style(Style::default().bg(theme.bg)); .style(Style::default().bg(theme.bg));
f.render_widget(&block, dialog_area); f.render_widget(block, dialog_area);
// Inner content area // Calculate inner area *after* defining the block
let inner_area = block.inner(dialog_area).inner(Margin { let inner_area = dialog_area.inner(Margin {
horizontal: 2, horizontal: 2, // Left/Right padding inside border
vertical: 1, vertical: 1, // Top/Bottom padding inside border
}); });
// Split into message and button areas // Layout for Message and Buttons
let mut constraints = vec![
// Allocate space for message, ensuring at least 1 line height
Constraint::Min(message_height.max(1)),
];
if button_row_height > 0 {
constraints.push(Constraint::Length(button_row_height));
}
let chunks = Layout::default() let chunks = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([ .constraints(constraints)
Constraint::Min(3), // Message content
Constraint::Length(3), // Button
])
.split(inner_area); .split(inner_area);
// Message text // Render Message
let message_text = Text::from(message.lines().map(|l| Line::from(Span::styled( let message_text = Text::from(
l, message_lines
Style::default().fg(theme.fg) .into_iter()
))).collect::<Vec<_>>()); .map(|l| Line::from(Span::styled(l, Style::default().fg(theme.fg))))
.collect::<Vec<_>>(),
);
let message_paragraph = Paragraph::new(message_text) let message_paragraph =
.alignment(Alignment::Center); Paragraph::new(message_text).alignment(Alignment::Center);
// Render message in the first chunk
f.render_widget(message_paragraph, chunks[0]); f.render_widget(message_paragraph, chunks[0]);
// OK Button // Render Buttons if they exist and there's a chunk for them
let button_style = if is_active { if !dialog_buttons.is_empty() && chunks.len() > 1 {
Style::default() let button_area = chunks[1];
.fg(theme.highlight) let button_count = dialog_buttons.len();
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.fg)
};
let button_block = Block::default() // Use Ratio for potentially more even distribution with few buttons
.borders(Borders::ALL) let button_constraints = std::iter::repeat(Constraint::Ratio(
.border_type(BorderType::Plain) 1,
.border_style(Style::default().fg(theme.accent)) button_count as u32,
.style(Style::default().bg(theme.bg)); ))
.take(button_count)
.collect::<Vec<_>>();
f.render_widget( let button_chunks = Layout::default()
Paragraph::new("OK") .direction(Direction::Horizontal)
.block(button_block) .constraints(button_constraints)
.style(button_style) .horizontal_margin(1) // Add space between buttons
.alignment(Alignment::Center), .split(button_area);
chunks[1],
); for (i, button_label) in dialog_buttons.iter().enumerate() {
// Ensure we don't try to render into a non-existent chunk
if i >= button_chunks.len() {
break;
}
let is_active = i == dialog_active_button_index;
let (button_style, border_style) = if is_active {
(
Style::default()
.fg(theme.highlight)
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.accent), // Highlight border
)
} else {
(
Style::default().fg(theme.fg),
Style::default().fg(theme.border), // Normal border
)
};
let button_block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(border_style);
f.render_widget(
Paragraph::new(button_label.as_str())
.block(button_block)
.style(button_style)
.alignment(Alignment::Center),
button_chunks[i],
);
}
}
} }
/// Helper function to center a rect with given percentage values
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}

View File

@@ -27,13 +27,16 @@ pub fn render_canvas(
.split(area); .split(area);
// Input container styling // Input container styling
let border_style = if form_state.has_unsaved_changes() {
Style::default().fg(theme.warning)
} else if is_edit_mode {
Style::default().fg(theme.accent)
} else {
Style::default().fg(theme.secondary)
};
let input_container = Block::default() let input_container = Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_style(if is_edit_mode { .border_style(border_style)
form_state.has_unsaved_changes().then(|| theme.warning).unwrap_or(theme.accent)
} else {
theme.secondary
})
.style(Style::default().bg(theme.bg)); .style(Style::default().bg(theme.bg));
// Input block dimensions // Input block dimensions

View File

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

View File

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

View File

@@ -0,0 +1,427 @@
// src/functions/modes/edit/auth_e.rs
use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::tui::functions::common::form::{revert, save};
use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any;
pub async fn execute_common_action<S: CanvasState + Any>(
action: &str,
state: &mut S,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" | "revert" => {
if !state.has_unsaved_changes() {
return Ok("No changes to save or revert.".to_string());
}
if let Some(form_state) =
(state as &mut dyn Any).downcast_mut::<FormState>()
{
match action {
"save" => {
save(
form_state,
grpc_client,
is_saved,
current_position,
total_count,
)
.await
}
"revert" => {
revert(
form_state,
grpc_client,
current_position,
total_count,
)
.await
}
_ => unreachable!(),
}
} else {
Ok(format!(
"Action '{}' not implemented for this state type.",
action
))
}
}
_ => Ok(format!("Common action '{}' not handled here.", action)),
}
}
pub async fn execute_edit_action<S: CanvasState>(
action: &str,
key: KeyEvent,
state: &mut S,
ideal_cursor_column: &mut usize,
_grpc_client: &mut GrpcClient,
_is_saved: &mut bool,
_current_position: &mut u64,
_total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"insert_char" => {
if let KeyCode::Char(c) = key.code {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
state.set_current_cursor_pos(cursor_pos + 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos();
}
} else {
return Ok("Error: insert_char called without a char key."
.to_string());
}
Ok("working?".to_string())
}
"delete_char_backward" => {
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
let new_pos = cursor_pos - 1;
state.set_current_cursor_pos(new_pos);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = new_pos;
}
}
Ok("".to_string())
}
"delete_char_forward" => {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
chars.remove(cursor_pos);
*field_value = chars.into_iter().collect();
state.set_has_unsaved_changes(true);
*ideal_cursor_column = cursor_pos;
}
Ok("".to_string())
}
"next_field" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = (current_field + 1) % num_fields;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"prev_field" => {
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
};
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_left" => {
let new_pos = state.current_cursor_pos().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_up" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
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();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_down" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.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();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
let new_pos = current_input.len();
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_first_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
state.set_current_field(0);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to first field".to_string())
}
"move_last_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = num_fields - 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to last field".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(
current_input,
state.current_cursor_pos(),
);
let final_pos = new_pos.min(current_input.len());
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos == current_pos {
find_word_end(current_input, new_pos + 1)
} else {
new_pos
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
}
}
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos >= len {
return len;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
if get_char_type(chars[pos]) == CharType::Whitespace {
pos = find_next_word_start(text, pos);
}
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}

View File

@@ -4,7 +4,7 @@ use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; use crate::state::canvas_state::CanvasState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::functions::common::form::{revert, save}; use crate::tui::functions::common::form::{revert, save};
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any; use std::any::Any;
@@ -173,11 +173,7 @@ pub async fn execute_edit_action<S: CanvasState>(
let num_fields = state.fields().len(); let num_fields = state.fields().len();
if num_fields > 0 { if num_fields > 0 {
let current_field = state.current_field(); let current_field = state.current_field();
let new_field = if current_field == 0 { let new_field = current_field.saturating_sub(1);
num_fields - 1
} else {
current_field - 1
};
state.set_current_field(new_field); state.set_current_field(new_field);
let current_input = state.get_current_input(); let current_input = state.get_current_input();
let max_pos = current_input.len(); let max_pos = current_input.len();
@@ -191,7 +187,7 @@ pub async fn execute_edit_action<S: CanvasState>(
"move_down" => { "move_down" => {
let num_fields = state.fields().len(); let num_fields = state.fields().len();
if num_fields > 0 { if num_fields > 0 {
let new_field = (state.current_field() + 1) % num_fields; let new_field = (state.current_field() + 1).min(num_fields - 1);
state.set_current_field(new_field); state.set_current_field(new_field);
let current_input = state.get_current_input(); let current_input = state.get_current_input();
let max_pos = current_input.len(); let max_pos = current_input.len();

View File

@@ -19,14 +19,89 @@ pub async fn execute_action<S: CanvasState>(
command_message: &mut String, command_message: &mut String,
) -> Result<String, Box<dyn Error>> { ) -> Result<String, Box<dyn Error>> {
match action { match action {
"previous_entry" | "next_entry" | "move_up" | "move_down" | "previous_entry" | "next_entry" => {
"move_first_line" | "move_last_line" => {
key_sequence_tracker.reset(); key_sequence_tracker.reset();
Ok(format!( Ok(format!(
"Action '{}' should be handled by context-specific logic", "Action '{}' should be handled by context-specific logic",
action action
)) ))
} }
"move_up" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let new_field = current_field.saturating_sub(1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("move up from functions/modes/read_only/auth_ro.rs".to_string())
}
"move_down" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let new_field = (state.current_field() + 1).min(num_fields - 1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("move down from functions/modes/read_only/auth_ro.rs".to_string())
}
"move_first_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
state.set_current_field(0);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_last_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
let last_field_index = num_fields - 1;
state.set_current_field(last_field_index);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"exit_edit_mode" => { "exit_edit_mode" => {
key_sequence_tracker.reset(); key_sequence_tracker.reset();
command_message.clear(); command_message.clear();

View File

@@ -33,11 +33,7 @@ pub async fn execute_action<S: CanvasState>(
return Ok("No fields to navigate.".to_string()); return Ok("No fields to navigate.".to_string());
} }
let current_field = state.current_field(); let current_field = state.current_field();
let new_field = if current_field == 0 { let new_field = current_field.saturating_sub(1);
num_fields - 1
} else {
current_field - 1
};
state.set_current_field(new_field); state.set_current_field(new_field);
let current_input = state.get_current_input(); let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() { let max_cursor_pos = if current_input.is_empty() {
@@ -56,7 +52,7 @@ pub async fn execute_action<S: CanvasState>(
return Ok("No fields to navigate.".to_string()); return Ok("No fields to navigate.".to_string());
} }
let current_field = state.current_field(); 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); state.set_current_field(new_field);
let current_input = state.get_current_input(); let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() { let max_cursor_pos = if current_input.is_empty() {

View File

@@ -1,4 +1,4 @@
// src/client/modes/canvas.rs // src/client/modes/canvas.rs
pub mod edit; pub mod edit;
pub mod common; pub mod common_mode;
pub mod read_only; pub mod read_only;

View File

@@ -5,7 +5,7 @@ use crate::state::pages::{form::FormState, auth::AuthState};
use crate::state::state::AppState; use crate::state::state::AppState;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::functions::common::{ use crate::tui::functions::common::{
form::{save as form_save, revert as form_revert}, form::{save as form_save, revert as form_revert},
login::{save as login_save, revert as login_revert} login::{save as login_save, revert as login_revert}
}; };

View File

@@ -2,16 +2,17 @@
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; use crate::state::pages::{auth::AuthState, form::FormState};
use crate::state::pages::form::FormState; use crate::state::state::AppState;
use crate::functions::modes::edit::form_e; use crate::functions::modes::edit::{auth_e, form_e};
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any;
pub async fn handle_edit_event_internal<S: CanvasState + Any>( pub async fn handle_edit_event(
is_auth_context: bool,
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
state: &mut S, form_state: &mut FormState,
auth_state: &mut AuthState,
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
command_message: &mut String, command_message: &mut String,
is_saved: &mut bool, is_saved: &mut bool,
@@ -19,61 +20,98 @@ pub async fn handle_edit_event_internal<S: CanvasState + Any>(
total_count: u64, total_count: u64,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
if let Some(action) = config.get_action_for_key_in_mode(
// Global command mode check
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
&config.keybindings.global, &config.keybindings.global,
key.code, key.code,
key.modifiers, key.modifiers
) { ) {
if action == "enter_command_mode" { *command_message = "Switching to Command Mode...".to_string();
*command_message = "Switching to Command Mode...".to_string(); return Ok(command_message.clone());
return Ok(command_message.clone());
}
} }
// Common actions (save/revert)
if let Some(action) = config.get_action_for_key_in_mode( if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common, &config.keybindings.common,
key.code, key.code,
key.modifiers, key.modifiers
) { ) {
if action == "save" || action == "revert" { if matches!(action, "save" | "revert") {
return form_e::execute_common_action( return if is_auth_context {
action, auth_e::execute_common_action(
state, action,
grpc_client, auth_state, // Concrete AuthState
is_saved, grpc_client,
current_position, is_saved,
total_count, current_position,
) total_count
.await; ).await
} else {
form_e::execute_common_action(
action,
form_state, // Concrete FormState
grpc_client,
is_saved,
current_position,
total_count
).await
};
} }
} }
// Edit-specific actions
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
return form_e::execute_edit_action( return if is_auth_context {
action, auth_e::execute_edit_action(
key, action,
state, key,
ideal_cursor_column, auth_state, // Full access to AuthState fields
grpc_client, ideal_cursor_column,
is_saved, grpc_client,
current_position, is_saved,
total_count, current_position,
) total_count
.await; ).await
} else {
form_e::execute_edit_action(
action,
key,
form_state, // Full access to FormState fields
ideal_cursor_column,
grpc_client,
is_saved,
current_position,
total_count
).await
};
} }
if let KeyCode::Char(c) = key.code { // Character insertion
return form_e::execute_edit_action( if let KeyCode::Char(_) = key.code {
"insert_char", return if is_auth_context {
key, auth_e::execute_edit_action(
state, "insert_char",
ideal_cursor_column, key,
grpc_client, auth_state,
is_saved, ideal_cursor_column,
current_position, grpc_client,
total_count, is_saved,
) current_position,
.await; total_count
).await
} else {
form_e::execute_edit_action(
"insert_char",
key,
form_state,
ideal_cursor_column,
grpc_client,
is_saved,
current_position,
total_count
).await
};
} }
Ok(command_message.clone()) Ok(command_message.clone())

View File

@@ -1,3 +1,6 @@
// src/client/modes/common.rs // src/client/modes/common.rs
pub mod command_mode; pub mod command_mode;
pub mod highlight; pub mod highlight;
pub mod commands;
pub use commands::*;

View File

@@ -4,9 +4,9 @@ use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::functions::common::commands::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
use crate::functions::common::form::{save, revert}; use crate::tui::functions::common::form::{save, revert};
pub async fn handle_command_event( pub async fn handle_command_event(
key: KeyEvent, key: KeyEvent,

View File

@@ -1,19 +1,18 @@
// src/modes/handlers/event.rs // src/modes/handlers/event.rs
use crossterm::event::Event; use crossterm::event::Event;
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::{ use crate::tui::terminal::core::TerminalCore;
core::TerminalCore,
};
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::functions::common::commands::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::state::canvas_state::CanvasState;
use crate::ui::handlers::rat_state::UiStateHandler; use crate::ui::handlers::rat_state::UiStateHandler;
use crate::modes::{ use crate::modes::{
common::{command_mode}, common::command_mode,
canvas::{edit, read_only, common}, canvas::{edit, read_only, common_mode},
general::navigation, general::navigation,
}; };
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
@@ -27,7 +26,6 @@ pub struct EventHandler {
pub edit_mode_cooldown: bool, pub edit_mode_cooldown: bool,
pub ideal_cursor_column: usize, pub ideal_cursor_column: usize,
pub key_sequence_tracker: KeySequenceTracker, pub key_sequence_tracker: KeySequenceTracker,
pub auth_state: AuthState,
pub auth_client: AuthClient, pub auth_client: AuthClient,
} }
@@ -41,7 +39,6 @@ impl EventHandler {
edit_mode_cooldown: false, edit_mode_cooldown: false,
ideal_cursor_column: 0, ideal_cursor_column: 0,
key_sequence_tracker: KeySequenceTracker::new(800), key_sequence_tracker: KeySequenceTracker::new(800),
auth_state: AuthState::new(),
auth_client: AuthClient::new().await?, auth_client: AuthClient::new().await?,
}) })
} }
@@ -54,11 +51,11 @@ impl EventHandler {
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
command_handler: &mut CommandHandler, command_handler: &mut CommandHandler,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState,
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,
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
// Determine current mode based on app state and event handler state
let current_mode = ModeManager::derive_mode(app_state, self); let current_mode = ModeManager::derive_mode(app_state, self);
app_state.update_mode(current_mode); app_state.update_mode(current_mode);
@@ -66,14 +63,12 @@ impl EventHandler {
let key_code = key.code; let key_code = key.code;
let modifiers = key.modifiers; let modifiers = key.modifiers;
// Handle common actions across all modes
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) { if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) {
return Ok((false, format!("Sidebar {}", return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" } if app_state.ui.show_sidebar { "shown" } else { "hidden" }
))); )));
} }
// Mode-specific handling
match current_mode { match current_mode {
AppMode::General => { AppMode::General => {
return navigation::handle_navigation_event( return navigation::handle_navigation_event(
@@ -88,7 +83,6 @@ impl EventHandler {
}, },
AppMode::ReadOnly => { AppMode::ReadOnly => {
// Check for mode transitions first
if config.is_enter_edit_mode_before(key_code, modifiers) && if config.is_enter_edit_mode_before(key_code, modifiers) &&
ModeManager::can_enter_edit_mode(current_mode) { ModeManager::can_enter_edit_mode(current_mode) {
self.is_edit_mode = true; self.is_edit_mode = true;
@@ -100,10 +94,25 @@ impl EventHandler {
if config.is_enter_edit_mode_after(key_code, modifiers) && if config.is_enter_edit_mode_after(key_code, modifiers) &&
ModeManager::can_enter_edit_mode(current_mode) { ModeManager::can_enter_edit_mode(current_mode) {
let current_input = form_state.get_current_input(); let current_input = if app_state.ui.show_login {
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() { auth_state.get_current_input()
form_state.current_cursor_pos += 1; } else {
self.ideal_cursor_column = form_state.current_cursor_pos; form_state.get_current_input()
};
let current_cursor_pos = if app_state.ui.show_login {
auth_state.current_cursor_pos()
} else {
form_state.current_cursor_pos()
};
if !current_input.is_empty() && current_cursor_pos < current_input.len() {
if app_state.ui.show_login {
auth_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = auth_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = form_state.current_cursor_pos();
}
} }
self.is_edit_mode = true; self.is_edit_mode = true;
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
@@ -112,7 +121,6 @@ impl EventHandler {
return Ok((false, self.command_message.clone())); 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 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) { if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) {
self.command_mode = true; self.command_mode = true;
@@ -122,8 +130,6 @@ impl EventHandler {
} }
} }
// 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( if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common, &config.keybindings.common,
key_code, key_code,
@@ -131,10 +137,10 @@ impl EventHandler {
) { ) {
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit" | "revert" => {
return common::handle_core_action( return common_mode::handle_core_action(
action, action,
form_state, form_state,
&mut self.auth_state, auth_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
terminal, terminal,
@@ -143,17 +149,16 @@ impl EventHandler {
total_count, total_count,
).await; ).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( return read_only::handle_read_only_event(
&app_state, &app_state,
key, key,
config, config,
form_state, form_state,
&mut self.auth_state, auth_state,
&mut self.key_sequence_tracker, &mut self.key_sequence_tracker,
current_position, current_position,
total_count, total_count,
@@ -165,27 +170,48 @@ impl EventHandler {
}, },
AppMode::Edit => { 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 {
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
return Ok((false, self.command_message.clone()));
}
self.is_edit_mode = false; self.is_edit_mode = false;
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
self.command_message = "Read-only mode".to_string();
let has_changes = if app_state.ui.show_login {
auth_state.has_unsaved_changes()
} else {
form_state.has_unsaved_changes()
};
self.command_message = if has_changes {
"Exited edit mode (unsaved changes remain)".to_string()
} else {
"Read-only mode".to_string()
};
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = form_state.get_current_input(); let current_input = if app_state.ui.show_login {
if !current_input.is_empty() && form_state.current_cursor_pos >= current_input.len() { auth_state.get_current_input()
form_state.current_cursor_pos = current_input.len() - 1; } else {
self.ideal_cursor_column = form_state.current_cursor_pos; form_state.get_current_input()
};
let current_cursor_pos = if app_state.ui.show_login {
auth_state.current_cursor_pos()
} else {
form_state.current_cursor_pos()
};
if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
let new_pos = current_input.len() - 1;
if app_state.ui.show_login {
auth_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = auth_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = form_state.current_cursor_pos();
}
} }
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( if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common, &config.keybindings.common,
key_code, key_code,
@@ -193,48 +219,35 @@ impl EventHandler {
) { ) {
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit" | "revert" => {
return common::handle_core_action( return common_mode::handle_core_action(
action, action,
form_state, form_state,
&mut self.auth_state, auth_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
terminal, terminal,
app_state, app_state,
current_position, current_position,
total_count, total_count,
).await; ).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(
let result = if app_state.ui.show_login { app_state.ui.show_login,
edit::handle_edit_event_internal( key,
key, config,
config, form_state,
&mut self.auth_state, // Use auth_state instead of form_state auth_state,
&mut self.ideal_cursor_column, &mut self.ideal_cursor_column,
&mut self.command_message, &mut self.command_message,
&mut app_state.ui.is_saved, &mut app_state.ui.is_saved,
current_position, current_position,
total_count, total_count,
grpc_client, grpc_client,
).await? ).await?;
} else {
edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?
};
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok((false, result)); return Ok((false, result));
@@ -263,10 +276,7 @@ impl EventHandler {
} }
} }
// 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

@@ -19,7 +19,7 @@ impl ModeManager {
return AppMode::Command; return AppMode::Command;
} }
if app_state.ui.show_login { // NEW: Check auth visibility if app_state.ui.show_login {
if event_handler.is_edit_mode { if event_handler.is_edit_mode {
AppMode::Edit AppMode::Edit
} else { } else {

View File

@@ -12,6 +12,7 @@ pub struct AuthState {
pub auth_token: Option<String>, pub auth_token: Option<String>,
pub user_id: Option<String>, pub user_id: Option<String>,
pub role: Option<String>, pub role: Option<String>,
pub has_unsaved_changes: bool,
} }
impl AuthState { impl AuthState {
@@ -26,6 +27,7 @@ impl AuthState {
auth_token: None, auth_token: None,
user_id: None, user_id: None,
role: None, role: None,
has_unsaved_changes: false,
} }
} }
} }
@@ -36,12 +38,16 @@ impl CanvasState for AuthState {
} }
fn current_cursor_pos(&self) -> usize { fn current_cursor_pos(&self) -> usize {
self.current_cursor_pos let len = match self.current_field {
0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
self.current_cursor_pos.min(len)
} }
fn has_unsaved_changes(&self) -> bool { fn has_unsaved_changes(&self) -> bool {
// Auth form doesn't need unsaved changes tracking self.has_unsaved_changes
false
} }
fn inputs(&self) -> Vec<&String> { fn inputs(&self) -> Vec<&String> {
@@ -52,7 +58,7 @@ impl CanvasState for AuthState {
match self.current_field { match self.current_field {
0 => &self.username, 0 => &self.username,
1 => &self.password, 1 => &self.password,
_ => "", // Return empty string for invalid index instead of panicking _ => "",
} }
} }
@@ -68,20 +74,31 @@ impl CanvasState for AuthState {
vec!["Username/Email", "Password"] vec!["Username/Email", "Password"]
} }
// --- Implement the setter methods ---
fn set_current_field(&mut self, index: usize) { fn set_current_field(&mut self, index: usize) {
// AuthState only has 2 fields (0 and 1) if index < 2 { // AuthState only has 2 fields
if index < 2 {
self.current_field = index; self.current_field = index;
// IMPORTANT: Clamp cursor position to the length of the NEW field
let len = match self.current_field {
0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
self.current_cursor_pos = self.current_cursor_pos.min(len);
} }
} }
fn set_current_cursor_pos(&mut self, pos: usize) { fn set_current_cursor_pos(&mut self, pos: usize) {
// Optional: Add validation based on current input length if needed let len = match self.current_field {
self.current_cursor_pos = pos; 0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
// Ensure stored position is always valid
self.current_cursor_pos = pos.min(len);
} }
fn set_has_unsaved_changes(&mut self, _changed: bool) { fn set_has_unsaved_changes(&mut self, changed: bool) {
// Auth form doesn't track unsaved changes, so do nothing // Allow the generic handler to signal changes
self.has_unsaved_changes = changed;
} }
} }

View File

@@ -5,12 +5,12 @@ use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::components::IntroState; use crate::components::IntroState;
use crate::modes::handlers::mode_manager::AppMode; use crate::modes::handlers::mode_manager::AppMode;
#[derive(Default)]
pub struct DialogState { pub struct DialogState {
pub show_dialog: bool, pub dialog_show: bool,
pub dialog_title: String, pub dialog_title: String,
pub dialog_message: String, pub dialog_message: String,
pub dialog_button_active: bool, pub dialog_buttons: Vec<String>,
pub dialog_active_button_index: usize,
} }
pub struct UiState { pub struct UiState {
@@ -77,21 +77,55 @@ impl AppState {
} }
// Add dialog helper methods // Add dialog helper methods
pub fn show_dialog(&mut self, title: &str, message: &str) { /// Shows a dialog with the given title, message, and buttons.
self.ui.dialog.show_dialog = true; /// The first button (index 0) is active by default.
pub fn show_dialog(
&mut self,
title: &str,
message: &str,
buttons: Vec<String>,
) {
self.ui.dialog.dialog_title = title.to_string(); self.ui.dialog.dialog_title = title.to_string();
self.ui.dialog.dialog_message = message.to_string(); self.ui.dialog.dialog_message = message.to_string();
self.ui.dialog.dialog_button_active = true; self.ui.dialog.dialog_buttons = buttons;
self.ui.dialog.dialog_active_button_index = 0; // Default to first button
self.ui.dialog.dialog_show = true; // Use new name
} }
/// Hides the dialog and clears its content.
pub fn hide_dialog(&mut self) { pub fn hide_dialog(&mut self) {
self.ui.dialog.show_dialog = false; self.ui.dialog.dialog_show = false; // Use new name
self.ui.dialog.dialog_title.clear(); self.ui.dialog.dialog_title.clear();
self.ui.dialog.dialog_message.clear(); self.ui.dialog.dialog_message.clear();
self.ui.dialog.dialog_buttons.clear();
self.ui.dialog.dialog_active_button_index = 0;
} }
pub fn set_dialog_button_active(&mut self, active: bool) { /// Sets the active button index, wrapping around if necessary.
self.ui.dialog.dialog_button_active = active; pub fn next_dialog_button(&mut self) {
if !self.ui.dialog.dialog_buttons.is_empty() {
let next_index = (self.ui.dialog.dialog_active_button_index + 1)
% self.ui.dialog.dialog_buttons.len();
self.ui.dialog.dialog_active_button_index = next_index; // Use new name
}
}
/// Sets the active button index, wrapping around if necessary.
pub fn previous_dialog_button(&mut self) {
if !self.ui.dialog.dialog_buttons.is_empty() {
let len = self.ui.dialog.dialog_buttons.len();
let prev_index =
(self.ui.dialog.dialog_active_button_index + len - 1) % len;
self.ui.dialog.dialog_active_button_index = prev_index; // Use new name
}
}
/// Gets the label of the currently active button, if any.
pub fn get_active_dialog_button_label(&self) -> Option<&str> {
self.ui.dialog
.dialog_buttons // Use new name
.get(self.ui.dialog.dialog_active_button_index) // Use new name
.map(|s| s.as_str())
} }
} }
@@ -109,3 +143,16 @@ impl Default for UiState {
} }
} }
} }
// Update the Default implementation for DialogState itself
impl Default for DialogState {
fn default() -> Self {
Self {
dialog_show: false, // Use new name
dialog_title: String::new(), // Use new name
dialog_message: String::new(), // Use new name
dialog_buttons: Vec::new(), // Use new name
dialog_active_button_index: 0, // Use new name
}
}
}

View File

@@ -1 +1,7 @@
// src/tui/functions/common.rs // src/tui/functions/common.rs
pub mod form;
pub mod login;
pub use form::*;
pub use login::*;

View File

@@ -0,0 +1,100 @@
// src/tui/functions/common/login.rs
use crate::services::auth::AuthClient;
use crate::state::pages::auth::AuthState;
use crate::state::state::AppState;
use crate::state::canvas_state::CanvasState;
// Remove unused import if CanvasState is not directly used here
// use crate::state::canvas_state::CanvasState;
/// Attempts to log the user in using the provided credentials via gRPC.
/// Updates AuthState and AppState on success or failure.
pub async fn save(
auth_state: &mut AuthState,
auth_client: &mut AuthClient,
app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> {
let identifier = auth_state.username.clone();
let password = auth_state.password.clone();
// Clear previous error/dialog state before attempting
auth_state.error_message = None;
// Use the helper to ensure dialog is hidden and cleared properly
app_state.hide_dialog();
// Call the gRPC login method
match auth_client.login(identifier, password).await {
Ok(response) => {
// Store authentication details on success
auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone());
auth_state.set_has_unsaved_changes(false);
let success_message = format!(
"Login Successful!\n\n\
Access Token: {}\n\
Token Type: {}\n\
Expires In: {}\n\
User ID: {}\n\
Role: {}",
response.access_token,
response.token_type,
response.expires_in,
response.user_id,
response.role
);
// Use the helper method to configure and show the dialog
// TODO Implement logic for pressing menu or exit buttons, not imeplementing it now,
// need to do other more important stuff now"
app_state.show_dialog(
"Login Success",
&success_message,
vec!["Menu".to_string(), "Exit".to_string()],
);
Ok("Login successful, details shown in dialog.".to_string())
}
Err(e) => {
let error_message = format!("{}", e);
// Use the helper method to configure and show the dialog
app_state.show_dialog(
"Login Failed",
&error_message,
vec!["OK".to_string()], // Pass buttons here
);
// REMOVE these lines:
// app_state.ui.dialog.dialog_title = "Login Failed".to_string();
// app_state.ui.dialog.dialog_message = error_message.clone();
// app_state.ui.dialog.dialog_show = true;
// app_state.ui.dialog.dialog_button_active = true;
auth_state.set_has_unsaved_changes(true);
Ok(format!("Login failed: {}", error_message))
}
}
}
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
pub async fn revert(
auth_state: &mut AuthState,
_app_state: &mut AppState, // Prefix unused variable
) -> String {
// Clear the input fields
auth_state.username.clear();
auth_state.password.clear();
auth_state.error_message = None;
auth_state.set_has_unsaved_changes(false);
// Ensure dialog is hidden if revert is called
// _app_state.hide_dialog(); // Uncomment if needed
// Navigation logic (currently disabled in original code)
// _app_state.ui.show_login = false;
// _app_state.ui.show_intro = true;
"Login reverted".to_string()
}

View File

@@ -11,6 +11,15 @@ pub async fn handle_action(
total_count: u64, total_count: u64,
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
// TODO store unsaved changes without deleting form state values
// First check for unsaved changes in both cases
if form_state.has_unsaved_changes() {
return Ok(
"Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
.to_string(),
);
}
match action { match action {
"previous_entry" => { "previous_entry" => {
let new_position = current_position.saturating_sub(1); let new_position = current_position.saturating_sub(1);

View File

@@ -3,14 +3,15 @@
use crate::tui::terminal::TerminalCore; use crate::tui::terminal::TerminalCore;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::services::ui_service::UiService; // Add this import use crate::services::ui_service::UiService;
use crate::tui::terminal::EventReader; use crate::tui::terminal::EventReader;
use crate::functions::common::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::ui::handlers::render::render_ui; use crate::ui::handlers::render::render_ui;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::state::canvas_state::CanvasState;
use crate::modes::handlers::event::EventHandler; use crate::modes::handlers::event::EventHandler;
use crate::state::state::AppState; use crate::state::state::AppState;
@@ -18,10 +19,10 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?; let config = Config::load()?;
let mut terminal = TerminalCore::new()?; let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?; let mut grpc_client = GrpcClient::new().await?;
let auth_client = AuthClient::new().await?; // let auth_client = AuthClient::new().await?; // AuthClient is now inside EventHandler
let mut command_handler = CommandHandler::new(); let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme); let theme = Theme::from_str(&config.colors.theme);
let mut auth_state = AuthState::default(); let mut auth_state = AuthState::default(); // The single source of truth for AuthState
// Initialize app_state first // Initialize app_state first
let mut app_state = AppState::new()?; let mut app_state = AppState::new()?;
@@ -32,7 +33,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// Initialize FormState with dynamic fields // Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names); let mut form_state = FormState::new(column_names);
// The rest of your UI initialization remains the same // Initialize EventHandler (which now contains AuthClient)
let mut event_handler = EventHandler::new().await?; let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new(); let event_reader = EventReader::new();
@@ -43,13 +44,16 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
loop { loop {
UiService::update_adresar_count(&mut grpc_client, &mut app_state).await?; UiService::update_adresar_count(&mut grpc_client, &mut app_state).await?;
// Determine edit mode based on EventHandler state
let is_edit_mode = event_handler.is_edit_mode;
terminal.draw(|f| { terminal.draw(|f| {
render_ui( render_ui(
f, f,
&mut form_state, &mut form_state,
&mut auth_state, &mut auth_state, // Pass the single AuthState instance
&theme, &theme,
event_handler.is_edit_mode, is_edit_mode, // Use determined edit mode
app_state.total_count, app_state.total_count,
app_state.current_position, app_state.current_position,
&app_state.current_dir, &app_state.current_dir,
@@ -62,6 +66,8 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let total_count = app_state.total_count; let total_count = app_state.total_count;
let mut current_position = app_state.current_position; let mut current_position = app_state.current_position;
// Store position before event handling to detect navigation
let position_before_event = current_position;
let event = event_reader.read_event()?; let event = event_reader.read_event()?;
let (should_exit, message) = event_handler.handle_event( let (should_exit, message) = event_handler.handle_event(
@@ -71,6 +77,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
&mut grpc_client, &mut grpc_client,
&mut command_handler, &mut command_handler,
&mut form_state, &mut form_state,
&mut auth_state, // Pass the single AuthState instance here too
&mut app_state, &mut app_state,
total_count, total_count,
&mut current_position, &mut current_position,
@@ -78,49 +85,86 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
app_state.current_position = current_position; app_state.current_position = current_position;
// Handle position changes and update form state let position_changed = app_state.current_position != position_before_event;
if !event_handler.is_edit_mode {
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1 // Limit to last character in readonly mode
} else {
0
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
// Ensure position never exceeds total_count + 1
if app_state.current_position > total_count + 1 {
app_state.current_position = total_count + 1;
}
if app_state.current_position > total_count {
// New entry - reset form
form_state.reset_to_empty();
form_state.current_field = 0;
} else if app_state.current_position >= 1 && app_state.current_position <= total_count {
// Existing entry - load data
let current_position = app_state.current_position;
let message = UiService::load_adresar_by_position(
&mut grpc_client,
&mut app_state,
&mut form_state,
current_position
).await?;
// Handle position changes and update form state (Only when form is shown)
if app_state.ui.show_form {
if position_changed && !event_handler.is_edit_mode {
let current_input = form_state.get_current_input(); let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() { let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1 // In readonly mode, limit to last character current_input.len() - 1 // Limit to last character in readonly mode
} else { } else {
current_input.len() 0
}; };
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos); form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
event_handler.command_message = message;
} else { // Ensure position never exceeds total_count + 1
// Invalid position - reset to first entry if app_state.current_position > total_count + 1 {
app_state.current_position = 1; app_state.current_position = total_count + 1;
}
if app_state.current_position > total_count {
// New entry - reset form
form_state.reset_to_empty();
form_state.current_field = 0;
} else if app_state.current_position >= 1 && app_state.current_position <= total_count {
// Existing entry - load data
let current_position_to_load = app_state.current_position; // Use a copy
let load_message = UiService::load_adresar_by_position(
&mut grpc_client,
&mut app_state, // Pass app_state mutably if needed by the service
&mut form_state,
current_position_to_load
).await?;
let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
current_input.len() - 1 // In readonly mode, limit to last character
} else {
current_input.len()
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
// Don't overwrite message from handle_event if load_message is simple success
if !load_message.starts_with("Loaded entry") || message.is_empty() {
event_handler.command_message = load_message;
}
} else {
// Invalid position (e.g., 0) - reset to first entry or new entry mode
app_state.current_position = 1.min(total_count + 1); // Go to 1 or new entry if empty
if app_state.current_position > total_count {
form_state.reset_to_empty();
form_state.current_field = 0;
}
}
} else if !position_changed && !event_handler.is_edit_mode {
// If position didn't change but we are in read-only, just adjust cursor
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
} }
} else if app_state.ui.show_login {
// Handle cursor updates for AuthState if needed, similar to FormState
if !event_handler.is_edit_mode {
let current_input = auth_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
auth_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
}
}
// Only update command message if handle_event provided one
if !message.is_empty() {
event_handler.command_message = message;
} }
event_handler.command_message = message;
if should_exit { if should_exit {
return Ok(()); return Ok(());
} }