Compare commits

...

54 Commits

Author SHA1 Message Date
filipriec
990ec9317f admin panel tiny improvement. STARTING OF ADMIN PANEL BUILDING 2025-04-14 15:27:26 +02:00
filipriec
718ceac17e cargo fix 2025-04-14 15:04:24 +02:00
filipriec
d154ba6b89 we compiled for now 2025-04-14 14:28:36 +02:00
filipriec
f2a63476b3 continuation of the fixes 2025-04-14 14:05:20 +02:00
filipriec
adcd3b37fa fixing this 2025-04-14 13:23:09 +02:00
filipriec
71dabc1e37 very bald changes, still destroyed 2025-04-14 12:07:15 +02:00
filipriec
2d724876eb going directly into adminstate from appstate for the admin page. DESTROYED 2025-04-14 11:24:56 +02:00
filipriec
1927d1fa4d appstate moved to its folder also 2025-04-13 22:52:15 +02:00
filipriec
d995fab0e4 moved canvasstate to the pages folder 2025-04-13 22:45:26 +02:00
filipriec
b4135c1626 attempt for dropdown generalization, minor change really 2025-04-13 22:14:34 +02:00
filipriec
3d0a9f2082 we successfully compiled and wen from auth state to login state and auth state 2025-04-13 17:47:00 +02:00
filipriec
1dd5f685a6 authstate splitting into login state and auth state, quite before maddness 2025-04-13 17:06:59 +02:00
filipriec
c1c4394f94 ... at the end of the dialog truncation 2025-04-13 14:58:41 +02:00
filipriec
16d9fcdadc only important stuff in the response of the login 2025-04-13 14:09:57 +02:00
filipriec
5b1db01fe6 displaying username and username contained in the jwt now 2025-04-13 14:04:30 +02:00
filipriec
e856e9d6c7 response contains username but jwt is holding username also 2025-04-13 13:45:22 +02:00
filipriec
ad2c783870 improvements on the register.rs 2025-04-13 00:09:12 +02:00
filipriec
5e101bef14 tab is triggering the suggestion dropdown menu, but ctrl+n and ctrl+p only cycle through it 2025-04-12 23:56:14 +02:00
filipriec
149949ad99 better dropdown gui 2025-04-12 22:42:06 +02:00
filipriec
741cc952fa fixed more dropdown menu 2025-04-12 18:06:19 +02:00
filipriec
d2bb7a0bf4 forgotten cargo lock 2025-04-12 17:48:35 +02:00
filipriec
d4d5bcec9e width for the dropdown fixed 2025-04-12 17:41:37 +02:00
filipriec
b4053a7b94 working perfectly well 2025-04-12 17:34:17 +02:00
filipriec
7b27d00972 working suggestions but position is wrong 2025-04-12 16:22:07 +02:00
filipriec
f4d234089f much better, still not it 2025-04-12 15:52:12 +02:00
filipriec
50a329fc0d suggestions on tab, still not working yet 2025-04-12 15:31:29 +02:00
filipriec
6d6df7ca5c still not working autocomplete 2025-04-12 00:13:28 +02:00
filipriec
6b16068706 moved to auth_e functions for dropdown from edit mode file 2025-04-11 23:42:18 +02:00
filipriec
024a0de4af completion not working yet 2025-04-11 22:54:44 +02:00
filipriec
e145d63ba6 fixing autocomplete, bombarded code, nothing in here 2025-04-11 22:39:09 +02:00
filipriec
e7e8b0b3f6 reg proper movement 2025-04-11 21:42:59 +02:00
filipriec
a7389db674 trigger dropdown, not working at all, needs proper implementation, ready for debug 2025-04-11 15:40:50 +02:00
filipriec
cf1aa4fd2a register form now has optional field role 2025-04-11 13:51:05 +02:00
filipriec
0fd2a589eb register with optional role in the post request 2025-04-11 13:37:57 +02:00
filipriec
944131d5a6 from 4e01740a61 till now, fully integrated working register 2025-04-11 08:52:01 +02:00
filipriec
eff46ac9bf working read only mode in login and register properly workig now 2025-04-11 08:50:54 +02:00
filipriec
14f9b254b2 read only mode needs adjustement to 4 fields from 2 2025-04-10 23:04:25 +02:00
filipriec
337d6050ff common mode register fix 2025-04-10 22:18:01 +02:00
filipriec
d36348b84f gRPC implementation of a registration working 2025-04-10 21:14:32 +02:00
filipriec
dfb6f5b375 registration auth services added 2025-04-10 21:00:41 +02:00
filipriec
a9089bc2ff displaying register 2025-04-10 20:01:03 +02:00
filipriec
5f5d690ff3 compiled time to render register properly well 2025-04-10 19:32:49 +02:00
filipriec
431882ece9 register 2 2025-04-10 19:27:04 +02:00
filipriec
b51e76e366 register on the way 2025-04-10 18:50:54 +02:00
filipriec
4e01740a61 fixed exit in the login dialog 2025-04-10 16:34:29 +02:00
filipriec
e729ed9df3 compiled 2025-04-10 16:05:06 +02:00
filipriec
6b241304fb dialog login functionality 2025-04-10 15:36:43 +02:00
filipriec
3ed8764087 cargo fix 2025-04-10 14:45:16 +02:00
filipriec
df61b245ab back to main 2025-04-10 14:42:11 +02:00
filipriec
7a364d654c repaired 2025-04-10 14:22:30 +02:00
filipriec
0d1a0be1a0 dialog movement fixed 2025-04-10 14:13:39 +02:00
filipriec
5da9f5aaf4 better, but more dialog logic is needed 2025-04-10 13:45:36 +02:00
filipriec
2bec0f5850 dialog 2 2025-04-10 13:40:24 +02:00
filipriec
5bc28ec38b dialog 2025-04-10 13:37:15 +02:00
59 changed files with 1640 additions and 465 deletions

9
Cargo.lock generated
View File

