Compare commits

...

40 Commits

Author SHA1 Message Date
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
filipriec
3dc5a89459 splitting modes into functions and how it works vs logic to handle it all 2025-04-03 23:23:25 +02:00
filipriec
9f6268dbc9 minor change 2025-04-03 23:00:34 +02:00
filipriec
2e912dd261 moved to form_ro 2025-04-03 22:12:20 +02:00
filipriec
6d6fff474f switching now execute action functions left to right 2025-04-03 20:04:01 +02:00
filipriec
e725c70570 splitting read_only mode 2025-04-03 19:50:35 +02:00
filipriec
07aeecbbfc functions created and now working, lets move modes functions here now 2025-04-03 19:43:59 +02:00
filipriec
9bfac04c44 modes functions dir 2025-04-03 12:34:37 +02:00
filipriec
6acf0d6378 new function dir for functions 2025-04-03 12:32:53 +02:00
filipriec
1a09624242 e fixed 2025-04-02 22:26:35 +02:00
filipriec
9e36385e63 decimated edit mode also 2025-04-02 21:13:18 +02:00
filipriec
43edadde0c trying restoring functionality we are not in there correctly yet 2025-04-02 21:06:49 +02:00
filipriec
d577ff6715 edit mode is like a readonly mode 2025-03-31 23:56:58 +02:00
filipriec
ca75c90ee9 changed read_only mode also 2025-03-31 23:37:02 +02:00
filipriec
8e0fae26ee we compiled 2025-03-31 22:08:39 +02:00
filipriec
bee95c3755 fixes, still 2 errors remaining 2025-03-31 20:10:53 +02:00
filipriec
306f4de14f smart way, but introduced many errors 2025-03-31 17:55:53 +02:00
filipriec
b2fc681e73 cargo fix 2025-03-31 17:16:10 +02:00
filipriec
060cff3f0f compiled 2025-03-31 17:10:51 +02:00
filipriec
07c48985e4 proper pass of the arguments 2025-03-31 16:25:11 +02:00
filipriec
3d266c2ad0 switching of the views done 2025-03-31 16:23:25 +02:00
filipriec
e2c326bf1e login gRPC 2025-03-31 16:16:07 +02:00
filipriec
7f5b671084 switch between login or form in the save request 2025-03-31 15:55:54 +02:00
filipriec
3ccf71ed0f switcher, have bugs 2025-03-31 15:42:48 +02:00
filipriec
efb59c5571 split config in modes/canvas is fixed and working properly well 2025-03-31 15:12:50 +02:00
filipriec
26cf06df14 needs fixes of the errors 2025-03-31 14:58:10 +02:00
filipriec
c82b62f72b moving modes/canvas/common.rs into the functions 2025-03-31 13:22:08 +02:00
filipriec
87cdb8048d we compiled fully, time to move grpc calls now 2025-03-31 12:07:01 +02:00
38 changed files with 2449 additions and 1155 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) );
.alignment(Alignment::Center);
let message_paragraph =
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

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

View File

@@ -0,0 +1,2 @@
// src/functions/common.rs

View File

@@ -0,0 +1,7 @@
// src/functions/mod.rs
pub mod common;
pub mod modes;
pub use common::*;
pub use modes::*;

View File

@@ -0,0 +1,8 @@
// src/functions/modes.rs
pub mod read_only;
pub mod edit;
pub use read_only::*;
pub use edit::*;

View File

@@ -0,0 +1,4 @@
// src/functions/modes/edit.rs
pub mod form_e;
pub mod auth_e;

View File

@@ -0,0 +1,431 @@
// 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 = 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_down" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.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())
}
"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

@@ -0,0 +1,431 @@
// src/functions/modes/edit/form_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("".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 = 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_down" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.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())
}
"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

@@ -0,0 +1,4 @@
// src/functions/modes/read_only.rs
pub mod auth_ro;
pub mod form_ro;

View File