@@ -421,13 +421,14 @@ dependencies = [
[[package]] [[package]]
name = "client" name = "client"
version = "0.3.3" version = "0.3.5"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"common", "common",
"crossterm", "crossterm",
"dirs 6.0.0", "dirs 6.0.0",
"dotenvy", "dotenvy",
"lazy_static",
"prost", "prost",
"ratatui", "ratatui",
"serde", "serde",
@@ -435,6 +436,8 @@ dependencies = [
"toml", "toml",
"tonic", "tonic",
"tracing", "tracing",
"unicode-segmentation",
"unicode-width 0.2.0",
] ]
[[package]] [[package]]
@@ -458,7 +461,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "0.3.3" version = "0.3.5"
dependencies = [ dependencies = [
"prost", "prost",
"serde", "serde",
@@ -2589,7 +2592,7 @@ dependencies = [
[[package]] [[package]]
name = "server" name = "server"
version = "0.3.3" version = "0.3.5"
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.3.3" version = "0.3.5"
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

@@ -11,6 +11,7 @@ common = { path = "../common" }
crossterm = "0.28.1" crossterm = "0.28.1"
dirs = "6.0.0" dirs = "6.0.0"
dotenvy = "0.15.7" dotenvy = "0.15.7"
lazy_static = "1.5.0"
prost = "0.13.5" prost = "0.13.5"
ratatui = "0.29.0" ratatui = "0.29.0"
serde = { version = "1.0.218", features = ["derive"] } serde = { version = "1.0.218", features = ["derive"] }
@@ -18,3 +19,5 @@ tokio = { version = "1.43.0", features = ["full", "macros"] }
toml = "0.8.20" toml = "0.8.20"
tonic = "0.12.3" tonic = "0.12.3"
tracing = "0.1.41" tracing = "0.1.41"
unicode-segmentation = "1.12.0"
unicode-width = "0.2.0"

View File

@@ -50,10 +50,14 @@ move_last_line = ["x"]
exit_edit_mode = ["esc","ctrl+e"] exit_edit_mode = ["esc","ctrl+e"]
delete_char_forward = ["delete"] delete_char_forward = ["delete"]
delete_char_backward = ["backspace"] delete_char_backward = ["backspace"]
next_field = ["tab", "enter"] next_field = ["enter"]
prev_field = ["shift+tab", "backtab"] prev_field = ["shift+enter"]
move_left = ["left"] move_left = ["left"]
move_right = ["right"] move_right = ["right"]
suggestion_down = ["ctrl+n", "tab"]
suggestion_up = ["ctrl+p", "shift+tab"]
select_suggestion = ["enter"]
exit_suggestion_mode = ["esc"]
[keybindings.command] [keybindings.command]
exit_command_mode = ["ctrl+g", "esc"] exit_command_mode = ["ctrl+g", "esc"]

View File

@@ -1,118 +1,108 @@
// src/components/admin/admin_panel.rs // src/components/admin/admin_panel.rs
use crate::config::colors::themes::Theme;
use crate::state::pages::admin::AdminState; // Import the persistent state
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use ratatui::{ use ratatui::{
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
style::Style,
text::{Line, Span, Text},
layout::{Alignment, Constraint, Direction, Layout, Rect}, layout::{Alignment, Constraint, Direction, Layout, Rect},
style::Style, // Added Modifier
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
Frame, Frame,
}; };
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::config::colors::themes::Theme;
pub struct AdminPanelState { // Renamed from AdminPanelState::render and made a standalone function
pub list_state: ListState, pub fn render_admin_panel(
pub profiles: Vec<String>, f: &mut Frame,
} admin_state: &AdminState, // Accept the persistent state (immutable borrow is enough for rendering)
area: Rect,
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>, // The globally selected profile for the checkmark
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.style(Style::default().bg(theme.bg));
impl AdminPanelState { let inner_area = block.inner(area);
pub fn new(profiles: Vec<String>) -> Self { f.render_widget(block, area);
let mut list_state = ListState::default();
if !profiles.is_empty() {
list_state.select(Some(0));
}
Self { list_state, profiles }
}
pub fn next(&mut self) { let chunks = Layout::default()
let i = self.list_state.selected().map_or(0, |i| .direction(Direction::Vertical)
if i >= self.profiles.len() - 1 { 0 } else { i + 1 }); .constraints([Constraint::Length(3), Constraint::Min(1)])
self.list_state.select(Some(i)); .split(inner_area);
}
pub fn previous(&mut self) { // Title
let i = self.list_state.selected().map_or(0, |i| let title = Line::from(Span::styled("Admin Panel", Style::default().fg(theme.highlight)));
if i == 0 { self.profiles.len() - 1 } else { i - 1 }); let title_widget = Paragraph::new(title).alignment(Alignment::Center);
self.list_state.select(Some(i)); f.render_widget(title_widget, chunks[0]);
}
pub fn render( // Content
&mut self, let content_chunks = Layout::default()
f: &mut Frame, .direction(Direction::Horizontal)
area: Rect, .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
theme: &Theme, .split(chunks[1]);
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.style(Style::default().bg(theme.bg));
let inner_area = block.inner(area); // Profile list - Use data from admin_state
f.render_widget(block, area); let items: Vec<ListItem> = admin_state
.profiles // Use profiles from the persistent state
let chunks = Layout::default() .iter()
.direction(Direction::Vertical) .map(|p| {
.constraints([Constraint::Length(3), Constraint::Min(1)]) ListItem::new(Line::from(vec![
.split(inner_area);
// Title
let title = Line::from(Span::styled("Admin Panel", Style::default().fg(theme.highlight)));
let title_widget = Paragraph::new(title).alignment(Alignment::Center);
f.render_widget(title_widget, chunks[0]);
// Content
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
.split(chunks[1]);
// Profile list
let items: Vec<ListItem> = self.profiles.iter()
.map(|p| ListItem::new(Line::from(vec![
Span::styled( Span::styled(
// Check against the globally selected profile for the checkmark
if Some(p) == selected_profile.as_ref() { "" } else { " " }, if Some(p) == selected_profile.as_ref() { "" } else { " " },
Style::default().fg(theme.accent) Style::default().fg(theme.accent),
), ),
Span::styled(p, Style::default().fg(theme.fg)), Span::styled(p, Style::default().fg(theme.fg)),
]))) ]))
.collect(); })
.collect();
let list = List::new(items) let list = List::new(items)
.block(Block::default().title("Profiles")) .block(Block::default().title("Profiles"))
.highlight_style(Style::default().bg(theme.highlight).fg(theme.bg)); .highlight_style(Style::default().bg(theme.highlight).fg(theme.bg));
f.render_stateful_widget(list, content_chunks[0], &mut self.list_state);
// Profile details // Render statefully using a CLONE of the list_state from persistent AdminState
if let Some(profile) = self.list_state.selected() // Cloning is necessary because render_stateful_widget needs `&mut ListState`
.and_then(|i| profile_tree.profiles.get(i)) // but we only have `&AdminState`. This is a common pattern in Ratatui.
{ let mut list_state_clone = admin_state.list_state.clone();
let mut text = Text::default(); f.render_stateful_widget(list, content_chunks[0], &mut list_state_clone);
text.lines.push(Line::from(vec![
Span::styled("Profile: ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]));
text.lines.push(Line::from("")); // Profile details - Use selection info from admin_state
text.lines.push(Line::from(Span::styled("Tables:", Style::default().fg(theme.accent)))); if let Some(profile) = admin_state
.get_selected_index() // Use the method from persistent state
for table in &profile.tables { .and_then(|i| profile_tree.profiles.get(i))
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)]; {
if !table.depends_on.is_empty() { let mut text = Text::default();
line.push(Span::styled( text.lines.push(Line::from(vec![
format!("{}", table.depends_on.join(", ")), Span::styled("Profile: ", Style::default().fg(theme.accent)),
Style::default().fg(theme.secondary) Span::styled(&profile.name, Style::default().fg(theme.highlight)),
)); ]));
}
text.lines.push(Line::from(line)); text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
"Tables:",
Style::default().fg(theme.accent),
)));
for table in &profile.tables {
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
if !table.depends_on.is_empty() {
line.push(Span::styled(
format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary),
));
} }
text.lines.push(Line::from(line));
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"));
f.render_widget(details_widget, content_chunks[1]);
} }
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"))
.wrap(Wrap { trim: true }); // Add wrapping
f.render_widget(details_widget, content_chunks[1]);
} }
} }

View File

@@ -3,3 +3,4 @@ pub mod login;
pub mod register; pub mod register;
pub use login::*; pub use login::*;
pub use register::*;

View File

@@ -2,11 +2,10 @@
use crate::{ use crate::{
config::colors::themes::Theme, config::colors::themes::Theme,
state::pages::auth::AuthState, state::pages::auth::LoginState,
components::common::dialog, components::common::dialog,
state::state::AppState, state::app::state::AppState,
}; };
use crate::modes::handlers::mode_manager::AppMode;
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color}, style::{Style, Modifier, Color},
@@ -18,7 +17,7 @@ pub fn render_login(
f: &mut Frame, f: &mut Frame,
area: Rect, area: Rect,
theme: &Theme, theme: &Theme,
state: &AuthState, login_state: &LoginState,
app_state: &AppState, app_state: &AppState,
is_edit_mode: bool, is_edit_mode: bool,
) { ) {
@@ -51,16 +50,16 @@ pub fn render_login(
crate::components::handlers::canvas::render_canvas( crate::components::handlers::canvas::render_canvas(
f, f,
chunks[0], chunks[0],
state, login_state,
&["Username/Email", "Password"], &["Username/Email", "Password"],
&state.current_field, &login_state.current_field,
&[&state.username, &state.password], &[&login_state.username, &login_state.password],
theme, theme,
is_edit_mode, is_edit_mode,
); );
// --- ERROR MESSAGE --- // --- ERROR MESSAGE ---
if let Some(err) = &state.error_message { if let Some(err) = &login_state.error_message {
f.render_widget( f.render_widget(
Paragraph::new(err.as_str()) Paragraph::new(err.as_str())
.style(Style::default().fg(Color::Red)) .style(Style::default().fg(Color::Red))
@@ -78,7 +77,7 @@ pub fn render_login(
// Login Button // Login Button
let login_button_index = 0; let login_button_index = 0;
let login_active = if app_state.ui.focus_outside_canvas { let login_active = if app_state.ui.focus_outside_canvas {
app_state.general.selected_item == login_button_index app_state.focused_button_index== login_button_index
} else { } else {
false false
}; };
@@ -105,7 +104,7 @@ pub fn render_login(
// Return Button // Return Button
let return_button_index = 1; // Assuming Return is the second general element let return_button_index = 1; // Assuming Return is the second general element
let return_active = if app_state.ui.focus_outside_canvas { let return_active = if app_state.ui.focus_outside_canvas {
app_state.general.selected_item == return_button_index app_state.focused_button_index== return_button_index
} else { } else {
false // Not active if focus is in canvas or other modes false // Not active if focus is in canvas or other modes
}; };

View File

@@ -0,0 +1,170 @@
// src/components/auth/register.rs
use crate::{
config::colors::themes::Theme,
state::pages::auth::RegisterState, // Use RegisterState
components::common::{dialog, autocomplete},
state::app::state::AppState,
state::pages::canvas_state::CanvasState,
modes::handlers::mode_manager::AppMode,
};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
};
pub fn render_register(
f: &mut Frame,
area: Rect,
theme: &Theme,
state: &RegisterState, // Use RegisterState
app_state: &AppState,
is_edit_mode: bool,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(Style::default().fg(theme.border))
.title(" Register ") // Update title
.style(Style::default().bg(theme.bg));
f.render_widget(block, area);
let inner_area = area.inner(Margin {
horizontal: 1,
vertical: 1,
});
// Adjust constraints for 4 fields + error + buttons
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(7), // Form (5 fields + padding)
Constraint::Length(1), // Help text line
Constraint::Length(1), // Error message
Constraint::Length(3), // Buttons
])
.split(inner_area);
// --- FORM RENDERING (Using render_canvas) ---
let active_field_rect = crate::components::handlers::canvas::render_canvas(
f,
chunks[0], // Area for the canvas
state, // The state object (RegisterState)
&[ // Field labels
"Username",
"Email*",
"Password*",
"Confirm Password",
"Role* (Tab)",
],
&state.current_field(), // Pass current field index
&state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(), // Pass inputs directly
theme,
is_edit_mode,
);
// --- HELP TEXT ---
let help_text = Paragraph::new("* are optional fields")
.style(Style::default().fg(theme.fg))
.alignment(Alignment::Center);
f.render_widget(help_text, chunks[1]);
// --- 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[2],
);
}
// --- BUTTONS ---
let button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(chunks[3]);
// Register Button
let register_button_index = 0;
let register_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== register_button_index
} else {
false
};
let mut register_style = Style::default().fg(theme.fg);
let mut register_border = Style::default().fg(theme.border);
if register_active {
register_style = register_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
register_border = register_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Register") // Update button text
.style(register_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(register_border),
),
button_chunks[0],
);
// Return Button (logic remains similar)
let return_button_index = 1;
let return_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== return_button_index
} else {
false
};
let mut return_style = Style::default().fg(theme.fg);
let mut return_border = Style::default().fg(theme.border);
if return_active {
return_style = return_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
return_border = return_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Return")
.style(return_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(return_border),
),
button_chunks[1],
);
// --- Render Autocomplete Dropdown (Draw AFTER buttons) ---
if app_state.current_mode == AppMode::Edit {
if let Some(suggestions) = state.get_suggestions() {
let selected = state.get_selected_suggestion_index();
if !suggestions.is_empty() {
if let Some(input_rect) = active_field_rect {
autocomplete::render_autocomplete_dropdown(f, input_rect, f.size(), theme, suggestions, selected);
}
}
}
}
// --- DIALOG --- (Keep dialog logic)
if app_state.ui.dialog.dialog_show {
dialog::render_dialog(
f,
f.area(),
theme,
&app_state.ui.dialog.dialog_title,
&app_state.ui.dialog.dialog_message,
&app_state.ui.dialog.dialog_buttons,
app_state.ui.dialog.dialog_active_button_index,
);
}
}

View File

@@ -3,8 +3,10 @@ pub mod command_line;
pub mod status_line; pub mod status_line;
pub mod background; pub mod background;
pub mod dialog; pub mod dialog;
pub mod autocomplete;
pub use command_line::*; pub use command_line::*;
pub use status_line::*; pub use status_line::*;
pub use background::*; pub use background::*;
pub use dialog::*; pub use dialog::*;
pub use autocomplete::*;

View File

@@ -0,0 +1,90 @@
// src/components/common/autocomplete.rs
use crate::config::colors::themes::Theme;
use ratatui::{
layout::Rect,
style::{Color, Modifier, Style},
widgets::{Block, List, ListItem, ListState},
Frame,
};
use unicode_width::UnicodeWidthStr;
/// Renders an opaque dropdown list for autocomplete suggestions.
pub fn render_autocomplete_dropdown(
f: &mut Frame,
input_rect: Rect,
frame_area: Rect,
theme: &Theme,
suggestions: &[String],
selected_index: Option<usize>,
) {
if suggestions.is_empty() {
return;
}
// --- Calculate Dropdown Size & Position ---
let max_suggestion_width = suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
let horizontal_padding: u16 = 2;
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
let dropdown_height = (suggestions.len() as u16).min(5);
let mut dropdown_area = Rect {
x: input_rect.x, // Align horizontally with input
y: input_rect.y + 1, // Position directly below input
width: dropdown_width,
height: dropdown_height,
};
// --- Clamping Logic (prevent rendering off-screen) ---
// Clamp vertically (if it goes below the frame)
if dropdown_area.bottom() > frame_area.height {
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height); // Try rendering above
}
// Clamp horizontally (if it goes past the right edge)
if dropdown_area.right() > frame_area.width {
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
}
// Ensure x is not negative (if clamping pushes it left)
dropdown_area.x = dropdown_area.x.max(0);
// Ensure y is not negative (if clamping pushes it up)
dropdown_area.y = dropdown_area.y.max(0);
// --- End Clamping ---
// Render a solid background block first to ensure opacity
let background_block = Block::default().style(Style::default().bg(Color::DarkGray));
f.render_widget(background_block, dropdown_area);
// Create list items, ensuring each has a defined background
let items: Vec<ListItem> = suggestions
.iter()
.enumerate()
.map(|(i, s)| {
let is_selected = selected_index == Some(i);
let s_width = s.width() as u16;
let padding_needed = dropdown_width.saturating_sub(s_width);
let padded_s = format!("{}{}", s, " ".repeat(padding_needed as usize));
ListItem::new(padded_s).style(if is_selected {
Style::default()
.fg(theme.bg) // Text color on highlight
.bg(theme.highlight) // Highlight background
.add_modifier(Modifier::BOLD)
} else {
// Style for non-selected items (matching background block)
Style::default()
.fg(theme.fg) // Text color on gray
.bg(Color::DarkGray) // Explicit gray background
})
})
.collect();
// Create the list widget (without its own block)
let list = List::new(items);
// State for managing selection highlight (still needed for logic)
let mut list_state = ListState::default();
list_state.select(selected_index);
// Render the list statefully *over* the background block
f.render_stateful_widget(list, dropdown_area, &mut list_state);
}

View File

@@ -1,13 +1,14 @@
// src/components/common/dialog.rs
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use ratatui::{ use ratatui::{
layout::{Constraint, Direction, Layout, Margin, Rect}, layout::{Constraint, Direction, Layout, Margin, Rect},
prelude::Alignment, prelude::Alignment,
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span, Text}, text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Paragraph, Clear}, // Added Clear widgets::{Block, BorderType, Borders, Paragraph, Clear},
Frame, Frame,
}; };
use unicode_segmentation::UnicodeSegmentation; // For grapheme clusters
use unicode_width::UnicodeWidthStr; // For accurate width calculation
pub fn render_dialog( pub fn render_dialog(
f: &mut Frame, f: &mut Frame,
@@ -18,15 +19,16 @@ pub fn render_dialog(
dialog_buttons: &[String], dialog_buttons: &[String],
dialog_active_button_index: usize, dialog_active_button_index: usize,
) { ) {
// Calculate required height based on the actual number of lines in the message
let message_lines: Vec<_> = dialog_message.lines().collect(); let message_lines: Vec<_> = dialog_message.lines().collect();
let message_height = message_lines.len() as u16; let message_height = message_lines.len() as u16;
let button_row_height = if dialog_buttons.is_empty() { 0 } else { 3 }; let button_row_height = if dialog_buttons.is_empty() { 0 } else { 3 };
let vertical_padding = 2; // Block borders (top/bottom) let vertical_padding = 2; // Block borders (top/bottom)
let inner_vertical_margin = 2; // Margin inside block (top/bottom) let inner_vertical_margin = 2; // Margin inside block (top/bottom)
// Calculate required height based on actual message lines
let required_inner_height = let required_inner_height =
message_height + button_row_height + inner_vertical_margin; message_height + button_row_height + inner_vertical_margin;
// Add block border height
let required_total_height = required_inner_height + vertical_padding; let required_total_height = required_inner_height + vertical_padding;
// Use a fixed percentage width, clamped to min/max // Use a fixed percentage width, clamped to min/max
@@ -61,10 +63,10 @@ pub fn render_dialog(
vertical: 1, // Top/Bottom padding inside border vertical: 1, // Top/Bottom padding inside border
}); });
// Layout for Message and Buttons // Layout for Message and Buttons based on actual message height
let mut constraints = vec![ let mut constraints = vec![
// Allocate space for message, ensuring at least 1 line height // Allocate space for message, ensuring at least 1 line height
Constraint::Min(message_height.max(1)), Constraint::Length(message_height.max(1)), // Use actual calculated height
]; ];
if button_row_height > 0 { if button_row_height > 0 {
constraints.push(Constraint::Length(button_row_height)); constraints.push(Constraint::Length(button_row_height));
@@ -76,15 +78,39 @@ pub fn render_dialog(
.split(inner_area); .split(inner_area);
// Render Message // Render Message
let message_text = Text::from( let available_width = inner_area.width as usize;
let ellipsis = "...";
let ellipsis_width = UnicodeWidthStr::width(ellipsis);
let processed_lines: Vec<Line> =
message_lines message_lines
.into_iter() .into_iter()
.map(|l| Line::from(Span::styled(l, Style::default().fg(theme.fg)))) .map(|line| {
.collect::<Vec<_>>(), let line_width = UnicodeWidthStr::width(line);
); if line_width > available_width {
// Truncate with ellipsis
let mut truncated_len = 0;
let mut current_width = 0;
// Iterate over graphemes to handle multi-byte characters correctly
for (idx, grapheme) in line.grapheme_indices(true) {
let grapheme_width = UnicodeWidthStr::width(grapheme);
if current_width + grapheme_width > available_width.saturating_sub(ellipsis_width) {
break; // Stop before exceeding width needed for text + ellipsis
}
current_width += grapheme_width;
truncated_len = idx + grapheme.len(); // Store the byte index of the end of the last fitting grapheme
}
let truncated_line = format!("{}{}", &line[..truncated_len], ellipsis);
Line::from(Span::styled(truncated_line, Style::default().fg(theme.fg)))
} else {
// Line fits, use it as is
Line::from(Span::styled(line, Style::default().fg(theme.fg)))
}
})
.collect();
let message_paragraph = let message_paragraph =
Paragraph::new(message_text).alignment(Alignment::Center); Paragraph::new(Text::from(processed_lines)).alignment(Alignment::Center);
// Render message in the first chunk // Render message in the first chunk
f.render_widget(message_paragraph, chunks[0]); f.render_widget(message_paragraph, chunks[0]);
@@ -143,4 +169,3 @@ pub fn render_dialog(
} }
} }
} }

View File

@@ -6,7 +6,7 @@ use ratatui::{
Frame, Frame,
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::components::handlers::canvas::render_canvas; use crate::components::handlers::canvas::render_canvas;
pub fn render_form( pub fn render_form(

View File

@@ -8,7 +8,7 @@ use ratatui::{
prelude::Alignment, prelude::Alignment,
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
pub fn render_canvas( pub fn render_canvas(
f: &mut Frame, f: &mut Frame,
@@ -19,7 +19,7 @@ pub fn render_canvas(
inputs: &[&String], inputs: &[&String],
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
) { ) -> Option<Rect> {
// Split area into columns // Split area into columns
let columns = Layout::default() let columns = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
@@ -56,6 +56,8 @@ pub fn render_canvas(
.constraints(vec![Constraint::Length(1); fields.len()]) .constraints(vec![Constraint::Length(1); fields.len()])
.split(input_area); .split(input_area);
let mut active_field_input_rect = None;
// Render labels // Render labels
for (i, field) in fields.iter().enumerate() { for (i, field) in fields.iter().enumerate() {
let label = Paragraph::new(Line::from(Span::styled( let label = Paragraph::new(Line::from(Span::styled(
@@ -84,9 +86,12 @@ pub fn render_canvas(
f.render_widget(input_display, input_rows[i]); f.render_widget(input_display, input_rows[i]);
if is_active { if is_active {
active_field_input_rect = Some(input_rows[i]);
let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16; let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16;
let cursor_y = input_rows[i].y; let cursor_y = input_rows[i].y;
f.set_cursor_position((cursor_x, cursor_y)); f.set_cursor_position((cursor_x, cursor_y));
} }
} }
active_field_input_rect
} }

View File

@@ -33,7 +33,7 @@ impl IntroState {
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([ .constraints([
Constraint::Percentage(40), Constraint::Percentage(40),
Constraint::Length(5), // Increased to accommodate 3 buttons Constraint::Length(5),
Constraint::Percentage(40), Constraint::Percentage(40),
]) ])
.split(inner_area); .split(inner_area);
@@ -48,51 +48,44 @@ impl IntroState {
.alignment(Alignment::Center); .alignment(Alignment::Center);
f.render_widget(title_para, chunks[1]); f.render_widget(title_para, chunks[1]);
// Buttons - now with 3 options // Buttons - now with 4 options
let button_area = Layout::default() let button_area = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([ .constraints([
Constraint::Percentage(33), Constraint::Percentage(25),
Constraint::Percentage(33), Constraint::Percentage(25),
Constraint::Percentage(33), Constraint::Percentage(25),
Constraint::Percentage(25),
]) ])
.split(chunks[1].inner(Margin { .split(chunks[1].inner(Margin {
horizontal: 1, horizontal: 1,
vertical: 1 vertical: 1
})); }));
self.render_button( let buttons = ["Continue", "Admin", "Login", "Register"];
f, for (i, &text) in buttons.iter().enumerate() {
button_area[0], self.render_button(
"Continue", f,
self.selected_option == 0, button_area[i],
theme, text,
); self.selected_option == i,
self.render_button( theme,
f, );
button_area[1], }
"Admin",
self.selected_option == 1,
theme,
);
self.render_button(
f,
button_area[2],
"Login",
self.selected_option == 2,
theme,
);
} }
fn render_button(&self, f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) { fn render_button(&self, f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
let button_style = if selected { let button_style = Style::default()
Style::default() .fg(if selected { theme.highlight } else { theme.fg })
.fg(theme.highlight) .bg(theme.bg)
.bg(theme.bg) .add_modifier(if selected {
.add_modifier(ratatui::style::Modifier::BOLD) ratatui::style::Modifier::BOLD
} else { } else {
Style::default().fg(theme.fg).bg(theme.bg) ratatui::style::Modifier::empty()
}; });
let border_style = Style::default()
.fg(if selected { theme.accent } else { theme.border });
let button = Paragraph::new(text) let button = Paragraph::new(text)
.style(button_style) .style(button_style)
@@ -101,21 +94,17 @@ impl IntroState {
Block::default() Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_type(BorderType::Double) .border_type(BorderType::Double)
.border_style(if selected { .border_style(border_style),
Style::default().fg(theme.accent)
} else {
Style::default().fg(theme.border)
}),
); );
f.render_widget(button, area); f.render_widget(button, area);
} }
pub fn next_option(&mut self) { pub fn next_option(&mut self) {
self.selected_option = (self.selected_option + 1) % 3; self.selected_option = (self.selected_option + 1) % 4;
} }
pub fn previous_option(&mut self) { pub fn previous_option(&mut self) {
self.selected_option = if self.selected_option == 0 { 2 } else { self.selected_option - 1 }; self.selected_option = if self.selected_option == 0 { 3 } else { self.selected_option - 1 };
} }
} }

View File

@@ -2,7 +2,7 @@
pub mod read_only; pub mod read_only;
pub mod edit; pub mod edit;
pub mod navigation;
pub use read_only::*; pub use read_only::*;
pub use edit::*; pub use edit::*;

View File

@@ -1,8 +1,9 @@
// src/functions/modes/edit/auth_e.rs // src/functions/modes/edit/auth_e.rs
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::{auth::AuthState, form::FormState}; use crate::state::pages::form::FormState;
use crate::state::pages::auth::RegisterState;
use crate::tui::functions::common::form::{revert, save}; use crate::tui::functions::common::form::{revert, save};
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any; use std::any::Any;
@@ -56,7 +57,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
} }
} }
pub async fn execute_edit_action<S: CanvasState>( pub async fn execute_edit_action<S: CanvasState + Any + Send>(
action: &str, action: &str,
key: KeyEvent, key: KeyEvent,
state: &mut S, state: &mut S,
@@ -297,6 +298,63 @@ pub async fn execute_edit_action<S: CanvasState>(
Ok("Moved to previous word end".to_string()) Ok("Moved to previous word end".to_string())
} }
// --- Autocomplete Actions ---
"suggestion_down" | "suggestion_up" | "select_suggestion" | "exit_suggestion_mode" => {
// Attempt to downcast to RegisterState to handle suggestion logic here
if let Some(register_state) = (state as &mut dyn Any).downcast_mut::<RegisterState>() {
// Only handle if it's the role field (index 4)
if register_state.current_field() == 4 {
match action {
"suggestion_down" if register_state.in_suggestion_mode => {
let max_index = register_state.role_suggestions.len().saturating_sub(1);
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index >= max_index { 0 } else { current_index + 1 });
Ok("Suggestion changed down".to_string())
}
"suggestion_up" if register_state.in_suggestion_mode => {
let max_index = register_state.role_suggestions.len().saturating_sub(1);
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index == 0 { max_index } else { current_index.saturating_sub(1) });
Ok("Suggestion changed up".to_string())
}
"select_suggestion" if register_state.in_suggestion_mode => {
if let Some(index) = register_state.selected_suggestion_index {
if let Some(selected_role) = register_state.role_suggestions.get(index).cloned() {
register_state.role = selected_role.clone(); // Update the role field
register_state.in_suggestion_mode = false; // Exit suggestion mode
register_state.show_role_suggestions = false; // Hide suggestions
register_state.selected_suggestion_index = None; // Clear selection
Ok(format!("Selected role: {}", selected_role)) // Return success message
} else {
Ok("Selected suggestion index out of bounds.".to_string()) // Error case
}
} else {
Ok("No suggestion selected".to_string())
}
}
"exit_suggestion_mode" => { // Handle Esc or other conditions
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
register_state.in_suggestion_mode = false;
Ok("Suggestions hidden".to_string())
}
_ => {
// Action is suggestion-related but state doesn't match (e.g., not in suggestion mode)
Ok("Suggestion action ignored: State mismatch.".to_string())
}
}
} else {
// It's RegisterState, but not the role field
Ok("Suggestion action ignored: Not on role field.".to_string())
}
} else {
// Downcast failed - this action is only for RegisterState
Ok(format!("Action '{}' not applicable for this state type.", action))
}
}
// --- End Autocomplete Actions ---
_ => Ok(format!("Unknown or unhandled edit action: {}", action)), _ => Ok(format!("Unknown or unhandled edit action: {}", action)),
} }
} }

View File

@@ -1,7 +1,7 @@
// src/functions/modes/edit/form_e.rs // src/functions/modes/edit/form_e.rs
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::tui::functions::common::form::{revert, save}; use crate::tui::functions::common::form::{revert, save};
use crate::tui::functions::common::form::SaveOutcome; use crate::tui::functions::common::form::SaveOutcome;

View File

@@ -0,0 +1,3 @@
// src/functions/modes/navigation.rs
// pub mod admin_nav;

View File

@@ -0,0 +1 @@
// src/functions/modes/navigation/admin_nav.rs

View File

@@ -1,8 +1,8 @@
// src/functions/modes/read_only/auth_ro.rs // src/functions/modes/read_only/auth_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::state::state::AppState; use crate::state::app::state::AppState;
use std::error::Error; use std::error::Error;
#[derive(PartialEq)] #[derive(PartialEq)]
@@ -60,7 +60,7 @@ pub async fn execute_action<S: CanvasState>(
if current_field == last_field_index { if current_field == last_field_index {
// Already on the last field, move focus outside // Already on the last field, move focus outside
app_state.ui.focus_outside_canvas = true; app_state.ui.focus_outside_canvas = true;
app_state.general.selected_item = 0; // Focus first general item (e.g., Login button) app_state.focused_button_index= 0;
key_sequence_tracker.reset(); key_sequence_tracker.reset();
Ok("Focus moved below canvas".to_string()) Ok("Focus moved below canvas".to_string())
} else { } else {

View File

@@ -1,7 +1,7 @@
// src/functions/modes/read_only/form_ro.rs // src/functions/modes/read_only/form_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use std::error::Error; use std::error::Error;
#[derive(PartialEq)] #[derive(PartialEq)]

View File

@@ -1,21 +1,24 @@
// src/modes/canvas/common_mode.rs // src/modes/canvas/common_mode.rs
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::{form::FormState, auth::AuthState}; use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState, auth::AuthState};
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::form::SaveOutcome; use crate::tui::functions::common::form::SaveOutcome;
use crate::tui::functions::common::{ use crate::tui::functions::common::{
form::{save as form_save, revert as form_revert}, form::{save as form_save, revert as form_revert},
login::{save as login_save, revert as login_revert} login::{save as login_save, revert as login_revert},
register::{save as register_save, revert as register_revert},
}; };
pub async fn handle_core_action( pub async fn handle_core_action(
action: &str, action: &str,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState, auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient, auth_client: &mut AuthClient,
terminal: &mut TerminalCore, terminal: &mut TerminalCore,
@@ -26,7 +29,10 @@ pub async fn handle_core_action(
match action { match action {
"save" => { "save" => {
if app_state.ui.show_login { if app_state.ui.show_login {
let message = login_save(auth_state, auth_client, app_state).await?; let message = login_save(auth_state, login_state, auth_client, app_state).await?;
Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register {
let message = register_save(register_state, auth_client, app_state).await?;
Ok(EventOutcome::Ok(message)) Ok(EventOutcome::Ok(message))
} else { } else {
let save_outcome = form_save( let save_outcome = form_save(
@@ -49,7 +55,9 @@ pub async fn handle_core_action(
}, },
"save_and_quit" => { "save_and_quit" => {
let message = if app_state.ui.show_login { let message = if app_state.ui.show_login {
login_save(auth_state, auth_client, app_state).await? login_save(auth_state, login_state, auth_client, app_state).await?
} else if app_state.ui.show_register {
register_save(register_state, auth_client, app_state).await?
} else { } else {
let save_outcome = form_save( let save_outcome = form_save(
form_state, form_state,
@@ -68,7 +76,10 @@ pub async fn handle_core_action(
}, },
"revert" => { "revert" => {
if app_state.ui.show_login { if app_state.ui.show_login {
let message = login_revert(auth_state, app_state).await; let message = login_revert(login_state, app_state).await;
Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register {
let message = register_revert(register_state, app_state).await;
Ok(EventOutcome::Ok(message)) Ok(EventOutcome::Ok(message))
} else { } else {
let message = form_revert( let message = form_revert(

View File

@@ -2,22 +2,26 @@
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::{auth::AuthState, form::FormState}; use crate::state::pages::{auth::{LoginState, RegisterState}};
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::functions::modes::edit::{auth_e, form_e}; use crate::functions::modes::edit::{auth_e, form_e};
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
use crossterm::event::{KeyCode, KeyEvent}; use crate::state::app::state::AppState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
pub async fn handle_edit_event( pub async fn handle_edit_event(
is_auth_context: bool,
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState, login_state: &mut LoginState,
register_state: &mut RegisterState,
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
command_message: &mut String, command_message: &mut String,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
app_state: &AppState,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
// Global command mode check // Global command mode check
@@ -37,10 +41,18 @@ pub async fn handle_edit_event(
key.modifiers key.modifiers
) { ) {
if matches!(action, "save" | "revert") { if matches!(action, "save" | "revert") {
let message = if is_auth_context { let message = if app_state.ui.show_login {
auth_e::execute_common_action( auth_e::execute_common_action(
action, action,
auth_state, // Concrete AuthState login_state,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_common_action(
action,
register_state,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count
@@ -55,7 +67,7 @@ pub async fn handle_edit_event(
).await ).await
.map(|outcome| match outcome { .map(|outcome| match outcome {
EventOutcome::Ok(msg) => msg, EventOutcome::Ok(msg) => msg,
EventOutcome::Exit(msg) => format!("Exit requested: {}", msg), // Or handle differently EventOutcome::Exit(msg) => format!("Exit requested: {}", msg),
EventOutcome::DataSaved(save_outcome, msg) => format!("Data saved ({:?}): {}", save_outcome, msg), EventOutcome::DataSaved(save_outcome, msg) => format!("Data saved ({:?}): {}", save_outcome, msg),
EventOutcome::ButtonSelected { context, index } => { EventOutcome::ButtonSelected { context, index } => {
"Unexpected action in edit mode".to_string() "Unexpected action in edit mode".to_string()
@@ -68,11 +80,36 @@ pub async fn handle_edit_event(
// Edit-specific actions // 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 if is_auth_context { // --- Special Handling for Tab/Shift+Tab in Role Field ---
if app_state.ui.show_register && register_state.current_field() == 4 {
if !register_state.in_suggestion_mode && key.code == KeyCode::Tab && key.modifiers == KeyModifiers::NONE {
register_state.update_role_suggestions();
if !register_state.role_suggestions.is_empty() {
register_state.in_suggestion_mode = true;
register_state.selected_suggestion_index = Some(0); // Select first suggestion
return Ok("Suggestions shown".to_string());
} else {
return Ok("No suggestions available".to_string());
}
}
}
// --- End Special Handling ---
return if app_state.ui.show_login {
auth_e::execute_edit_action( auth_e::execute_edit_action(
action, action,
key, key,
auth_state, // Full access to AuthState fields login_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_edit_action(
action,
key,
register_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
@@ -82,7 +119,7 @@ pub async fn handle_edit_event(
form_e::execute_edit_action( form_e::execute_edit_action(
action, action,
key, key,
form_state, // Full access to FormState fields form_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
@@ -93,11 +130,30 @@ pub async fn handle_edit_event(
// Character insertion // Character insertion
if let KeyCode::Char(_) = key.code { if let KeyCode::Char(_) = key.code {
return if is_auth_context { // If in suggestion mode, exit it before inserting char
if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
}
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
// --- End Autocomplete Trigger ---
return if app_state.ui.show_login {
auth_e::execute_edit_action( auth_e::execute_edit_action(
"insert_char", "insert_char",
key, key,
auth_state, login_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_edit_action(
"insert_char",
key,
register_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
@@ -116,5 +172,35 @@ pub async fn handle_edit_event(
}; };
} }
// Handle Backspace/Delete for Autocomplete Trigger
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
// If in suggestion mode, exit it before deleting char
if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
}
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
// Execute the action first
let result = if app_state.ui.show_register {
auth_e::execute_edit_action(
action_str,
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else {
// Handle for login/form if needed, assuming auth_e covers RegisterState
Ok("Action not applicable here".to_string()) // Placeholder
}?;
return Ok(result);
}
Ok(command_message.clone()) Ok(command_message.clone())
} }

View File

@@ -3,10 +3,10 @@
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::canvas_state::CanvasState; use crate::state::pages::{canvas_state::CanvasState, auth::RegisterState};
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::LoginState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::functions::modes::read_only::{auth_ro, form_ro}; use crate::functions::modes::read_only::{auth_ro, form_ro};
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
@@ -15,7 +15,8 @@ pub async fn handle_read_only_event(
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState, login_state: &mut LoginState,
register_state: &mut RegisterState,
key_sequence_tracker: &mut KeySequenceTracker, key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
@@ -31,23 +32,31 @@ 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, current_pos) = if app_state.ui.show_login { let (current_input, current_pos) = if app_state.ui.show_login { // Check Login first
( (
auth_state.get_current_input(), login_state.get_current_input(),
auth_state.current_cursor_pos(), login_state.current_cursor_pos(),
)
} else if app_state.ui.show_register { // Then check Register
(
register_state.get_current_input(),
register_state.current_cursor_pos(),
) )
} else { } else {
( (
form_state.get_current_input(), form_state.get_current_input(),
form_state.current_cursor_pos(), form_state.current_cursor_pos(),
) ) // Default to Form
}; };
if !current_input.is_empty() && current_pos < current_input.len() { if !current_input.is_empty() && current_pos < current_input.len() {
if app_state.ui.show_login { if app_state.ui.show_login {
auth_state.set_current_cursor_pos(current_pos + 1); login_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = auth_state.current_cursor_pos(); *ideal_cursor_column = login_state.current_cursor_pos();
} else { } else if app_state.ui.show_register {
register_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = register_state.current_cursor_pos();
} else { // Default to Form
form_state.set_current_cursor_pos(current_pos + 1); form_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = form_state.current_cursor_pos(); *ideal_cursor_column = form_state.current_cursor_pos();
} }
@@ -65,6 +74,10 @@ pub async fn handle_read_only_event(
"previous_entry", "previous_entry",
"next_entry", "next_entry",
]; ];
// Add context actions specific to register if needed, otherwise reuse login/form ones
const CONTEXT_ACTIONS_REGISTER: &[&str] = &[
// Add actions like "next_field", "prev_field" if handled differently than general read-only
];
if key.modifiers.is_empty() { if key.modifiers.is_empty() {
key_sequence_tracker.add_key(key.code); key_sequence_tracker.add_key(key.code);
@@ -81,18 +94,22 @@ pub async fn handle_read_only_event(
ideal_cursor_column, ideal_cursor_column,
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { } else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action( crate::tui::functions::login::handle_action(action).await?
} else if app_state.ui.show_register{
auth_ro::execute_action(
action, action,
auth_state, app_state,
register_state,
ideal_cursor_column, ideal_cursor_column,
) key_sequence_tracker,
.await? command_message,
).await?
} else if app_state.ui.show_login { } else if app_state.ui.show_login {
auth_ro::execute_action( auth_ro::execute_action(
action, action,
app_state, app_state,
auth_state, login_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,
@@ -128,18 +145,22 @@ pub async fn handle_read_only_event(
ideal_cursor_column, ideal_cursor_column,
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { } else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action( crate::tui::functions::login::handle_action(action).await?
action, } else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login {
auth_ro::execute_action( auth_ro::execute_action(
action, action,
app_state, app_state,
auth_state, register_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
).await?
} else if app_state.ui.show_login { // Handle login general actions
auth_ro::execute_action(
action,
app_state,
login_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,
@@ -174,18 +195,22 @@ pub async fn handle_read_only_event(
ideal_cursor_column, ideal_cursor_column,
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { } else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action( crate::tui::functions::login::handle_action(action).await?
action, } else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login {
auth_ro::execute_action( auth_ro::execute_action(
action, action,
app_state, app_state,
auth_state, register_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
).await?
} else if app_state.ui.show_login { // Handle login general actions
auth_ro::execute_action(
action,
app_state,
login_state,
ideal_cursor_column, ideal_cursor_column,
key_sequence_tracker, key_sequence_tracker,
command_message, command_message,

View File

@@ -4,7 +4,7 @@ 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::state::{state::AppState, pages::auth::AuthState}; use crate::state::{app::state::AppState, pages::auth::LoginState, pages::auth::RegisterState};
use crate::modes::common::commands::CommandHandler; use crate::modes::common::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
use crate::tui::functions::common::form::{save, revert}; use crate::tui::functions::common::form::{save, revert};
@@ -16,7 +16,8 @@ pub async fn handle_command_event(
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
app_state: &AppState, app_state: &AppState,
auth_state: &AuthState, login_state: &LoginState,
register_state: &RegisterState,
form_state: &mut FormState, form_state: &mut FormState,
command_input: &mut String, command_input: &mut String,
command_message: &mut String, command_message: &mut String,
@@ -39,7 +40,8 @@ pub async fn handle_command_event(
config, config,
form_state, form_state,
app_state, app_state,
auth_state, login_state,
register_state,
command_input, command_input,
command_message, command_message,
grpc_client, grpc_client,
@@ -73,7 +75,8 @@ async fn process_command(
config: &Config, config: &Config,
form_state: &mut FormState, form_state: &mut FormState,
app_state: &AppState, app_state: &AppState,
auth_state: &AuthState, login_state: &LoginState,
register_state: &RegisterState,
command_input: &mut String, command_input: &mut String,
command_message: &mut String, command_message: &mut String,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
@@ -101,7 +104,8 @@ async fn process_command(
terminal, terminal,
app_state, app_state,
form_state, form_state,
auth_state, login_state,
register_state,
) )
.await?; .await?;
command_input.clear(); command_input.clear();

View File

@@ -1,8 +1,8 @@
// src/modes/common/commands.rs // src/modes/common/commands.rs
use crate::tui::terminal::core::TerminalCore; use crate::tui::terminal::core::TerminalCore;
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::state::pages::{form::FormState, auth::AuthState}; use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
pub struct CommandHandler; pub struct CommandHandler;
@@ -17,10 +17,11 @@ impl CommandHandler {
terminal: &mut TerminalCore, terminal: &mut TerminalCore,
app_state: &AppState, app_state: &AppState,
form_state: &FormState, form_state: &FormState,
auth_state: &AuthState, login_state: &LoginState,
register_state: &RegisterState,
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action { match action {
"quit" => self.handle_quit(terminal, app_state, form_state, auth_state).await, "quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
"force_quit" => self.handle_force_quit(terminal).await, "force_quit" => self.handle_force_quit(terminal).await,
"save_and_quit" => self.handle_save_quit(terminal).await, "save_and_quit" => self.handle_save_quit(terminal).await,
_ => Ok((false, format!("Unknown command: {}", action))), _ => Ok((false, format!("Unknown command: {}", action))),
@@ -32,11 +33,14 @@ impl CommandHandler {
terminal: &mut TerminalCore, terminal: &mut TerminalCore,
app_state: &AppState, app_state: &AppState,
form_state: &FormState, form_state: &FormState,
auth_state: &AuthState, login_state: &LoginState,
register_state: &RegisterState,
) -> Result<(bool, String), Box<dyn std::error::Error>> { ) -> Result<(bool, String), Box<dyn std::error::Error>> {
// Use actual unsaved changes state instead of is_saved flag // Use actual unsaved changes state instead of is_saved flag
let has_unsaved = if app_state.ui.show_login { let has_unsaved = if app_state.ui.show_login {
auth_state.has_unsaved_changes() login_state.has_unsaved_changes()
} else if app_state.ui.show_register {
register_state.has_unsaved_changes()
} else { } else {
form_state.has_unsaved_changes form_state.has_unsaved_changes
}; };

View File

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

View File

@@ -0,0 +1,127 @@
// src/modes/general/dialog.rs
use crossterm::event::{Event, KeyCode};
use crate::config::binds::config::Config;
use crate::ui::handlers::context::DialogPurpose;
use crate::state::app::state::AppState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::{login, register};
/// Handles key events specifically when a dialog is active.
/// Returns Some(Result<EventOutcome, Error>) if the event was handled (consumed),
/// otherwise returns None.
pub async fn handle_dialog_event(
event: &Event,
config: &Config,
app_state: &mut AppState,
auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> {
if let Event::Key(key) = event {
// Always allow Esc to dismiss
if key.code == KeyCode::Esc {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Dialog dismissed".to_string())));
}
// Check general bindings for dialog actions
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
match action {
"move_down" | "next_option" => {
let current_index = app_state.ui.dialog.dialog_active_button_index;
let num_buttons = app_state.ui.dialog.dialog_buttons.len();
if num_buttons > 0 && current_index < num_buttons - 1 {
app_state.ui.dialog.dialog_active_button_index += 1;
}
return Some(Ok(EventOutcome::Ok(String::new())));
}
"move_up" | "previous_option" => {
let current_index = app_state.ui.dialog.dialog_active_button_index;
if current_index > 0 {
app_state.ui.dialog.dialog_active_button_index -= 1;
}
return Some(Ok(EventOutcome::Ok(String::new())));
}
"select" => {
let selected_index = app_state.ui.dialog.dialog_active_button_index;
let purpose = match app_state.ui.dialog.purpose {
Some(p) => p,
None => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Internal Error: Dialog context lost".to_string())));
}
};
// Handle Dialog Actions Directly Here
match purpose {
DialogPurpose::LoginSuccess => {
match selected_index {
0 => { // "Menu" button selected
app_state.hide_dialog();
let message = login::back_to_main(login_state, app_state).await;
return Some(Ok(EventOutcome::Ok(message)));
}
1 => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Exiting dialog".to_string())));
}
_ => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::LoginFailed => {
match selected_index {
0 => { // "OK" button selected
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Login failed dialog dismissed".to_string())));
}
_ => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::RegisterSuccess => { // Add this arm
match selected_index {
0 => { // "OK" button for RegisterSuccess
app_state.hide_dialog();
// Go back to intro after successful registration dialog
let message = register::back_to_main(register_state, app_state).await;
return Some(Ok(EventOutcome::Ok(message)));
}
_ => { // Default for RegisterSuccess
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::RegisterFailed => { // Add this arm
match selected_index {
0 => { // "OK" button for RegisterFailed
app_state.hide_dialog(); // Just dismiss
return Some(Ok(EventOutcome::Ok("Register failed dialog dismissed".to_string())));
}
_ => { // Default for RegisterFailed
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
}
}
_ => {} // Ignore other general actions when dialog is shown
}
}
// If it was a key event but not handled above, consume it
Some(Ok(EventOutcome::Ok(String::new())))
} else {
// If it wasn't a key event, consume it too while dialog is active
Some(Ok(EventOutcome::Ok(String::new())))
}
}

View File

@@ -2,10 +2,12 @@
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::LoginState;
use crate::state::canvas_state::CanvasState; use crate::state::pages::auth::RegisterState;
use crate::state::pages::admin::AdminState;
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::context::UiContext; use crate::ui::handlers::context::UiContext;
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
@@ -14,7 +16,9 @@ pub async fn handle_navigation_event(
config: &Config, config: &Config,
form_state: &mut FormState, form_state: &mut FormState,
app_state: &mut AppState, app_state: &mut AppState,
auth_state: &mut AuthState, login_state: &mut LoginState,
register_state: &mut RegisterState,
admin_state: &mut AdminState,
command_mode: &mut bool, command_mode: &mut bool,
command_input: &mut String, command_input: &mut String,
command_message: &mut String, command_message: &mut String,
@@ -22,11 +26,11 @@ pub async fn handle_navigation_event(
if let Some(action) = config.get_general_action(key.code, key.modifiers) { if let Some(action) = config.get_general_action(key.code, key.modifiers) {
match action { match action {
"move_up" => { "move_up" => {
move_up(app_state, auth_state); move_up(app_state, login_state, register_state, admin_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
"move_down" => { "move_down" => {
move_down(app_state); move_down(app_state, admin_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
"next_option" => { "next_option" => {
@@ -59,13 +63,14 @@ pub async fn handle_navigation_event(
let (context, index) = if app_state.ui.show_intro { let (context, index) = if app_state.ui.show_intro {
(UiContext::Intro, app_state.ui.intro_state.selected_option) (UiContext::Intro, app_state.ui.intro_state.selected_option)
} else if app_state.ui.show_login && app_state.ui.focus_outside_canvas { } else if app_state.ui.show_login && app_state.ui.focus_outside_canvas {
(UiContext::Login, app_state.general.selected_item) (UiContext::Login, app_state.focused_button_index)
} else if app_state.ui.show_register && app_state.ui.focus_outside_canvas {
(UiContext::Register, app_state.focused_button_index)
} else if app_state.ui.show_admin { } else if app_state.ui.show_admin {
(UiContext::Admin, app_state.general.selected_item) (UiContext::Admin, admin_state.get_selected_index().unwrap_or(0))
} else if app_state.ui.dialog.dialog_show { } else if app_state.ui.dialog.dialog_show {
(UiContext::Dialog, app_state.ui.dialog.dialog_active_button_index) (UiContext::Dialog, app_state.ui.dialog.dialog_active_button_index)
} else { } else {
// Handle cases where select is pressed but no button context applies
return Ok(EventOutcome::Ok("Select (No Action)".to_string())); return Ok(EventOutcome::Ok("Select (No Action)".to_string()));
}; };
return Ok(EventOutcome::ButtonSelected { context, index }); return Ok(EventOutcome::ButtonSelected { context, index });
@@ -76,49 +81,37 @@ pub async fn handle_navigation_event(
Ok(EventOutcome::Ok(String::new())) Ok(EventOutcome::Ok(String::new()))
} }
pub fn move_up(app_state: &mut AppState, auth_state: &mut AuthState) { pub fn move_up(app_state: &mut AppState, login_state: &mut LoginState, register_state: &mut RegisterState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login { if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register{
if app_state.general.selected_item == 0 { if app_state.focused_button_index == 0 {
app_state.ui.focus_outside_canvas = false; app_state.ui.focus_outside_canvas = false;
let last_field_index = auth_state.fields().len().saturating_sub(1); if app_state.ui.show_login {
auth_state.set_current_field(last_field_index); let last_field_index = login_state.fields().len().saturating_sub(1);
login_state.set_current_field(last_field_index);
} else {
let last_field_index = register_state.fields().len().saturating_sub(1);
register_state.set_current_field(last_field_index);
}
} else { } else {
app_state.general.selected_item = app_state.general.selected_item.saturating_sub(1); app_state.focused_button_index = app_state.focused_button_index.saturating_sub(1);
} }
} else if app_state.ui.show_intro { } else if app_state.ui.show_intro {
app_state.ui.intro_state.previous_option(); app_state.ui.intro_state.previous_option();
} else if app_state.ui.show_admin { } else if app_state.ui.show_admin {
// Assuming profile_tree.profiles is the list we're navigating admin_state.previous();
let profile_count = app_state.profile_tree.profiles.len();
if profile_count == 0 {
return;
}
// Use general state for tracking selection in admin panel
if app_state.general.selected_item == 0 {
app_state.general.selected_item = profile_count - 1;
} else {
app_state.general.selected_item = app_state.general.selected_item.saturating_sub(1);
}
} }
} }
pub fn move_down(app_state: &mut AppState) { pub fn move_down(app_state: &mut AppState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login { if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register {
let num_general_elements = 2; let num_general_elements = 2;
if app_state.general.selected_item < num_general_elements - 1 { if app_state.focused_button_index < num_general_elements - 1 {
app_state.general.selected_item += 1; app_state.focused_button_index += 1;
} }
} else if app_state.ui.show_intro { } else if app_state.ui.show_intro {
app_state.ui.intro_state.next_option(); app_state.ui.intro_state.next_option();
} else if app_state.ui.show_admin { } else if app_state.ui.show_admin {
// Assuming profile_tree.profiles is the list we're navigating admin_state.next();
let profile_count = app_state.profile_tree.profiles.len();
if profile_count == 0 {
return;
}
app_state.general.selected_item = (app_state.general.selected_item + 1) % profile_count;
} }
} }
@@ -128,7 +121,7 @@ pub fn next_option(app_state: &mut AppState) { // Remove option_count parameter
} else { } else {
// Get option count from state instead of parameter // Get option count from state instead of parameter
let option_count = app_state.profile_tree.profiles.len(); let option_count = app_state.profile_tree.profiles.len();
app_state.general.current_option = (app_state.general.current_option + 1) % option_count; app_state.focused_button_index = (app_state.focused_button_index + 1) % option_count;
} }
} }
@@ -137,10 +130,10 @@ pub fn previous_option(app_state: &mut AppState) {
app_state.ui.intro_state.previous_option(); app_state.ui.intro_state.previous_option();
} else { } else {
let option_count = app_state.profile_tree.profiles.len(); let option_count = app_state.profile_tree.profiles.len();
app_state.general.current_option = if app_state.general.current_option == 0 { app_state.focused_button_index = if app_state.focused_button_index == 0 {
option_count.saturating_sub(1) // Wrap to last option option_count.saturating_sub(1)
} else { } else {
app_state.general.current_option - 1 app_state.focused_button_index - 1
}; };
} }
} }

View File

@@ -8,15 +8,19 @@ 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::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::admin::AdminState;
use crate::state::app::state::AppState;
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::rat_state::UiStateHandler; use crate::ui::handlers::rat_state::UiStateHandler;
use crate::ui::handlers::context::UiContext; use crate::ui::handlers::context::UiContext;
use crate::tui::functions::{intro, admin}; use crate::tui::functions::{intro, admin};
use crate::tui::functions::common::login; use crate::tui::functions::common::{login, register};
use crate::modes::{ use crate::modes::{
common::command_mode, common::command_mode,
canvas::{edit, read_only, common_mode}, canvas::{edit, read_only, common_mode},
general::navigation, general::{navigation, dialog},
}; };
use crate::config::binds::key_sequences::KeySequenceTracker; use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::modes::handlers::mode_manager::{ModeManager, AppMode}; use crate::modes::handlers::mode_manager::{ModeManager, AppMode};
@@ -64,13 +68,27 @@ impl EventHandler {
command_handler: &mut CommandHandler, command_handler: &mut CommandHandler,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState, auth_state: &mut AuthState,
app_state: &mut crate::state::state::AppState, login_state: &mut LoginState,
register_state: &mut RegisterState,
admin_state: &mut AdminState,
app_state: &mut AppState,
total_count: u64, total_count: u64,
current_position: &mut u64, current_position: &mut u64,
) -> Result<EventOutcome, Box<dyn std::error::Error>> { ) -> Result<EventOutcome, Box<dyn std::error::Error>> {
let current_mode = ModeManager::derive_mode(app_state, self); let current_mode = ModeManager::derive_mode(app_state, self);
app_state.update_mode(current_mode); app_state.update_mode(current_mode);
// --- DIALOG MODALITY ---
if app_state.ui.dialog.dialog_show {
if let Some(dialog_result) = dialog::handle_dialog_event(
&event, config, app_state, auth_state, login_state, register_state
).await {
return dialog_result;
}
return Ok(EventOutcome::Ok(String::new()));
}
// --- END DIALOG MODALITY CHECK ---
if let Event::Key(key) = event { if let Event::Key(key) = event {
let key_code = key.code; let key_code = key.code;
let modifiers = key.modifiers; let modifiers = key.modifiers;
@@ -89,7 +107,9 @@ impl EventHandler {
config, config,
form_state, form_state,
app_state, app_state,
auth_state, login_state,
register_state,
admin_state,
&mut self.command_mode, &mut self.command_mode,
&mut self.command_input, &mut self.command_input,
&mut self.command_message, &mut self.command_message,
@@ -99,31 +119,36 @@ impl EventHandler {
let mut message = String::from("Selected"); // Default message let mut message = String::from("Selected"); // Default message
match context { match context {
UiContext::Intro => { UiContext::Intro => {
intro::handle_intro_selection(app_state, index); // Pass index intro::handle_intro_selection(app_state, index);
if app_state.ui.show_admin {
let profile_names = app_state.profile_tree.profiles.iter()
.map(|p| p.name.clone())
.collect();
admin_state.set_profiles(profile_names);
}
message = format!("Intro Option {} selected", index); message = format!("Intro Option {} selected", index);
} }
UiContext::Login => { UiContext::Login => {
message = match index { message = match index {
0 => login::save(auth_state, &mut self.auth_client, app_state).await?, 0 => login::save(auth_state, login_state, &mut self.auth_client, app_state).await?,
1 => { 1 => login::back_to_main(login_state, app_state).await,
let msg = login::revert(auth_state, app_state).await; _ => "Invalid Login Option".to_string(),
// Optional: Add navigation logic here if revert should change screen };
// app_state.ui.show_login = false; }
// app_state.ui.show_intro = true; UiContext::Register => {
msg message = match index {
} 0 => register::save(register_state, &mut self.auth_client, app_state).await?,
1 => register::back_to_main(register_state, app_state).await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}; };
} }
UiContext::Admin => { UiContext::Admin => {
// Assuming handle_admin_selection uses app_state.general.selected_item admin::handle_admin_selection(app_state, admin_state);
admin::handle_admin_selection(app_state);
message = format!("Admin Option {} selected", index); message = format!("Admin Option {} selected", index);
} }
UiContext::Dialog => { UiContext::Dialog => {
// Add specific dialog handling logic here message = "Internal error: Unexpected dialog state".to_string();
message = format!("Dialog Button {} selected", index);
app_state.hide_dialog(); // Example action
} }
} }
return Ok(EventOutcome::Ok(message)); // Return Ok with message return Ok(EventOutcome::Ok(message)); // Return Ok with message
@@ -144,21 +169,21 @@ 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 = if app_state.ui.show_login { let current_input = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.get_current_input() login_state.get_current_input()
} else { } else {
form_state.get_current_input() form_state.get_current_input()
}; };
let current_cursor_pos = if app_state.ui.show_login { let current_cursor_pos = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.current_cursor_pos() login_state.current_cursor_pos()
} else { } else {
form_state.current_cursor_pos() form_state.current_cursor_pos()
}; };
if !current_input.is_empty() && current_cursor_pos < current_input.len() { if !current_input.is_empty() && current_cursor_pos < current_input.len() {
if app_state.ui.show_login { if app_state.ui.show_login || app_state.ui.show_register{
auth_state.set_current_cursor_pos(current_cursor_pos + 1); login_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = auth_state.current_cursor_pos(); self.ideal_cursor_column = login_state.current_cursor_pos();
} else { } else {
form_state.set_current_cursor_pos(current_cursor_pos + 1); form_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = form_state.current_cursor_pos(); self.ideal_cursor_column = form_state.current_cursor_pos();
@@ -191,6 +216,8 @@ impl EventHandler {
action, action,
form_state, form_state,
auth_state, auth_state,
login_state,
register_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
terminal, terminal,
@@ -208,7 +235,8 @@ impl EventHandler {
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state,
&mut self.key_sequence_tracker, &mut self.key_sequence_tracker,
current_position, current_position,
total_count, total_count,
@@ -225,8 +253,8 @@ impl EventHandler {
self.is_edit_mode = false; self.is_edit_mode = false;
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
let has_changes = if app_state.ui.show_login { let has_changes = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.has_unsaved_changes() login_state.has_unsaved_changes()
} else { } else {
form_state.has_unsaved_changes() form_state.has_unsaved_changes()
}; };
@@ -239,22 +267,22 @@ impl EventHandler {
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = if app_state.ui.show_login { let current_input = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.get_current_input() login_state.get_current_input()
} else { } else {
form_state.get_current_input() form_state.get_current_input()
}; };
let current_cursor_pos = if app_state.ui.show_login { let current_cursor_pos = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.current_cursor_pos() login_state.current_cursor_pos()
} else { } else {
form_state.current_cursor_pos() form_state.current_cursor_pos()
}; };
if !current_input.is_empty() && current_cursor_pos >= current_input.len() { if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
let new_pos = current_input.len() - 1; let new_pos = current_input.len() - 1;
if app_state.ui.show_login { if app_state.ui.show_login || app_state.ui.show_register{
auth_state.set_current_cursor_pos(new_pos); login_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = auth_state.current_cursor_pos(); self.ideal_cursor_column = login_state.current_cursor_pos();
} else { } else {
form_state.set_current_cursor_pos(new_pos); form_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = form_state.current_cursor_pos(); self.ideal_cursor_column = form_state.current_cursor_pos();
@@ -274,6 +302,8 @@ impl EventHandler {
action, action,
form_state, form_state,
auth_state, auth_state,
login_state,
register_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
terminal, terminal,
@@ -287,16 +317,17 @@ impl EventHandler {
} }
let message = edit::handle_edit_event( let message = edit::handle_edit_event(
app_state.ui.show_login,
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state,
&mut self.ideal_cursor_column, &mut self.ideal_cursor_column,
&mut self.command_message, &mut self.command_message,
current_position, current_position,
total_count, total_count,
grpc_client, grpc_client,
app_state,
).await?; ).await?;
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
@@ -308,7 +339,8 @@ impl EventHandler {
key, key,
config, config,
app_state, app_state,
auth_state, login_state,
register_state,
form_state, form_state,
&mut self.command_input, &mut self.command_input,
&mut self.command_message, &mut self.command_message,
@@ -318,7 +350,7 @@ impl EventHandler {
current_position, current_position,
total_count, total_count,
).await?; ).await?;
if let EventOutcome::Ok(msg) = &outcome { if let EventOutcome::Ok(msg) = &outcome {
if msg == "Exited command mode" { if msg == "Exited command mode" {
self.command_mode = false; self.command_mode = false;

View File

@@ -1,5 +1,5 @@
// src/modes/handlers/mode_manager.rs // src/modes/handlers/mode_manager.rs
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::modes::handlers::event::EventHandler; use crate::modes::handlers::event::EventHandler;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -23,7 +23,7 @@ impl ModeManager {
return AppMode::General; return AppMode::General;
} }
if app_state.ui.show_login { if app_state.ui.show_login || app_state.ui.show_register {
if event_handler.is_edit_mode { if event_handler.is_edit_mode {
AppMode::Edit AppMode::Edit
} else { } else {

View File

@@ -2,7 +2,8 @@
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,
LoginRequest, LoginResponse LoginRequest, LoginResponse,
RegisterRequest, AuthResponse,
}; };
pub struct AuthClient { pub struct AuthClient {
@@ -15,9 +16,30 @@ impl AuthClient {
Ok(Self { client }) Ok(Self { client })
} }
/// Login user via gRPC.
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> { pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(LoginRequest { identifier, password }); let request = tonic::Request::new(LoginRequest { identifier, password });
let response = self.client.login(request).await?.into_inner(); let response = self.client.login(request).await?.into_inner();
Ok(response) Ok(response)
} }
/// Registers a new user via gRPC.
pub async fn register(
&mut self,
username: String,
email: String,
password: Option<String>,
password_confirmation: Option<String>,
role: Option<String>,
) -> Result<AuthResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(RegisterRequest {
username,
email,
password: password.unwrap_or_default(),
password_confirmation: password_confirmation.unwrap_or_default(),
role: role.unwrap_or_default(),
});
let response = self.client.register(request).await?.into_inner();
Ok(response)
}
} }

View File

@@ -3,7 +3,7 @@
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::functions::common::form::SaveOutcome; use crate::tui::functions::common::form::SaveOutcome;
use crate::state::state::AppState; use crate::state::app::state::AppState;
pub struct UiService; pub struct UiService;

3
client/src/state/app.rs Normal file
View File

@@ -0,0 +1,3 @@
// src/state/app.rs
pub mod state;

View File

@@ -4,6 +4,7 @@ use std::env;
use common::proto::multieko2::table_definition::ProfileTreeResponse; 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;
use crate::ui::handlers::context::DialogPurpose;
pub struct DialogState { pub struct DialogState {
pub dialog_show: bool, pub dialog_show: bool,
@@ -11,6 +12,7 @@ pub struct DialogState {
pub dialog_message: String, pub dialog_message: String,
pub dialog_buttons: Vec<String>, pub dialog_buttons: Vec<String>,
pub dialog_active_button_index: usize, pub dialog_active_button_index: usize,
pub purpose: Option<DialogPurpose>,
} }
pub struct UiState { pub struct UiState {
@@ -19,14 +21,10 @@ pub struct UiState {
pub show_admin: bool, pub show_admin: bool,
pub show_form: bool, pub show_form: bool,
pub show_login: bool, pub show_login: bool,
pub show_register: bool,
pub intro_state: IntroState, pub intro_state: IntroState,
pub focus_outside_canvas: bool, pub focus_outside_canvas: bool,
pub dialog: DialogState, // Add dialog state here pub dialog: DialogState,
}
pub struct GeneralState {
pub selected_item: usize,
pub current_option: usize,
} }
pub struct AppState { pub struct AppState {
@@ -37,10 +35,10 @@ pub struct AppState {
pub profile_tree: ProfileTreeResponse, pub profile_tree: ProfileTreeResponse,
pub selected_profile: Option<String>, pub selected_profile: Option<String>,
pub current_mode: AppMode, pub current_mode: AppMode,
pub focused_button_index: usize,
// UI preferences // UI preferences
pub ui: UiState, pub ui: UiState,
pub general: GeneralState,
} }
impl AppState { impl AppState {
@@ -55,11 +53,8 @@ impl AppState {
profile_tree: ProfileTreeResponse::default(), profile_tree: ProfileTreeResponse::default(),
selected_profile: None, selected_profile: None,
current_mode: AppMode::General, current_mode: AppMode::General,
focused_button_index: 0,
ui: UiState::default(), ui: UiState::default(),
general: GeneralState {
selected_item: 0,
current_option: 0,
},
}) })
} }
@@ -84,21 +79,26 @@ impl AppState {
title: &str, title: &str,
message: &str, message: &str,
buttons: Vec<String>, buttons: Vec<String>,
purpose: DialogPurpose,
) { ) {
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_buttons = buttons; self.ui.dialog.dialog_buttons = buttons;
self.ui.dialog.dialog_active_button_index = 0; // Default to first button self.ui.dialog.dialog_active_button_index = 0;
self.ui.dialog.dialog_show = true; // Use new name self.ui.dialog.purpose = Some(purpose);
self.ui.dialog.dialog_show = true;
self.ui.focus_outside_canvas = true;
} }
/// Hides the dialog and clears its content. /// Hides the dialog and clears its content.
pub fn hide_dialog(&mut self) { pub fn hide_dialog(&mut self) {
self.ui.dialog.dialog_show = false; // Use new name self.ui.dialog.dialog_show = false;
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_buttons.clear();
self.ui.dialog.dialog_active_button_index = 0; self.ui.dialog.dialog_active_button_index = 0;
self.ui.dialog.purpose = None;
self.ui.focus_outside_canvas = false;
} }
/// Sets the active button index, wrapping around if necessary. /// Sets the active button index, wrapping around if necessary.
@@ -137,6 +137,7 @@ impl Default for UiState {
show_admin: false, show_admin: false,
show_form: false, show_form: false,
show_login: false, show_login: false,
show_register: false,
intro_state: IntroState::new(), intro_state: IntroState::new(),
focus_outside_canvas: false, focus_outside_canvas: false,
dialog: DialogState::default(), dialog: DialogState::default(),
@@ -148,11 +149,12 @@ impl Default for UiState {
impl Default for DialogState { impl Default for DialogState {
fn default() -> Self { fn default() -> Self {
Self { Self {
dialog_show: false, // Use new name dialog_show: false,
dialog_title: String::new(), // Use new name dialog_title: String::new(),
dialog_message: String::new(), // Use new name dialog_message: String::new(),
dialog_buttons: Vec::new(), // Use new name dialog_buttons: Vec::new(),
dialog_active_button_index: 0, // Use new name dialog_active_button_index: 0,
purpose: None,
} }
} }
} }

View File

@@ -1,4 +1,3 @@
// src/state/mod.rs // src/state/mod.rs
pub mod state; pub mod app;
pub mod pages; pub mod pages;
pub mod canvas_state;

View File

@@ -2,3 +2,5 @@
pub mod form; pub mod form;
pub mod auth; pub mod auth;
pub mod admin;
pub mod canvas_state;

View File

@@ -0,0 +1,65 @@
// src/state/pages/admin.rs
use ratatui::widgets::ListState;
#[derive(Default, Clone, Debug)]
pub struct AdminState {
pub profiles: Vec<String>,
pub list_state: ListState,
}
impl AdminState {
/// Gets the index of the currently selected item.
pub fn get_selected_index(&self) -> Option<usize> {
self.list_state.selected()
}
/// Gets the name of the currently selected profile.
pub fn get_selected_profile_name(&self) -> Option<&String> {
self.list_state.selected().and_then(|i| self.profiles.get(i))
}
/// Populates the profile list and updates/resets the selection.
pub fn set_profiles(&mut self, new_profiles: Vec<String>) {
let current_selection_index = self.list_state.selected();
self.profiles = new_profiles;
if self.profiles.is_empty() {
self.list_state.select(None);
} else {
let new_selection = match current_selection_index {
Some(index) => Some(index.min(self.profiles.len() - 1)),
None => Some(0),
};
self.list_state.select(new_selection);
}
}
/// Selects the next profile in the list, wrapping around.
pub fn next(&mut self) {
if self.profiles.is_empty() {
self.list_state.select(None);
return;
}
let i = match self.list_state.selected() {
Some(i) => if i >= self.profiles.len() - 1 { 0 } else { i + 1 },
None => 0,
};
self.list_state.select(Some(i));
}
/// Selects the previous profile in the list, wrapping around.
pub fn previous(&mut self) {
if self.profiles.is_empty() {
self.list_state.select(None);
return;
}
let i = match self.list_state.selected() {
Some(i) => if i == 0 { self.profiles.len() - 1 } else { i - 1 },
None => self.profiles.len() - 1,
};
self.list_state.select(Some(i));
}
}

View File

@@ -1,38 +1,113 @@
// src/state/pages/auth.rs // src/state/pages/auth.rs
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use lazy_static::lazy_static;
lazy_static! {
pub static ref AVAILABLE_ROLES: Vec<String> = vec![
"admin".to_string(),
"moderator".to_string(),
"accountant".to_string(),
"viewer".to_string(),
];
}
/// Represents the authenticated session state
#[derive(Default)] #[derive(Default)]
pub struct AuthState { pub struct AuthState {
pub return_selected: bool, pub auth_token: Option<String>,
pub user_id: Option<String>,
pub role: Option<String>,
pub decoded_username: Option<String>,
}
/// Represents the state of the Login form UI
#[derive(Default)]
pub struct LoginState {
pub username: String, pub username: String,
pub password: String, pub password: String,
pub error_message: Option<String>, pub error_message: Option<String>,
pub current_field: usize, pub current_field: usize,
pub current_cursor_pos: usize, pub current_cursor_pos: usize,
pub auth_token: Option<String>,
pub user_id: Option<String>,
pub role: Option<String>,
pub has_unsaved_changes: bool, pub has_unsaved_changes: bool,
} }
/// Represents the state of the Registration form UI
#[derive(Default, Clone)]
pub struct RegisterState {
pub username: String,
pub email: String,
pub password: String,
pub password_confirmation: String,
pub role: String,
pub error_message: Option<String>,
pub current_field: usize,
pub current_cursor_pos: usize,
pub has_unsaved_changes: bool,
pub show_role_suggestions: bool,
pub role_suggestions: Vec<String>,
pub selected_suggestion_index: Option<usize>,
pub in_suggestion_mode: bool,
}
impl AuthState { impl AuthState {
/// Creates a new empty AuthState (unauthenticated)
pub fn new() -> Self {
Self {
auth_token: None,
user_id: None,
role: None,
decoded_username: None,
}
}
}
impl LoginState {
/// Creates a new empty LoginState
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
return_selected: false,
username: String::new(), username: String::new(),
password: String::new(), password: String::new(),
error_message: None, error_message: None,
current_field: 0, current_field: 0,
current_cursor_pos: 0, current_cursor_pos: 0,
auth_token: None,
user_id: None,
role: None,
has_unsaved_changes: false, has_unsaved_changes: false,
} }
} }
} }
impl CanvasState for AuthState { impl RegisterState {
/// Creates a new empty RegisterState
pub fn new() -> Self {
Self {
username: String::new(),
email: String::new(),
password: String::new(),
password_confirmation: String::new(),
role: String::new(),
error_message: None,
current_field: 0,
current_cursor_pos: 0,
has_unsaved_changes: false,
show_role_suggestions: false,
role_suggestions: Vec::new(),
selected_suggestion_index: None,
in_suggestion_mode: false,
}
}
/// Updates role suggestions based on current input
pub fn update_role_suggestions(&mut self) {
let current_input = self.role.to_lowercase();
self.role_suggestions = AVAILABLE_ROLES
.iter()
.filter(|role| role.to_lowercase().contains(&current_input))
.cloned()
.collect();
self.show_role_suggestions = !self.role_suggestions.is_empty();
}
}
impl CanvasState for LoginState {
fn current_field(&self) -> usize { fn current_field(&self) -> usize {
self.current_field self.current_field
} }
@@ -66,7 +141,7 @@ impl CanvasState for AuthState {
match self.current_field { match self.current_field {
0 => &mut self.username, 0 => &mut self.username,
1 => &mut self.password, 1 => &mut self.password,
_ => panic!("Invalid current_field index in AuthState"), _ => panic!("Invalid current_field index in LoginState"),
} }
} }
@@ -75,13 +150,12 @@ impl CanvasState for AuthState {
} }
fn set_current_field(&mut self, index: usize) { fn set_current_field(&mut self, index: usize) {
if index < 2 { // AuthState only has 2 fields if index < 2 {
self.current_field = index; self.current_field = index;
// IMPORTANT: Clamp cursor position to the length of the NEW field
let len = match self.current_field { let len = match self.current_field {
0 => self.username.len(), 0 => self.username.len(),
1 => self.password.len(), 1 => self.password.len(),
_ => 0, _ => 0,
}; };
self.current_cursor_pos = self.current_cursor_pos.min(len); self.current_cursor_pos = self.current_cursor_pos.min(len);
} }
@@ -89,16 +163,133 @@ impl CanvasState for AuthState {
fn set_current_cursor_pos(&mut self, pos: usize) { fn set_current_cursor_pos(&mut self, pos: usize) {
let len = match self.current_field { let len = match self.current_field {
0 => self.username.len(), 0 => self.username.len(),
1 => self.password.len(), 1 => self.password.len(),
_ => 0, _ => 0,
}; };
// Ensure stored position is always valid
self.current_cursor_pos = pos.min(len); self.current_cursor_pos = pos.min(len);
} }
fn set_has_unsaved_changes(&mut self, changed: bool) { fn set_has_unsaved_changes(&mut self, changed: bool) {
// Allow the generic handler to signal changes
self.has_unsaved_changes = changed; self.has_unsaved_changes = changed;
} }
fn get_suggestions(&self) -> Option<&[String]> {
None
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
None
}
}
impl CanvasState for RegisterState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
let len = match self.current_field {
0 => self.username.len(),
1 => self.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.len(),
_ => 0,
};
self.current_cursor_pos.min(len)
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
vec![
&self.username,
&self.email,
&self.password,
&self.password_confirmation,
&self.role,
]
}
fn get_current_input(&self) -> &str {
match self.current_field {
0 => &self.username,
1 => &self.email,
2 => &self.password,
3 => &self.password_confirmation,
4 => &self.role,
_ => "",
}
}
fn get_current_input_mut(&mut self) -> &mut String {
match self.current_field {
0 => &mut self.username,
1 => &mut self.email,
2 => &mut self.password,
3 => &mut self.password_confirmation,
4 => &mut self.role,
_ => panic!("Invalid current_field index in RegisterState"),
}
}
fn fields(&self) -> Vec<&str> {
vec![
"Username",
"Email (Optional)",
"Password (Optional)",
"Confirm Password",
"Role (Optional)"
]
}
fn set_current_field(&mut self, index: usize) {
if index < 5 {
self.current_field = index;
let len = match self.current_field {
0 => self.username.len(),
1 => self.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.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.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.len(),
_ => 0,
};
self.current_cursor_pos = pos.min(len);
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
fn get_suggestions(&self) -> Option<&[String]> {
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
Some(&self.role_suggestions)
} else {
None
}
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
self.selected_suggestion_index
} else {
None
}
}
} }

View File

@@ -13,4 +13,8 @@ pub trait CanvasState {
fn set_current_field(&mut self, index: usize); fn set_current_field(&mut self, index: usize);
fn set_current_cursor_pos(&mut self, pos: usize); fn set_current_cursor_pos(&mut self, pos: usize);
fn set_has_unsaved_changes(&mut self, changed: bool); fn set_has_unsaved_changes(&mut self, changed: bool);
// --- Autocomplete Support ---
fn get_suggestions(&self) -> Option<&[String]>;
fn get_selected_suggestion_index(&self) -> Option<usize>;
} }

View File

@@ -2,7 +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; use crate::state::pages::canvas_state::CanvasState;
pub struct FormState { pub struct FormState {
pub id: i64, pub id: i64,
@@ -133,4 +133,13 @@ impl CanvasState for FormState {
fn set_has_unsaved_changes(&mut self, changed: bool) { fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed; self.has_unsaved_changes = changed;
} }
// --- Autocomplete Support (Not Used for FormState) ---
fn get_suggestions(&self) -> Option<&[String]> {
None // FormState doesn't provide suggestions
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
None // FormState doesn't have selected suggestions
}
} }

View File

@@ -1,8 +1,11 @@
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
pub fn handle_admin_selection(app_state: &mut AppState) { pub fn handle_admin_selection(app_state: &mut AppState, admin_state: &AdminState) {
let profiles = &app_state.profile_tree.profiles; let profiles = &app_state.profile_tree.profiles;
if !profiles.is_empty() && app_state.general.selected_item < profiles.len() { if let Some(selected_index) = admin_state.get_selected_index() {
app_state.selected_profile = Some(profiles[app_state.general.selected_item].name.clone()); if let Some(profile) = profiles.get(selected_index) {
app_state.selected_profile = Some(profile.name.clone());
}
} }
} }

View File

@@ -2,4 +2,4 @@
pub mod form; pub mod form;
pub mod login; pub mod login;
pub mod register;

View File

@@ -1,23 +1,25 @@
// src/tui/functions/common/login.rs // src/tui/functions/common/login.rs
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::state::state::AppState; use crate::state::pages::auth::LoginState;
use crate::state::canvas_state::CanvasState; use crate::state::app::state::AppState;
// Remove unused import if CanvasState is not directly used here use crate::state::pages::canvas_state::CanvasState;
// use crate::state::canvas_state::CanvasState; use crate::ui::handlers::context::DialogPurpose;
/// Attempts to log the user in using the provided credentials via gRPC. /// Attempts to log the user in using the provided credentials via gRPC.
/// Updates AuthState and AppState on success or failure. /// Updates AuthState and AppState on success or failure.
pub async fn save( pub async fn save(
auth_state: &mut AuthState, auth_state: &mut AuthState,
login_state: &mut LoginState,
auth_client: &mut AuthClient, auth_client: &mut AuthClient,
app_state: &mut AppState, app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<String, Box<dyn std::error::Error>> {
let identifier = auth_state.username.clone(); let identifier = login_state.username.clone();
let password = auth_state.password.clone(); let password = login_state.password.clone();
// Clear previous error/dialog state before attempting // Clear previous error/dialog state before attempting
auth_state.error_message = None; login_state.error_message = None;
// Use the helper to ensure dialog is hidden and cleared properly // Use the helper to ensure dialog is hidden and cleared properly
app_state.hide_dialog(); app_state.hide_dialog();
@@ -28,29 +30,24 @@ pub async fn save(
auth_state.auth_token = Some(response.access_token.clone()); auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone()); auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone()); auth_state.role = Some(response.role.clone());
auth_state.set_has_unsaved_changes(false); auth_state.decoded_username = Some(response.username.clone());
login_state.set_has_unsaved_changes(false);
let success_message = format!( let success_message = format!(
"Login Successful!\n\n\ "Login Successful!\n\n\
Access Token: {}\n\ Username: {}\n\
Token Type: {}\n\
Expires In: {}\n\
User ID: {}\n\ User ID: {}\n\
Role: {}", Role: {}",
response.access_token, response.username,
response.token_type,
response.expires_in,
response.user_id, response.user_id,
response.role response.role
); );
// Use the helper method to configure and show the dialog
// TODO Implement logic for pressing menu or exit buttons, not imeplementing it now,
// need to do other more important stuff now"
app_state.show_dialog( app_state.show_dialog(
"Login Success", "Login Success",
&success_message, &success_message,
vec!["Menu".to_string(), "Exit".to_string()], vec!["Menu".to_string(), "Exit".to_string()],
DialogPurpose::LoginSuccess,
); );
Ok("Login successful, details shown in dialog.".to_string()) Ok("Login successful, details shown in dialog.".to_string())
@@ -62,15 +59,11 @@ pub async fn save(
app_state.show_dialog( app_state.show_dialog(
"Login Failed", "Login Failed",
&error_message, &error_message,
vec!["OK".to_string()], // Pass buttons here vec!["OK".to_string()],
DialogPurpose::LoginFailed,
); );
// 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); login_state.set_has_unsaved_changes(true);
Ok(format!("Login failed: {}", error_message)) Ok(format!("Login failed: {}", error_message))
} }
@@ -79,22 +72,38 @@ pub async fn save(
/// Reverts the login form fields to empty and returns to the previous screen (Intro). /// Reverts the login form fields to empty and returns to the previous screen (Intro).
pub async fn revert( pub async fn revert(
auth_state: &mut AuthState, login_state: &mut LoginState,
app_state: &mut AppState, app_state: &mut AppState,
) -> String { ) -> String {
// Clear the input fields // Clear the input fields
auth_state.username.clear(); login_state.username.clear();
auth_state.password.clear(); login_state.password.clear();
auth_state.error_message = None; login_state.error_message = None;
auth_state.set_has_unsaved_changes(false); login_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() "Login reverted".to_string()
} }
pub async fn back_to_main(
login_state: &mut LoginState,
app_state: &mut AppState,
) -> String {
// Clear the input fields
login_state.username.clear();
login_state.password.clear();
login_state.error_message = None;
login_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;
// Reset focus state
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index= 0;
"Returned to main menu".to_string()
}

View File

@@ -0,0 +1,154 @@
// src/tui/functions/common/register.rs
use crate::{
services::auth::AuthClient,
state::{
pages::auth::RegisterState,
app::state::AppState,
pages::canvas_state::CanvasState,
},
ui::handlers::context::DialogPurpose,
};
/// Attempts to register the user using the provided details via gRPC.
/// Updates RegisterState and AppState on success or failure.
pub async fn save(
register_state: &mut RegisterState,
auth_client: &mut AuthClient,
app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> {
let username = register_state.username.clone();
let email = register_state.email.clone();
// Handle optional passwords: send None if empty, Some(value) otherwise
let password = if register_state.password.is_empty() {
None
} else {
Some(register_state.password.clone())
};
let password_confirmation = if register_state.password_confirmation.is_empty() {
None
} else {
Some(register_state.password_confirmation.clone())
};
let role = if register_state.role.is_empty() {
None
} else {
Some(register_state.role.clone())
};
// Basic client-side validation (example)
if username.is_empty() {
app_state.show_dialog(
"Registration Failed",
"Username cannot be empty.",
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
register_state.error_message = Some("Username cannot be empty.".to_string());
return Ok("Registration failed: Username cannot be empty.".to_string());
}
if password.is_some() && password != password_confirmation {
app_state.show_dialog(
"Registration Failed",
"Passwords do not match.",
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
register_state.error_message = Some("Passwords do not match.".to_string());
return Ok("Registration failed: Passwords do not match.".to_string());
}
// Clear previous error/dialog state before attempting
register_state.error_message = None;
app_state.hide_dialog();
// Call the gRPC register method
match auth_client.register(username, email, password, password_confirmation, role).await {
Ok(response) => {
// Clear fields on success? Optional, maybe wait for dialog confirmation.
// register_state.username.clear();
// register_state.email.clear();
// register_state.password.clear();
// register_state.password_confirmation.clear();
register_state.set_has_unsaved_changes(false);
let success_message = format!(
"Registration Successful!\n\n\
User ID: {}\n\
Username: {}\n\
Email: {}\n\
Role: {}",
response.id,
response.username,
response.email,
response.role
);
// Show success dialog
app_state.show_dialog(
"Registration Success",
&success_message,
vec!["OK".to_string()], // Simple OK for now
DialogPurpose::RegisterSuccess,
);
Ok("Registration successful, details shown in dialog.".to_string())
}
Err(e) => {
let error_message = format!("{}", e);
register_state.error_message = Some(error_message.clone());
register_state.set_has_unsaved_changes(true); // Keep changes on error
// Show error dialog
app_state.show_dialog(
"Registration Failed",
&error_message,
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
Ok(format!("Registration failed: {}", error_message))
}
}
}
/// Clears the registration form fields.
pub async fn revert(
register_state: &mut RegisterState,
_app_state: &mut AppState, // Keep signature consistent if needed elsewhere
) -> String {
register_state.username.clear();
register_state.email.clear();
register_state.password.clear();
register_state.password_confirmation.clear();
register_state.role.clear();
register_state.error_message = None;
register_state.set_has_unsaved_changes(false);
register_state.current_field = 0; // Reset focus to first field
register_state.current_cursor_pos = 0;
"Registration form cleared".to_string()
}
/// Clears the form and returns to the intro screen.
pub async fn back_to_main(
register_state: &mut RegisterState,
app_state: &mut AppState,
) -> String {
// Clear fields first
let _ = revert(register_state, app_state).await;
// Ensure dialog is hidden
app_state.hide_dialog();
// Navigation logic
app_state.ui.show_register = false;
app_state.ui.show_intro = true;
// Reset focus state
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index = 0;
"Returned to main menu".to_string()
}

View File

@@ -1,7 +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; use crate::state::pages::canvas_state::CanvasState;
pub async fn handle_action( pub async fn handle_action(
action: &str, action: &str,

View File

@@ -1,4 +1,4 @@
use crate::state::state::AppState; use crate::state::app::state::AppState;
pub fn handle_intro_selection(app_state: &mut AppState, index: usize) { // Add index parameter pub fn handle_intro_selection(app_state: &mut AppState, index: usize) { // Add index parameter
match index { // Use index directly match index { // Use index directly
@@ -17,6 +17,12 @@ pub fn handle_intro_selection(app_state: &mut AppState, index: usize) { // Add i
app_state.ui.show_admin = false; app_state.ui.show_admin = false;
app_state.ui.show_login = true; app_state.ui.show_login = true;
} }
3 => { // Register
app_state.ui.show_intro = false;
app_state.ui.show_register = true;
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index = 0;
}
_ => {} _ => {}
} }
app_state.ui.show_intro = false; app_state.ui.show_intro = false;

View File

@@ -1,11 +1,6 @@
// src/tui/functions/login.rs // src/tui/functions/login.rs
use crate::state::pages::auth::AuthState;
pub async fn handle_action( pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::Error>> {
action: &str,
auth_state: &mut AuthState,
ideal_cursor_column: &mut usize,
) -> Result<String, Box<dyn std::error::Error>> {
match action { match action {
"previous_entry" => { "previous_entry" => {
Ok("Previous entry at tui/functions/login.rs not implemented".into()) Ok("Previous entry at tui/functions/login.rs not implemented".into())

View File

@@ -1,8 +1,21 @@
// src/ui/handlers/context.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UiContext { pub enum UiContext {
Intro, Intro,
Login, Login,
Register,
Admin, Admin,
Dialog, Dialog,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialogPurpose {
LoginSuccess,
LoginFailed,
RegisterSuccess,
RegisterFailed,
// TODO in the future:
// ConfirmQuit,
}

View File

@@ -1,7 +1,7 @@
// src/ui/handlers/rat_state.rs // src/ui/handlers/rat_state.rs
use crossterm::event::{KeyCode, KeyModifiers}; use crossterm::event::{KeyCode, KeyModifiers};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::state::state::UiState; use crate::state::app::state::UiState;
pub struct UiStateHandler; pub struct UiStateHandler;

View File

@@ -6,20 +6,25 @@ use crate::components::{
render_status_line, render_status_line,
handlers::sidebar::{self, calculate_sidebar_layout}, handlers::sidebar::{self, calculate_sidebar_layout},
form::form::render_form, form::form::render_form,
admin::{admin_panel::AdminPanelState}, auth::{login::render_login, register::render_register},
auth::login::render_login,
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::Frame; use ratatui::Frame;
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::state::AppState; use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
pub fn render_ui( pub fn render_ui(
f: &mut Frame, f: &mut Frame,
form_state: &mut FormState, form_state: &mut FormState,
auth_state: &mut AuthState, auth_state: &mut AuthState,
login_state: &LoginState,
register_state: &RegisterState,
admin_state: &mut AdminState,
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
total_count: u64, total_count: u64,
@@ -29,7 +34,6 @@ pub fn render_ui(
command_mode: bool, command_mode: bool,
command_message: &str, command_message: &str,
app_state: &AppState, app_state: &AppState,
// intro_state parameter removed
) { ) {
render_background(f, f.area(), theme); render_background(f, f.area(), theme);
@@ -44,37 +48,29 @@ pub fn render_ui(
let main_content_area = root[0]; let main_content_area = root[0];
if app_state.ui.show_intro { if app_state.ui.show_intro {
// Use app_state's intro_state directly
app_state.ui.intro_state.render(f, main_content_area, theme); app_state.ui.intro_state.render(f, main_content_area, theme);
} else if app_state.ui.show_register {
render_register(
f,
main_content_area,
theme,
register_state,
app_state,
register_state.current_field < 4
);
}else if app_state.ui.show_login { }else if app_state.ui.show_login {
render_login( render_login(
f, f,
main_content_area, main_content_area,
theme, theme,
auth_state, login_state,
app_state, // Add AppState reference here app_state,
auth_state.current_field < 2 login_state.current_field < 2
); );
} else if app_state.ui.show_admin { } else if app_state.ui.show_admin {
// Create temporary AdminPanelState for rendering crate::components::admin::admin_panel::render_admin_panel(
let mut admin_state = AdminPanelState::new(
app_state.profile_tree.profiles
.iter()
.map(|p| p.name.clone())
.collect()
);
// Set the selected item - FIXED
if !admin_state.profiles.is_empty() {
let selected_index = std::cmp::min(
app_state.general.selected_item,
admin_state.profiles.len() - 1
);
admin_state.list_state.select(Some(selected_index));
}
admin_state.render(
f, f,
admin_state,
main_content_area, main_content_area,
theme, theme,
&app_state.profile_tree, &app_state.profile_tree,

View File

@@ -7,11 +7,14 @@ use crate::modes::handlers::event::{EventHandler, EventOutcome}; // Import Event
use crate::modes::handlers::mode_manager::{AppMode, ModeManager}; use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::ui_service::UiService; use crate::services::ui_service::UiService;
use crate::state::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::form::FormState; use crate::state::pages::form::FormState;
use crate::state::state::AppState; use crate::state::pages::auth::AuthState;
use crate::tui::functions::common::form::SaveOutcome; // Import SaveOutcome use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::admin::AdminState;
use crate::state::app::state::AppState;
// Import SaveOutcome
use crate::tui::terminal::{EventReader, TerminalCore}; use crate::tui::terminal::{EventReader, TerminalCore};
use crate::ui::handlers::render::render_ui; use crate::ui::handlers::render::render_ui;
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
@@ -22,7 +25,10 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let mut grpc_client = GrpcClient::new().await?; let mut grpc_client = GrpcClient::new().await?;
let mut command_handler = CommandHandler::new(); let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme); let theme = Theme::from_str(&config.colors.theme);
let mut auth_state = AuthState::default(); // The single source of truth for AuthState let mut auth_state = AuthState::default();
let mut register_state = RegisterState::default();
let mut login_state = LoginState::default();
let mut admin_state = AdminState::default();
// Initialize app_state first // Initialize app_state first
let mut app_state = AppState::new()?; let mut app_state = AppState::new()?;
@@ -52,9 +58,12 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
render_ui( render_ui(
f, f,
&mut form_state, &mut form_state,
&mut auth_state, // Pass the single AuthState instance &mut auth_state,
&login_state,
&register_state,
&mut admin_state,
&theme, &theme,
is_edit_mode, // Use determined edit mode is_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,
@@ -105,13 +114,16 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
.handle_event( .handle_event(
event, event,
&config, &config,
&mut terminal, // Pass terminal mutably &mut terminal,
&mut grpc_client, &mut grpc_client,
&mut command_handler, &mut command_handler,
&mut form_state, &mut form_state,
&mut auth_state, &mut auth_state,
&mut login_state,
&mut register_state,
&mut admin_state,
&mut app_state, &mut app_state,
total_count, // Pass the count *before* potential save total_count,
&mut current_position, &mut current_position,
) )
.await; .await;
@@ -239,17 +251,25 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
form_state.current_cursor_pos = form_state.current_cursor_pos =
event_handler.ideal_cursor_column.min(max_cursor_pos); event_handler.ideal_cursor_column.min(max_cursor_pos);
} }
} else if app_state.ui.show_login { } else if app_state.ui.show_register {
// Handle cursor updates for AuthState if needed, similar to FormState
if !event_handler.is_edit_mode { if !event_handler.is_edit_mode {
let current_input = auth_state.get_current_input(); let current_input = register_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() { let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1 current_input.len() - 1
} else { } else {
0 0
}; };
auth_state.current_cursor_pos = register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
event_handler.ideal_cursor_column.min(max_cursor_pos); }
} else if app_state.ui.show_login {
if !event_handler.is_edit_mode {
let current_input = login_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
} }
} }

View File

@@ -14,6 +14,7 @@ message RegisterRequest {
string email = 2; string email = 2;
string password = 3; string password = 3;
string password_confirmation = 4; string password_confirmation = 4;
string role = 5;
} }
message AuthResponse { message AuthResponse {
@@ -34,4 +35,5 @@ message LoginResponse {
int32 expires_in = 3; // Expiration in seconds (86400 for 24 hours) int32 expires_in = 3; // Expiration in seconds (86400 for 24 hours)
string user_id = 4; // User's UUID in string format string user_id = 4; // User's UUID in string format
string role = 5; // User's role string role = 5; // User's role
string username = 6;
} }

Binary file not shown.

View File

@@ -9,6 +9,8 @@ pub struct RegisterRequest {
pub password: ::prost::alloc::string::String, pub password: ::prost::alloc::string::String,
#[prost(string, tag = "4")] #[prost(string, tag = "4")]
pub password_confirmation: ::prost::alloc::string::String, pub password_confirmation: ::prost::alloc::string::String,
#[prost(string, tag = "5")]
pub role: ::prost::alloc::string::String,
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct AuthResponse { pub struct AuthResponse {
@@ -50,6 +52,8 @@ pub struct LoginResponse {
/// User's role /// User's role
#[prost(string, tag = "5")] #[prost(string, tag = "5")]
pub role: ::prost::alloc::string::String, pub role: ::prost::alloc::string::String,
#[prost(string, tag = "6")]
pub username: ::prost::alloc::string::String,
} }
/// Generated client implementations. /// Generated client implementations.
pub mod auth_service_client { pub mod auth_service_client {

View File

@@ -0,0 +1,37 @@
grpcurl -plaintext -d '{
"username": "testuser_default_role",
"email": "default@example.com",
"password": "password",
"password_confirmation": "password"
}' localhost:50051 multieko2.auth.AuthService/Register
{
"id": "73017288-af41-49d8-b4cb-2ac2109b38a1",
"username": "testuser_default_role",
"email": "default@example.com",
"role": "accountant"
}
grpcurl -plaintext -d '{
"username": "testuser_admin_role",
"email": "admin@example.com",
"password": "password",
"password_confirmation": "password",
"role": "admin"
}' localhost:50051 multieko2.auth.AuthService/Register
{
"id": "9437e318-818b-4c34-822d-c2d6601b835e",
"username": "testuser_admin_role",
"email": "admin@example.com",
"role": "admin"
}
grpcurl -plaintext -d '{
"username": "testuser_invalid_role",
"email": "invalid@example.com",
"password": "password",
"password_confirmation": "password",
"role": "invalid_role_name"
}' localhost:50051 multieko2.auth.AuthService/Register
ERROR:
Code: InvalidArgument
Message: Invalid role specified: 'invalid_role_name'
╭─    ~/Doc/pr/multieko2/server    main +3 !1 
╰─

View File

@@ -11,7 +11,7 @@ pub async fn login(
) -> Result<Response<LoginResponse>, Status> { ) -> Result<Response<LoginResponse>, Status> {
let user = sqlx::query!( let user = sqlx::query!(
r#" r#"
SELECT id, password_hash, role SELECT id, username, password_hash, role
FROM users FROM users
WHERE username = $1 OR email = $1 WHERE username = $1 OR email = $1
"#, "#,
@@ -33,7 +33,7 @@ pub async fn login(
return Err(Status::unauthenticated("Invalid credentials")); return Err(Status::unauthenticated("Invalid credentials"));
} }
let token = jwt::generate_token(user.id, &user.role) let token = jwt::generate_token(user.id, &user.role, &user.username)
.map_err(|e| Status::internal(e.to_string()))?; .map_err(|e| Status::internal(e.to_string()))?;
Ok(Response::new(LoginResponse { Ok(Response::new(LoginResponse {
@@ -42,5 +42,6 @@ pub async fn login(
expires_in: 86400, // 24 hours expires_in: 86400, // 24 hours
user_id: user.id.to_string(), user_id: user.id.to_string(),
role: user.role, role: user.role,
username: user.username,
})) }))
} }

View File

@@ -5,6 +5,8 @@ use common::proto::multieko2::auth::{RegisterRequest, AuthResponse};
use crate::db::PgPool; use crate::db::PgPool;
use crate::auth::models::AuthError; use crate::auth::models::AuthError;
const DEFAULT_ROLE: &str = "accountant";
pub async fn register( pub async fn register(
pool: &PgPool, pool: &PgPool,
payload: RegisterRequest, payload: RegisterRequest,
@@ -18,20 +20,28 @@ pub async fn register(
let password_hash = hash(payload.password, DEFAULT_COST) let password_hash = hash(payload.password, DEFAULT_COST)
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?; .map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
let role_to_insert = if payload.role.is_empty() { DEFAULT_ROLE } else { &payload.role };
// Insert user // Insert user
let user = sqlx::query!( let user = sqlx::query!(
r#" r#"
INSERT INTO users (username, email, password_hash, role) INSERT INTO users (username, email, password_hash, role)
VALUES ($1, $2, $3, 'accountant') VALUES ($1, $2, $3, $4)
RETURNING id, username, email, role RETURNING id, username, email, role
"#, "#,
payload.username, payload.username,
payload.email, payload.email,
password_hash password_hash,
role_to_insert
) )
.fetch_one(pool) .fetch_one(pool)
.await .await
.map_err(|e| { .map_err(|e| {
if let Some(db_err) = e.as_database_error() {
if db_err.constraint() == Some("valid_roles") {
return Status::invalid_argument(format!("Invalid role specified: '{}'", role_to_insert));
}
}
if e.to_string().contains("duplicate key") { if e.to_string().contains("duplicate key") {
Status::already_exists(AuthError::UserExists.to_string()) Status::already_exists(AuthError::UserExists.to_string())
} else { } else {

View File

@@ -18,6 +18,7 @@ pub struct Claims {
pub sub: Uuid, // User ID pub sub: Uuid, // User ID
pub exp: i64, // Expiration time pub exp: i64, // Expiration time
pub role: String, // User role pub role: String, // User role
pub username: String,
} }
pub fn init_jwt() -> Result<(), AuthError> { pub fn init_jwt() -> Result<(), AuthError> {
@@ -32,7 +33,7 @@ pub fn init_jwt() -> Result<(), AuthError> {
Ok(()) Ok(())
} }
pub fn generate_token(user_id: Uuid, role: &str) -> Result<String, AuthError> { pub fn generate_token(user_id: Uuid, role: &str, username: &str) -> Result<String, AuthError> {
let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?; let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?;
let exp = OffsetDateTime::now_utc() + Duration::days(365000); let exp = OffsetDateTime::now_utc() + Duration::days(365000);
@@ -40,6 +41,7 @@ pub fn generate_token(user_id: Uuid, role: &str) -> Result<String, AuthError> {
sub: user_id, sub: user_id,
exp: exp.unix_timestamp(), exp: exp.unix_timestamp(),
role: role.to_string(), role: role.to_string(),
username: username.to_string(),
}; };
encode(&Header::default(), &claims, &keys.encoding) encode(&Header::default(), &claims, &keys.encoding)