@@ -0,0 +1,358 @@
// src/functions/modes/read_only/auth_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::canvas_state::CanvasState;
use std::error::Error;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
pub async fn execute_action<S: CanvasState>(
action: &str,
state: &mut S,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
) -> Result<String, Box<dyn Error>> {
match action {
"previous_entry" | "next_entry" => {
key_sequence_tracker.reset();
Ok(format!(
"Action '{}' should be handled by context-specific logic",
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 = 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_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 = (current_field + 1) % num_fields;
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" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = state.current_cursor_pos();
let new_pos = current_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_input.is_empty()
&& current_pos < current_input.len().saturating_sub(1)
{
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".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().saturating_sub(1));
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 {
new_pos
} else {
find_word_end(current_input, new_pos + 1)
};
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())
}
"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();
if !current_input.is_empty() {
let new_pos = current_input.len().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
} else {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
}
Ok("".to_string())
}
_ => {
key_sequence_tracker.reset();
Ok(format!("Unknown read-only action: {}", action))
},
}
}
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();
if chars.is_empty() {
return 0;
}
let current_pos = current_pos.min(chars.len());
if current_pos == chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let next_start = find_next_word_start(text, current_pos);
if next_start >= chars.len() {
return chars.len().saturating_sub(1);
}
let mut pos = next_start;
let word_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
let original_pos = pos;
let current_type = get_char_type(chars[pos]);
if current_type != CharType::Whitespace {
while pos < len && get_char_type(chars[pos]) == current_type {
pos += 1;
}
return pos.saturating_sub(1);
}
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 get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
0
} else {
pos
}
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 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[0]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[0]) != 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

@@ -0,0 +1,357 @@
// src/functions/modes/read_only/form_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::canvas_state::CanvasState;
use std::error::Error;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
pub async fn execute_action<S: CanvasState>(
action: &str,
state: &mut S,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
) -> Result<String, Box<dyn Error>> {
match action {
"previous_entry" | "next_entry" => {
key_sequence_tracker.reset();
Ok(format!(
"Action '{}' should be handled by context-specific logic",
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 = 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_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("".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 = (current_field + 1) % num_fields;
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("".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" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = state.current_cursor_pos();
let new_pos = current_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_input.is_empty()
&& current_pos < current_input.len().saturating_sub(1)
{
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".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().saturating_sub(1));
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 {
new_pos
} else {
find_word_end(current_input, new_pos + 1)
};
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())
}
"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();
if !current_input.is_empty() {
let new_pos = current_input.len().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
} else {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
}
Ok("".to_string())
}
_ => {
key_sequence_tracker.reset();
Ok(format!("Unknown read-only action: {}", action))
},
}
}
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();
if chars.is_empty() {
return 0;
}
let current_pos = current_pos.min(chars.len());
if current_pos == chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let next_start = find_next_word_start(text, current_pos);
if next_start >= chars.len() {
return chars.len().saturating_sub(1);
}
let mut pos = next_start;
let word_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
let original_pos = pos;
let current_type = get_char_type(chars[pos]);
if current_type != CharType::Whitespace {
while pos < len && get_char_type(chars[pos]) == current_type {
pos += 1;
}
return pos.saturating_sub(1);
}
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 get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
0
} else {
pos
}
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 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[0]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[0]) != 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

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

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

@@ -0,0 +1,75 @@
// src/modes/canvas/common.rs
use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::{form::FormState, auth::AuthState};
use crate::state::state::AppState;
use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::tui::functions::common::{
form::{save as form_save, revert as form_revert},
login::{save as login_save, revert as login_revert}
};
pub async fn handle_core_action(
action: &str,
form_state: &mut FormState,
auth_state: &mut AuthState,
grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient,
terminal: &mut TerminalCore,
app_state: &mut AppState,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"save" => {
if app_state.ui.show_login {
let message = login_save(auth_state, auth_client, app_state).await?;
Ok((false, message))
} else {
let message = form_save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
Ok((false, message))
}
},
"force_quit" => {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".to_string()))
},
"save_and_quit" => {
let message = if app_state.ui.show_login {
login_save(auth_state, auth_client, app_state).await?
} else {
form_save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?
};
terminal.cleanup()?;
Ok((true, format!("{}. Exiting application.", message)))
},
"revert" => {
if app_state.ui.show_login {
let message = login_revert(auth_state, app_state).await;
Ok((false, message))
} else {
let message = form_revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
Ok((false, message))
}
},
_ => Ok((false, format!("Core action not handled: {}", action))),
}
}

View File

@@ -1,17 +1,18 @@
// 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 crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState;
use crate::modes::canvas::common;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::pages::{auth::AuthState, form::FormState};
use crate::state::state::AppState;
use crate::functions::modes::edit::{auth_e, form_e};
use crossterm::event::{KeyCode, KeyEvent};
pub async fn handle_edit_event(
pub async fn handle_edit_event_internal( is_auth_context: bool,
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
form_state: &mut FormState, 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,455 +20,99 @@ pub async fn handle_edit_event_internal(
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("enter_command_mode") = config.get_action_for_key_in_mode(&config.keybindings.global, key.code, key.modifiers) {
// Ignore in edit mode and process as normal input // Global command mode check
handle_edit_specific_input(key, form_state, ideal_cursor_column); if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
&config.keybindings.global,
key.code,
key.modifiers
) {
*command_message = "Switching to Command Mode...".to_string();
return Ok(command_message.clone()); return Ok(command_message.clone());
} }
// Check common actions first // Common actions (save/revert)
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.common, key.code, key.modifiers) { if let Some(action) = config.get_action_for_key_in_mode(
return execute_common_action( &config.keybindings.common,
action, key.code,
form_state, key.modifiers
grpc_client, ) {
is_saved, if matches!(action, "save" | "revert") {
current_position, return if is_auth_context {
total_count, auth_e::execute_common_action(
).await; action,
auth_state, // Concrete AuthState
grpc_client,
is_saved,
current_position,
total_count
).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 execute_edit_action( return if is_auth_context {
action, auth_e::execute_edit_action(
form_state, action,
ideal_cursor_column, key,
grpc_client, // Changed from AppTerminal auth_state, // Full access to AuthState fields
is_saved, ideal_cursor_column,
current_position, grpc_client,
total_count, is_saved,
).await; current_position,
total_count
).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
};
} }
handle_edit_specific_input( // Character insertion
key, if let KeyCode::Char(_) = key.code {
form_state, return if is_auth_context {
ideal_cursor_column, auth_e::execute_edit_action(
); "insert_char",
key,
auth_state,
ideal_cursor_column,
grpc_client,
is_saved,
current_position,
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())
} }
async fn execute_common_action(
action: &str,
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client,
is_saved,
current_position,
total_count,
).await
},
"revert" => {
common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await
},
"move_up" | "move_down" => {
// Reuse edit mode's existing logic
execute_edit_action(
action,
form_state,
&mut 0, // Dummy ideal_cursor_column (not used here)
grpc_client,
is_saved,
current_position,
total_count,
).await
},
_ => Ok(format!("Common action not handled: {}", action)),
}
}
fn handle_edit_specific_input(
key: KeyEvent,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
) {
match key.code {
KeyCode::Char(c) => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos + 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
KeyCode::Backspace => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
}
KeyCode::Delete => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
}
}
KeyCode::Tab => {
if key.modifiers.contains(KeyModifiers::SHIFT) {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
} else {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
KeyCode::Enter => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
_ => {}
}
}
async fn execute_edit_action(
action: &str,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
grpc_client: &mut GrpcClient, // Changed from AppTerminal
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client, // Changed from AppTerminal
is_saved,
current_position,
total_count,
).await
},
"move_left" => {
form_state.current_cursor_pos = form_state.current_cursor_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
if form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_up" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_down" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
form_state.current_cursor_pos = current_input.len();
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_first_line" => {
form_state.current_field = 0;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to first line".to_string())
}
"move_last_line" => {
form_state.current_field = form_state.fields.len() - 1;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to last line".to_string())
}
// Word movement actions
"move_word_next" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
// Edit-specific actions that can be bound to keys
"delete_char_forward" => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
}
Ok("".to_string())
}
"delete_char_backward" => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
Ok("".to_string())
}
"insert_char" => {
// This could be expanded to allow configurable character insertion
// For now, it's a placeholder that would need additional parameters
Ok("Character insertion requires configuration".to_string())
}
"next_field" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"prev_field" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
// Fallback for unrecognized actions
_ => Ok(format!("Unknown action: {}", action)),
}
}
// Reuse these character and word navigation helper functions
#[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();
if chars.is_empty() || current_pos >= chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.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();
if chars.is_empty() {
return 0;
}
if current_pos >= chars.len() - 1 {
return chars.len() - 1;
}
let mut pos = current_pos;
if get_char_type(chars[pos]) == CharType::Whitespace {
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
} else {
let current_type = get_char_type(chars[pos]);
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
pos += 1;
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
}
}
if pos >= chars.len() {
return chars.len() - 1;
}
let word_type = get_char_type(chars[pos]);
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
pos += 1;
}
pos
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 {
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 {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos -= 1;
let prev_word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
pos -= 1;
}
while pos < chars.len() - 1 &&
get_char_type(chars[pos + 1]) == prev_word_type {
pos += 1;
}
}
}
pos
}

View File

@@ -1,19 +1,13 @@
// src/modes/canvas/read_only.rs // src/modes/canvas/read_only.rs
use crossterm::event::{KeyEvent};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
use crate::services::grpc_client::GrpcClient;
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::services::grpc_client::GrpcClient;
#[derive(PartialEq)] use crate::state::canvas_state::CanvasState;
enum CharType { use crate::state::pages::auth::AuthState;
Whitespace, use crate::state::pages::form::FormState;
Alphanumeric, use crate::functions::modes::read_only::{auth_ro, form_ro};
Punctuation, use crossterm::event::KeyEvent;
}
pub async fn handle_read_only_event( pub async fn handle_read_only_event(
app_state: &crate::state::state::AppState, app_state: &crate::state::state::AppState,
@@ -29,7 +23,6 @@ pub async fn handle_read_only_event(
edit_mode_cooldown: &mut bool, edit_mode_cooldown: &mut bool,
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
// Check for entering Edit mode from Read-Only mode
if config.is_enter_edit_mode_before(key.code, key.modifiers) { if config.is_enter_edit_mode_before(key.code, key.modifiers) {
*edit_mode_cooldown = true; *edit_mode_cooldown = true;
*command_message = "Entering Edit mode".to_string(); *command_message = "Entering Edit mode".to_string();
@@ -37,25 +30,47 @@ pub async fn handle_read_only_event(
} }
if config.is_enter_edit_mode_after(key.code, key.modifiers) { if config.is_enter_edit_mode_after(key.code, key.modifiers) {
let current_input = form_state.get_current_input(); let (current_input, current_pos) = if app_state.ui.show_login {
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() { (
form_state.current_cursor_pos += 1; auth_state.get_current_input(),
*ideal_cursor_column = form_state.current_cursor_pos; auth_state.current_cursor_pos(),
)
} else {
(
form_state.get_current_input(),
form_state.current_cursor_pos(),
)
};
if !current_input.is_empty() && current_pos < current_input.len() {
if app_state.ui.show_login {
auth_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = auth_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = form_state.current_cursor_pos();
}
} }
*edit_mode_cooldown = true; *edit_mode_cooldown = true;
*command_message = "Entering Edit mode (after cursor)".to_string(); *command_message = "Entering Edit mode (after cursor)".to_string();
return Ok((false, command_message.clone())); return Ok((false, command_message.clone()));
} }
// Handle Read-Only mode keybindings const CONTEXT_ACTIONS_FORM: &[&str] = &[
"previous_entry",
"next_entry",
];
const CONTEXT_ACTIONS_LOGIN: &[&str] = &[
"previous_entry",
"next_entry",
];
if key.modifiers.is_empty() { if key.modifiers.is_empty() {
key_sequence_tracker.add_key(key.code); key_sequence_tracker.add_key(key.code);
let sequence = key_sequence_tracker.get_sequence(); let sequence = key_sequence_tracker.get_sequence();
// Try to match the current sequence against Read-Only mode bindings
if let Some(action) = config.matches_key_sequence_generalized(&sequence) { if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
let result = if (action == "previous_entry" || action == "next_entry" || let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
action == "move_up" || action == "move_down") && app_state.ui.show_form {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
form_state, form_state,
@@ -63,38 +78,45 @@ pub async fn handle_read_only_event(
current_position, current_position,
total_count, total_count,
ideal_cursor_column, ideal_cursor_column,
).await? )
} else if (action == "move_up" || action == "move_down") && app_state.ui.show_login { .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
crate::tui::functions::login::handle_action( crate::tui::functions::login::handle_action(
action, action,
auth_state, auth_state,
ideal_cursor_column, ideal_cursor_column,
).await? )
.await?
} else if app_state.ui.show_login {
auth_ro::execute_action(
action,
auth_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else { } else {
execute_action( form_ro::execute_action(
action, action,
form_state, form_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,
current_position, )
total_count, .await?
grpc_client,
).await?
}; };
key_sequence_tracker.reset(); key_sequence_tracker.reset();
return Ok((false, result)); return Ok((false, result));
} }
// Check if this might be a prefix of a longer sequence
if config.is_key_sequence_prefix(&sequence) { if config.is_key_sequence_prefix(&sequence) {
return Ok((false, command_message.clone())); return Ok((false, command_message.clone()));
} }
// Since it's not part of a multi-key sequence, check for a direct action
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) { if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if action == "previous_entry" && app_state.ui.show_form { let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
form_state, form_state,
@@ -102,29 +124,44 @@ pub async fn handle_read_only_event(
current_position, current_position,
total_count, total_count,
ideal_cursor_column, ideal_cursor_column,
).await? )
.await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
crate::tui::functions::login::handle_action(
action,
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login {
auth_ro::execute_action(
action,
auth_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else { } else {
execute_action( form_ro::execute_action(
action, action,
form_state, form_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,
current_position, )
total_count, .await?
grpc_client,
).await?
}; };
key_sequence_tracker.reset(); key_sequence_tracker.reset();
return Ok((false, result)); return Ok((false, result));
} }
} }
key_sequence_tracker.reset();
} else { } else {
// If modifiers are pressed, check for direct key bindings
key_sequence_tracker.reset(); key_sequence_tracker.reset();
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if action == "previous_entry" && app_state.ui.show_form { let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
form_state, form_state,
@@ -132,287 +169,51 @@ pub async fn handle_read_only_event(
current_position, current_position,
total_count, total_count,
ideal_cursor_column, ideal_cursor_column,
).await? )
.await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
crate::tui::functions::login::handle_action(
action,
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login {
auth_ro::execute_action(
action,
auth_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else { } else {
execute_action( form_ro::execute_action(
action, action,
form_state, form_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,
current_position, )
total_count, .await?
grpc_client,
).await?
}; };
return Ok((false, result)); return Ok((false, result));
} }
} }
// Show a helpful message when no binding was found
if !*edit_mode_cooldown { if !*edit_mode_cooldown {
let default_key = "i".to_string(); let default_key = "i".to_string();
let edit_key = config.keybindings.read_only.get("enter_edit_mode_before") let edit_key = config
.keybindings
.read_only
.get("enter_edit_mode_before")
.and_then(|keys| keys.first()) .and_then(|keys| keys.first())
.unwrap_or(&default_key); .map(|k| k.to_string())
.unwrap_or(default_key);
*command_message = format!("Read-only mode - press {} to edit", edit_key); *command_message = format!("Read-only mode - press {} to edit", edit_key);
} }
*edit_mode_cooldown = false;
Ok((false, command_message.clone())) Ok((false, command_message.clone()))
} }
async fn execute_action(
action: &str,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"previous_entry" | "next_entry" => {
// This will only be called when no component is active
key_sequence_tracker.reset();
Ok(format!("Navigation prev/next only available in form mode"))
}
"move_up" | "move_down" => {
// This will only be called when no component is active
key_sequence_tracker.reset();
Ok(format!("Navigation up/down only available in form mode"))
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = form_state.current_cursor_pos;
form_state.current_cursor_pos = current_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
let current_pos = form_state.current_cursor_pos;
if !current_input.is_empty() && current_pos < current_input.len() - 1 {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("Moved to previous word end".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
form_state.current_cursor_pos = current_input.len() - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_first_line" => {
// Change field first
form_state.current_field = 0;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
current_input.len()
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to first line".to_string())
}
"move_last_line" => {
// Change field first
form_state.current_field = form_state.fields.len() - 1;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
current_input.len()
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to last line".to_string())
}
_ => Ok(format!("Unknown action: {}", action)),
}
}
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();
if chars.is_empty() || current_pos >= chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.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();
if chars.is_empty() {
return 0;
}
if current_pos >= chars.len() - 1 {
return chars.len() - 1;
}
let mut pos = current_pos;
if get_char_type(chars[pos]) == CharType::Whitespace {
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
} else {
let current_type = get_char_type(chars[pos]);
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
pos += 1;
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
}
}
if pos >= chars.len() {
return chars.len() - 1;
}
let word_type = get_char_type(chars[pos]);
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
pos += 1;
}
pos
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 {
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 {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos -= 1;
let prev_word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
pos -= 1;
}
while pos < chars.len() - 1 &&
get_char_type(chars[pos + 1]) == prev_word_type {
pos += 1;
}
}
}
pos
}

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,11 +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::tui::controls::commands::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
use crate::modes::{ use crate::tui::functions::common::form::{save, revert};
canvas::{common},
};
pub async fn handle_command_event( pub async fn handle_command_event(
key: KeyEvent, key: KeyEvent,
@@ -97,7 +95,7 @@ async fn process_command(
Ok((should_exit, message, true)) Ok((should_exit, message, true))
}, },
"save" => { "save" => {
let message = common::save( let message = save(
form_state, form_state,
grpc_client, grpc_client,
&mut command_handler.is_saved, &mut command_handler.is_saved,
@@ -108,7 +106,7 @@ async fn process_command(
return Ok((false, message, true)); return Ok((false, message, true));
}, },
"revert" => { "revert" => {
let message = common::revert( let message = revert(
form_state, form_state,
grpc_client, grpc_client,
current_position, current_position,

View File

@@ -5,14 +5,16 @@ use crate::tui::terminal::{
core::TerminalCore, core::TerminalCore,
}; };
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::tui::controls::commands::CommandHandler; use crate::services::auth::AuthClient;
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;
@@ -26,12 +28,13 @@ 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_state: AuthState, // Removed
pub auth_client: AuthClient,
} }
impl EventHandler { impl EventHandler {
pub fn new() -> Self { pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
EventHandler { Ok(EventHandler {
command_mode: false, command_mode: false,
command_input: String::new(), command_input: String::new(),
command_message: String::new(), command_message: String::new(),
@@ -39,8 +42,9 @@ 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_state: AuthState::new(), // Removed
} auth_client: AuthClient::new().await?,
})
} }
pub async fn handle_event( pub async fn handle_event(
@@ -51,6 +55,7 @@ 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, // Added
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,
@@ -97,10 +102,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;
@@ -120,7 +140,6 @@ impl EventHandler {
} }
// Check for core application actions (save, quit, etc.) // 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,
@@ -128,27 +147,29 @@ 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,
auth_state, // Changed
grpc_client, grpc_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 read_only mode handle its own actions (including navigation from common bindings) // Let read_only mode handle its own actions
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, // Changed
&mut self.key_sequence_tracker, &mut self.key_sequence_tracker,
current_position, current_position,
total_count, total_count,
@@ -162,7 +183,13 @@ impl EventHandler {
AppMode::Edit => { AppMode::Edit => {
// Check for exiting edit mode // 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 { let has_changes = if app_state.ui.show_login {
auth_state.has_unsaved_changes()
} else {
form_state.has_unsaved_changes()
};
if has_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();
return Ok((false, self.command_message.clone())); return Ok((false, self.command_message.clone()));
} }
@@ -171,16 +198,31 @@ impl EventHandler {
self.command_message = "Read-only mode".to_string(); self.command_message = "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.) // 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,
@@ -188,25 +230,29 @@ 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,
auth_state, // Changed
grpc_client, grpc_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 edit mode handle its own actions
let result = edit::handle_edit_event_internal( let result = edit::handle_edit_event(
app_state.ui.show_login,
key, key,
config, config,
form_state, form_state,
auth_state, // Changed
&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,
@@ -246,6 +292,5 @@ impl EventHandler {
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

@@ -1,5 +1,4 @@
// src/services/login.rs // src/services/auth.rs
use tonic::transport::Channel; use tonic::transport::Channel;
use common::proto::multieko2::auth::{ use common::proto::multieko2::auth::{
auth_service_client::AuthServiceClient, auth_service_client::AuthServiceClient,

View File

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

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 _ => "",
} }
} }
@@ -67,4 +73,32 @@ impl CanvasState for AuthState {
fn fields(&self) -> Vec<&str> { fn fields(&self) -> Vec<&str> {
vec!["Username/Email", "Password"] vec!["Username/Email", "Password"]
} }
fn set_current_field(&mut self, index: usize) {
if index < 2 { // AuthState only has 2 fields
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) {
let len = match self.current_field {
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) {
// Allow the generic handler to signal changes
self.has_unsaved_changes = changed;
}
} }

View File

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

View File

@@ -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,5 +0,0 @@
// src/tui/controls.rs
pub mod commands;
pub use commands::*;

View File

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

View File

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

View File

@@ -1,81 +1,9 @@
// src/modes/canvas/common.rs // src/tui/functions/common/form.rs
use crate::config::binds::config::Config;
use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::form::FormState;
use crate::state::state::AppState;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
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,
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,

View File

@@ -0,0 +1,103 @@
// 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
app_state.show_dialog(
"Login Success",
&success_message,
vec!["OK".to_string()], // Pass buttons here
);
// REMOVE these lines:
// app_state.ui.dialog.dialog_title = "Login Success".to_string();
// app_state.ui.dialog.dialog_message = success_message;
// app_state.ui.dialog.dialog_show = true;
// app_state.ui.dialog.dialog_button_active = true;
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

@@ -1,6 +1,7 @@
// src/tui/functions/form.rs // src/tui/functions/form.rs
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState;
pub async fn handle_action( pub async fn handle_action(
action: &str, action: &str,
@@ -74,38 +75,6 @@ pub async fn handle_action(
Ok("Already at last entry".into()) Ok("Already at last entry".into())
} }
} }
"move_up" => {
// Change field first
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
// Get current input AFTER changing field
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 = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_down" => {
// Change field first
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
// Get current input AFTER changing field
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 = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
_ => Err("Unknown form action".into()) _ => Err("Unknown form action".into())
} }
} }

View File

@@ -8,56 +8,11 @@ pub async fn handle_action(
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
match action { match action {
"move_up" => { "previous_entry" => {
if auth_state.return_selected { Ok("Previous entry at tui/functions/login.rs not implemented".into())
// From Return button to last field (password)
auth_state.return_selected = false;
auth_state.current_field = 1;
} else if auth_state.current_field == 1 {
// Password -> Username
auth_state.current_field = 0;
} else if auth_state.current_field == 0 {
// Username -> Password (wrap around fields only)
auth_state.current_field = 1;
} else if auth_state.current_field == 2 {
// From Login button to Password field
auth_state.current_field = 1;
}
// Update cursor position only when in a field
if auth_state.current_field < 2 {
let current_input = auth_state.get_current_input();
let max_cursor_pos = current_input.len();
auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
Ok(format!("Navigation 'up' from functions/login"))
} }
"move_down" => { "next_entry" => {
if auth_state.return_selected { Ok("Next entry at tui/functions/login.rs not implemented".into())
// From Return button to first field (username)
auth_state.return_selected = false;
auth_state.current_field = 0;
} else if auth_state.current_field == 0 {
// Username -> Password
auth_state.current_field = 1;
} else if auth_state.current_field == 1 {
// Password -> Login button
auth_state.current_field = 2;
auth_state.return_selected = false;
} else if auth_state.current_field == 2 {
// Login button -> Return button
auth_state.return_selected = true;
}
// Update cursor position only when in a field
if auth_state.current_field < 2 {
let current_input = auth_state.get_current_input();
let max_cursor_pos = current_input.len();
auth_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
Ok(format!("Navigation 'down' from functions/login"))
} }
_ => Err("Unknown login action".into()) _ => Err("Unknown login action".into())
} }

View File

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

View File

@@ -2,14 +2,16 @@
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::ui_service::UiService; // Add this import use crate::services::auth::AuthClient;
use crate::tui::controls::CommandHandler; use crate::services::ui_service::UiService;
use crate::tui::terminal::EventReader; use crate::tui::terminal::EventReader;
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;
@@ -17,9 +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?; // 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()?;
@@ -30,8 +33,8 @@ 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(); let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new(); let event_reader = EventReader::new();
// Fetch the total count of Adresar entries // Fetch the total count of Adresar entries
@@ -41,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,
@@ -69,6 +75,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,
@@ -76,49 +83,74 @@ 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 // Handle position changes and update form state (Only when form is shown)
if !event_handler.is_edit_mode { if app_state.ui.show_form { // Added check
let current_input = form_state.get_current_input(); if !event_handler.is_edit_mode {
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?;
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 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(());
} }