Compare commits

...

43 Commits

Author SHA1 Message Date
filipriec
f4689125e0 minor changes 2025-04-15 20:28:31 +02:00
filipriec
bbba67a253 buffer for form fix performed 2025-04-15 20:19:30 +02:00
filipriec
800b857e53 buffers are in the layers now 2025-04-15 19:42:12 +02:00
filipriec
921059bed8 buffer logic going hard, we are killing buffers from login and register now 2025-04-15 18:56:11 +02:00
filipriec
e8b585dc07 killing of the buffers now works 2025-04-15 18:43:36 +02:00
filipriec
afce27184a better defaults 2025-04-15 18:37:27 +02:00
filipriec
8d41beef0b killing of the buffer working 2025-04-15 18:33:42 +02:00
filipriec
5e482cd77b buffer close, not kill implemented yet 2025-04-15 18:29:59 +02:00
filipriec
09068fd4e5 FPS counter added 2025-04-15 18:11:26 +02:00
filipriec
d8c2b9089b fixes are now in place properly well 2025-04-15 17:52:58 +02:00
filipriec
bb577bc276 now buffer handling is global but not allowed from edit mode 2025-04-15 16:23:26 +02:00
filipriec
6267e3d593 working switching of the buffers properly well now 2025-04-15 16:03:14 +02:00
filipriec
c091a39802 compiled 2025-04-15 14:12:42 +02:00
filipriec
f94006dd08 buffer its independent, needs fixes 2025-04-15 13:57:17 +02:00
filipriec
f42790980d perfectly working buffer now 2025-04-15 00:18:42 +02:00
filipriec
779683de4b buffer movement is now working as I would only wish it would. Needs layers implementation, will do in the future 2025-04-15 00:10:28 +02:00
filipriec
aa8887318f history of buffers implemented now 2025-04-14 23:58:58 +02:00
filipriec
3ad8dc6490 better buffer list 2025-04-14 23:35:56 +02:00
filipriec
20f9fae141 buffer working 2025-04-14 22:34:22 +02:00
filipriec
ec062bbf24 its on the top of the screen now 2025-04-14 22:17:24 +02:00
filipriec
8745c9ea2f sidebar fixed bugs and buffer implementation 1 2025-04-14 22:14:01 +02:00
filipriec
0917654361 admin panel now distinguish admin and other roles of the user 2025-04-14 21:04:55 +02:00
filipriec
d892d1cfa0 role restricted admin panel 2025-04-14 20:50:02 +02:00
filipriec
e31138c250 DONE we have now intro state separate from others completely 2025-04-14 20:00:02 +02:00
filipriec
7cbe5ce8be intro movement fixed 2025-04-14 16:25:54 +02:00
filipriec
1c31d4cd1c moved introstate into the state folder 2025-04-14 16:24:21 +02:00
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
58 changed files with 1128 additions and 642 deletions

24
Cargo.lock generated
View File

@@ -421,7 +421,7 @@ dependencies = [
[[package]] [[package]]
name = "client" name = "client"
version = "0.3.5" version = "0.3.13"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"common", "common",
@@ -432,10 +432,12 @@ dependencies = [
"prost", "prost",
"ratatui", "ratatui",
"serde", "serde",
"time",
"tokio", "tokio",
"toml", "toml",
"tonic", "tonic",
"tracing", "tracing",
"unicode-segmentation",
"unicode-width 0.2.0", "unicode-width 0.2.0",
] ]
@@ -460,7 +462,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "0.3.5" version = "0.3.13"
dependencies = [ dependencies = [
"prost", "prost",
"serde", "serde",
@@ -712,9 +714,9 @@ dependencies = [
[[package]] [[package]]
name = "deranged" name = "deranged"
version = "0.3.11" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" checksum = "9c9e6a11ca8224451684bc0d7d5a7adbf8f2fd6887261a1cfc3c0432f9d4068e"
dependencies = [ dependencies = [
"powerfmt", "powerfmt",
] ]
@@ -2591,7 +2593,7 @@ dependencies = [
[[package]] [[package]]
name = "server" name = "server"
version = "0.3.5" version = "0.3.13"
dependencies = [ dependencies = [
"bcrypt", "bcrypt",
"chrono", "chrono",
@@ -3211,9 +3213,9 @@ dependencies = [
[[package]] [[package]]
name = "time" name = "time"
version = "0.3.39" version = "0.3.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dad298b01a40a23aac4580b67e3dbedb7cc8402f3592d7f49469de2ea4aecdd8" checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40"
dependencies = [ dependencies = [
"deranged", "deranged",
"itoa", "itoa",
@@ -3228,15 +3230,15 @@ dependencies = [
[[package]] [[package]]
name = "time-core" name = "time-core"
version = "0.1.3" version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "765c97a5b985b7c11d7bc27fa927dc4fe6af3a6dfb021d28deb60d3bf51e76ef" checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c"
[[package]] [[package]]
name = "time-macros" name = "time-macros"
version = "0.2.20" version = "0.2.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8093bc3e81c3bc5f7879de09619d06c9a5a5e45ca44dfeeb7225bae38005c5c" checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49"
dependencies = [ dependencies = [
"num-conv", "num-conv",
"time-core", "time-core",

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.5" version = "0.3.13"
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

@@ -1,5 +1,7 @@
# Hey # Hey
This is only work in progress, until release 1.0.0 this is for development use cases only.
I run development like this: I run development like this:
Server: Server:

View File

@@ -15,8 +15,10 @@ 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"] }
time = "0.3.41"
tokio = { version = "1.43.0", features = ["full", "macros"] } 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" unicode-width = "0.2.0"

View File

@@ -2,6 +2,8 @@
[keybindings] [keybindings]
enter_command_mode = [":", "ctrl+;"] enter_command_mode = [":", "ctrl+;"]
next_buffer = ["ctrl+l"]
previous_buffer = ["ctrl+h"]
[keybindings.general] [keybindings.general]
move_up = ["k", "Up"] move_up = ["k", "Up"]
@@ -10,6 +12,7 @@ next_option = ["l", "Right"]
previous_option = ["h", "Left"] previous_option = ["h", "Left"]
select = ["Enter"] select = ["Enter"]
toggle_sidebar = ["ctrl+t"] toggle_sidebar = ["ctrl+t"]
toggle_buffer_list = ["ctrl+b"]
next_field = ["Tab"] next_field = ["Tab"]
prev_field = ["Shift+Tab"] prev_field = ["Shift+Tab"]
@@ -24,6 +27,7 @@ save_and_quit = ["ctrl+shift+s"]
move_up = ["Up"] move_up = ["Up"]
move_down = ["Down"] move_down = ["Down"]
toggle_sidebar = ["ctrl+t"] toggle_sidebar = ["ctrl+t"]
toggle_buffer_list = ["ctrl+b"]
# MODE SPECIFIC # MODE SPECIFIC
# READ ONLY MODE # READ ONLY MODE

View File

@@ -1,118 +1,137 @@
// src/components/admin/admin_panel.rs // src/components/admin/admin_panel.rs
use crate::config::colors::themes::Theme;
use crate::state::pages::auth::AuthState;
use crate::state::pages::admin::AdminState;
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use ratatui::{ use ratatui::{
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph}, layout::{Alignment, Constraint, Direction, Layout, Rect},
style::Style, style::Style,
text::{Line, Span, Text}, text::{Line, Span, Text},
layout::{Alignment, Constraint, Direction, Layout, Rect}, 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 { /// Renders the view specific to admin users.
pub list_state: ListState, fn render_admin_panel_admin(f: &mut Frame, content_chunks: &[Rect], theme: &Theme) {
pub profiles: Vec<String>, // Admin-specific view placeholder
let admin_message = Paragraph::new("Admin-specific view. Profile selection not applicable.")
.style(Style::default().fg(theme.fg))
.alignment(Alignment::Center);
// Render only in the right pane for now, leaving left empty
f.render_widget(admin_message, content_chunks[1]);
} }
impl AdminPanelState { pub fn render_admin_panel(
pub fn new(profiles: Vec<String>) -> Self { f: &mut Frame,
let mut list_state = ListState::default(); auth_state: &AuthState,
if !profiles.is_empty() { admin_state: &AdminState,
list_state.select(Some(0)); area: Rect,
} theme: &Theme,
Self { list_state, profiles } 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);
f.render_widget(block, area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(1)])
.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]);
if auth_state.role.as_deref() != Some("admin") {
render_admin_panel_non_admin(
f,
admin_state,
&content_chunks,
theme,
profile_tree,
selected_profile,
);
} else {
render_admin_panel_admin(f, &content_chunks, theme);
} }
}
pub fn next(&mut self) { /// Renders the view for non-admin users (profile list and details).
let i = self.list_state.selected().map_or(0, |i| fn render_admin_panel_non_admin(
if i >= self.profiles.len() - 1 { 0 } else { i + 1 }); f: &mut Frame,
self.list_state.select(Some(i)); admin_state: &AdminState,
} content_chunks: &[Rect],
theme: &Theme,
pub fn previous(&mut self) { profile_tree: &ProfileTreeResponse,
let i = self.list_state.selected().map_or(0, |i| selected_profile: &Option<String>,
if i == 0 { self.profiles.len() - 1 } else { i - 1 }); ) {
self.list_state.select(Some(i)); // Profile list - Use data from admin_state
} let items: Vec<ListItem> = admin_state
.profiles
pub fn render( .iter()
&mut self, .map(|p| {
f: &mut Frame, ListItem::new(Line::from(vec![
area: Rect,
theme: &Theme,
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);
f.render_widget(block, area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(1)])
.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(
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); let mut list_state_clone = admin_state.list_state.clone();
f.render_stateful_widget(list, content_chunks[0], &mut list_state_clone);
// Profile details // Profile details - Use selection info from admin_state
if let Some(profile) = self.list_state.selected() if let Some(profile) = admin_state
.and_then(|i| profile_tree.profiles.get(i)) .get_selected_index()
{ .and_then(|i| profile_tree.profiles.get(i))
let mut text = Text::default(); {
text.lines.push(Line::from(vec![ let mut text = Text::default();
Span::styled("Profile: ", Style::default().fg(theme.accent)), text.lines.push(Line::from(vec![
Span::styled(&profile.name, Style::default().fg(theme.highlight)), Span::styled("Profile: ", Style::default().fg(theme.accent)),
])); Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]));
text.lines.push(Line::from("")); text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled("Tables:", Style::default().fg(theme.accent)))); text.lines.push(Line::from(Span::styled(
"Tables:",
Style::default().fg(theme.accent),
)));
for table in &profile.tables { for table in &profile.tables {
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)]; let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
if !table.depends_on.is_empty() { if !table.depends_on.is_empty() {
line.push(Span::styled( line.push(Span::styled(
format!("{}", table.depends_on.join(", ")), format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary) Style::default().fg(theme.secondary),
)); ));
}
text.lines.push(Line::from(line));
} }
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 });
f.render_widget(details_widget, content_chunks[1]);
} }
} }

View File

@@ -2,9 +2,9 @@
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 ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin}, layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
@@ -17,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,
) { ) {
@@ -50,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))
@@ -77,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
}; };
@@ -104,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

@@ -4,14 +4,14 @@ use crate::{
config::colors::themes::Theme, config::colors::themes::Theme,
state::pages::auth::RegisterState, // Use RegisterState state::pages::auth::RegisterState, // Use RegisterState
components::common::{dialog, autocomplete}, components::common::{dialog, autocomplete},
state::state::AppState, state::app::state::AppState,
state::canvas_state::CanvasState, state::pages::canvas_state::CanvasState,
modes::handlers::mode_manager::AppMode, 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},
widgets::{Block, BorderType, Borders, Paragraph, Wrap}, widgets::{Block, BorderType, Borders, Paragraph},
Frame, Frame,
}; };
@@ -42,6 +42,7 @@ pub fn render_register(
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([ .constraints([
Constraint::Length(7), // Form (5 fields + padding) Constraint::Length(7), // Form (5 fields + padding)
Constraint::Length(1), // Help text line
Constraint::Length(1), // Error message Constraint::Length(1), // Error message
Constraint::Length(3), // Buttons Constraint::Length(3), // Buttons
]) ])
@@ -54,25 +55,31 @@ pub fn render_register(
state, // The state object (RegisterState) state, // The state object (RegisterState)
&[ // Field labels &[ // Field labels
"Username", "Username",
"Email (Optional)", "Email*",
"Password (Optional)", "Password*",
"Confirm Password", "Confirm Password",
"Role (Optional)", "Role* (Tab)",
], ],
&state.current_field(), // Pass current field index &state.current_field(), // Pass current field index
&state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(), // Pass inputs directly &state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(), // Pass inputs directly
theme, theme,
is_edit_mode, is_edit_mode,
// No need to pass suggestion state here, render_canvas uses the trait
); );
// --- 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 --- // --- ERROR MESSAGE ---
if let Some(err) = &state.error_message { if let Some(err) = &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))
.alignment(Alignment::Center), .alignment(Alignment::Center),
chunks[1], chunks[2],
); );
} }
@@ -80,12 +87,12 @@ pub fn render_register(
let button_chunks = Layout::default() let button_chunks = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(chunks[2]); .split(chunks[3]);
// Register Button // Register Button
let register_button_index = 0; let register_button_index = 0;
let register_active = if app_state.ui.focus_outside_canvas { let register_active = if app_state.ui.focus_outside_canvas {
app_state.general.selected_item == register_button_index app_state.focused_button_index== register_button_index
} else { } else {
false false
}; };
@@ -112,7 +119,7 @@ pub fn render_register(
// Return Button (logic remains similar) // Return Button (logic remains similar)
let return_button_index = 1; let return_button_index = 1;
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 false
}; };

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

@@ -1,11 +1,11 @@
// src/client/components/handlers/status_line.rs
use ratatui::{ use ratatui::{
widgets::Paragraph,
style::Style, style::Style,
layout::Rect, layout::Rect,
Frame, Frame,
text::{Line, Span}, text::{Line, Span},
widgets::Paragraph,
}; };
use unicode_width::UnicodeWidthStr;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use std::path::Path; use std::path::Path;
@@ -15,17 +15,11 @@ pub fn render_status_line(
current_dir: &str, current_dir: &str,
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
current_fps: f64,
) { ) {
// Program name and version
let program_info = format!("multieko2 v{}", env!("CARGO_PKG_VERSION")); let program_info = format!("multieko2 v{}", env!("CARGO_PKG_VERSION"));
let mode_text = if is_edit_mode { "[EDIT]" } else { "[READ-ONLY]" };
let mode_text = if is_edit_mode {
"[EDIT]"
} else {
"[READ-ONLY]"
};
// Shorten the current directory path
let home_dir = dirs::home_dir().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default(); let home_dir = dirs::home_dir().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
let display_dir = if current_dir.starts_with(&home_dir) { let display_dir = if current_dir.starts_with(&home_dir) {
current_dir.replacen(&home_dir, "~", 1) current_dir.replacen(&home_dir, "~", 1)
@@ -33,47 +27,51 @@ pub fn render_status_line(
current_dir.to_string() current_dir.to_string()
}; };
// Create the full status line text
let full_text = format!("{} | {} | {}", mode_text, display_dir, program_info);
// Check if the full text fits in the available width
let available_width = area.width as usize; let available_width = area.width as usize;
let mut display_text = if full_text.len() <= available_width { let mode_width = UnicodeWidthStr::width(mode_text);
// If it fits, use the full text let program_info_width = UnicodeWidthStr::width(program_info.as_str());
full_text let fps_text = format!("{:.0} FPS", current_fps);
let fps_width = UnicodeWidthStr::width(fps_text.as_str());
let separator = " | ";
let separator_width = UnicodeWidthStr::width(separator);
let fixed_width_with_fps = mode_width + separator_width + separator_width +
program_info_width + separator_width + fps_width;
let show_fps = fixed_width_with_fps < available_width;
let remaining_width_for_dir = available_width.saturating_sub(
mode_width + separator_width + separator_width + program_info_width +
if show_fps { separator_width + fps_width } else { 0 }
);
let dir_display_text = if UnicodeWidthStr::width(display_dir.as_str()) <= remaining_width_for_dir {
display_dir
} else { } else {
// If it doesn't fit, prioritize mode and program info, and show only the directory name
let dir_name = Path::new(current_dir) let dir_name = Path::new(current_dir)
.file_name() .file_name()
.and_then(|n| n.to_str()) .and_then(|n| n.to_str())
.unwrap_or(current_dir); .unwrap_or(current_dir);
format!("{} | {} | {}", mode_text, dir_name, program_info) if UnicodeWidthStr::width(dir_name) <= remaining_width_for_dir {
dir_name.to_string()
} else {
dir_name.chars().take(remaining_width_for_dir).collect()
}
}; };
// If even the shortened version overflows, truncate it let mut spans = vec![
if display_text.len() > available_width {
display_text = display_text.chars().take(available_width).collect();
}
// Create the status line text using Line and Span
let status_line = Line::from(vec![
Span::styled(mode_text, Style::default().fg(theme.accent)), Span::styled(mode_text, Style::default().fg(theme.accent)),
Span::styled(" | ", Style::default().fg(theme.border)), Span::styled(" | ", Style::default().fg(theme.border)),
Span::styled( Span::styled(dir_display_text, Style::default().fg(theme.fg)),
display_text.split(" | ").nth(1).unwrap_or(""), // Directory part
Style::default().fg(theme.fg),
),
Span::styled(" | ", Style::default().fg(theme.border)), Span::styled(" | ", Style::default().fg(theme.border)),
Span::styled( Span::styled(program_info, Style::default().fg(theme.secondary)),
program_info, ];
Style::default()
.fg(theme.secondary)
.add_modifier(ratatui::style::Modifier::BOLD),
),
]);
// Render the status line if show_fps {
let paragraph = Paragraph::new(status_line) spans.push(Span::styled(" | ", Style::default().fg(theme.border)));
spans.push(Span::styled(fps_text, Style::default().fg(theme.secondary)));
}
let paragraph = Paragraph::new(Line::from(spans))
.style(Style::default().bg(theme.bg)); .style(Style::default().bg(theme.bg));
f.render_widget(paragraph, area); f.render_widget(paragraph, area);

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

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

View File

@@ -0,0 +1,76 @@
// src/components/handlers/buffer_list.rs
use crate::config::colors::themes::Theme;
use crate::state::app::buffer::BufferState;
use ratatui::{
layout::{Alignment, Rect},
style::{Style, Stylize},
text::{Line, Span},
widgets::Paragraph,
Frame,
};
use unicode_width::UnicodeWidthStr;
use crate::functions::common::buffer::get_view_layer;
pub fn render_buffer_list(
f: &mut Frame,
area: Rect,
theme: &Theme,
buffer_state: &BufferState,
) {
// --- Style Definitions ---
let active_style = Style::default()
.fg(theme.bg)
.bg(theme.highlight);
let inactive_style = Style::default()
.fg(theme.fg)
.bg(theme.bg);
// --- Determine Active Layer ---
let active_layer = match buffer_state.history.get(buffer_state.active_index) {
Some(view) => get_view_layer(view),
None => 1,
};
// --- Create Spans ---
let mut spans = Vec::new();
let mut current_width = 0;
for (original_index, view) in buffer_state.history.iter().enumerate() {
// Filter: Only process views matching the active layer
if get_view_layer(view) != active_layer {
continue;
}
let is_active = original_index == buffer_state.active_index;
let buffer_name = view.display_name();
let buffer_text = format!(" {} ", buffer_name);
let text_width = UnicodeWidthStr::width(buffer_text.as_str());
// Calculate width needed for this buffer (separator + text)
let needed_width = text_width;
if current_width + needed_width > area.width as usize {
break;
}
// Add the buffer text itself
let text_style = if is_active { active_style } else { inactive_style };
spans.push(Span::styled(buffer_text, text_style));
current_width += text_width;
}
// --- Filler Span ---
let remaining_width = area.width.saturating_sub(current_width as u16);
if !spans.is_empty() || remaining_width > 0 {
spans.push(Span::styled(
" ".repeat(remaining_width as usize),
inactive_style,
));
}
// --- Render ---
let buffer_line = Line::from(spans);
let paragraph = Paragraph::new(buffer_line).alignment(Alignment::Left);
f.render_widget(paragraph, area);
}

View File

@@ -8,9 +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;
use crate::components::common::autocomplete;
use crate::components::render_autocomplete_dropdown;
pub fn render_canvas( pub fn render_canvas(
f: &mut Frame, f: &mut Frame,

View File

@@ -8,103 +8,80 @@ use ratatui::{
Frame, Frame,
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::state::pages::intro::IntroState;
pub struct IntroState { pub fn render_intro(f: &mut Frame, intro_state: &IntroState, area: Rect, theme: &Theme) {
pub selected_option: usize, 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);
f.render_widget(block, area);
// Center layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(40),
Constraint::Length(5),
Constraint::Percentage(40),
])
.split(inner_area);
// Title
let title = Line::from(vec![
Span::styled("multieko2", Style::default().fg(theme.highlight)),
Span::styled(" v", Style::default().fg(theme.fg)),
Span::styled(env!("CARGO_PKG_VERSION"), Style::default().fg(theme.secondary)),
]);
let title_para = Paragraph::new(title)
.alignment(Alignment::Center);
f.render_widget(title_para, chunks[1]);
// Buttons - now with 4 options
let button_area = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
])
.split(chunks[1].inner(Margin {
horizontal: 1,
vertical: 1
}));
let buttons = ["Continue", "Admin", "Login", "Register"];
for (i, &text) in buttons.iter().enumerate() {
render_button(f, button_area[i], text, intro_state.selected_option == i, theme);
}
} }
impl IntroState { fn render_button(f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
pub fn new() -> Self { let button_style = Style::default()
Self { selected_option: 0 } .fg(if selected { theme.highlight } else { theme.fg })
} .bg(theme.bg)
.add_modifier(if selected {
ratatui::style::Modifier::BOLD
} else {
ratatui::style::Modifier::empty()
});
pub fn render(&self, f: &mut Frame, area: Rect, theme: &Theme) { let border_style = Style::default()
let block = Block::default() .fg(if selected { theme.accent } else { theme.border });
let button = Paragraph::new(text)
.style(button_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_type(BorderType::Rounded) .border_type(BorderType::Double)
.border_style(Style::default().fg(theme.accent)) .border_style(border_style),
.style(Style::default().bg(theme.bg)); );
let inner_area = block.inner(area); f.render_widget(button, area);
f.render_widget(block, area);
// Center layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(40),
Constraint::Length(5),
Constraint::Percentage(40),
])
.split(inner_area);
// Title
let title = Line::from(vec![
Span::styled("multieko2", Style::default().fg(theme.highlight)),
Span::styled(" v", Style::default().fg(theme.fg)),
Span::styled(env!("CARGO_PKG_VERSION"), Style::default().fg(theme.secondary)),
]);
let title_para = Paragraph::new(title)
.alignment(Alignment::Center);
f.render_widget(title_para, chunks[1]);
// Buttons - now with 4 options
let button_area = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
])
.split(chunks[1].inner(Margin {
horizontal: 1,
vertical: 1
}));
let buttons = ["Continue", "Admin", "Login", "Register"];
for (i, &text) in buttons.iter().enumerate() {
self.render_button(
f,
button_area[i],
text,
self.selected_option == i,
theme,
);
}
}
fn render_button(&self, f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
let button_style = Style::default()
.fg(if selected { theme.highlight } else { theme.fg })
.bg(theme.bg)
.add_modifier(if selected {
ratatui::style::Modifier::BOLD
} else {
ratatui::style::Modifier::empty()
});
let border_style = Style::default()
.fg(if selected { theme.accent } else { theme.border });
let button = Paragraph::new(text)
.style(button_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Double)
.border_style(border_style),
);
f.render_widget(button, area);
}
pub fn next_option(&mut self) {
self.selected_option = (self.selected_option + 1) % 4;
}
pub fn previous_option(&mut self) {
self.selected_option = if self.selected_option == 0 { 3 } else { self.selected_option - 1 };
}
} }

View File

@@ -1,2 +1,5 @@
// src/functions/common.rs // src/functions/common.rs
pub mod buffer;
pub use buffer::*;

View File

@@ -0,0 +1,35 @@
// src/functions/common/buffer.rs
use crate::state::app::buffer::BufferState;
use crate::state::app::buffer::AppView;
pub fn get_view_layer(view: &AppView) -> u8 {
match view {
AppView::Intro => 1,
AppView::Login | AppView::Register | AppView::Admin => 2,
AppView::Form(_) | AppView::Scratch => 3,
}
}
/// Switches the active buffer index.
pub fn switch_buffer(buffer_state: &mut BufferState, next: bool) -> bool {
if buffer_state.history.len() <= 1 {
return false;
}
let len = buffer_state.history.len();
let current_index = buffer_state.active_index;
let new_index = if next {
(current_index + 1) % len
} else {
(current_index + len - 1) % len
};
if new_index != current_index {
buffer_state.active_index = new_index;
true
} else {
false
}
}

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,7 +1,7 @@
// 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::form::FormState; use crate::state::pages::form::FormState;
use crate::state::pages::auth::RegisterState; use crate::state::pages::auth::RegisterState;
use crate::tui::functions::common::form::{revert, save}; use crate::tui::functions::common::form::{revert, save};
@@ -300,9 +300,9 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
// --- Autocomplete Actions --- // --- Autocomplete Actions ---
"suggestion_down" | "suggestion_up" | "select_suggestion" | "exit_suggestion_mode" => { "suggestion_down" | "suggestion_up" | "select_suggestion" | "exit_suggestion_mode" => {
// Attempt to downcast to RegisterState // Attempt to downcast to RegisterState to handle suggestion logic here
if let Some(register_state) = (state as &mut dyn Any).downcast_mut::<RegisterState>() { if let Some(register_state) = (state as &mut dyn Any).downcast_mut::<RegisterState>() {
// Only handle if it's the role field (index 4) and suggestions are shown (except for hide) // Only handle if it's the role field (index 4)
if register_state.current_field() == 4 { if register_state.current_field() == 4 {
match action { match action {
"suggestion_down" if register_state.in_suggestion_mode => { "suggestion_down" if register_state.in_suggestion_mode => {
@@ -319,34 +319,37 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
} }
"select_suggestion" if register_state.in_suggestion_mode => { "select_suggestion" if register_state.in_suggestion_mode => {
if let Some(index) = register_state.selected_suggestion_index { if let Some(index) = register_state.selected_suggestion_index {
let selected_role = register_state.role_suggestions[index].clone(); if let Some(selected_role) = register_state.role_suggestions.get(index).cloned() {
register_state.role = selected_role.clone(); // Update the role field register_state.role = selected_role.clone(); // Update the role field
register_state.in_suggestion_mode = false; // Exit suggestion mode register_state.in_suggestion_mode = false; // Exit suggestion mode
register_state.show_role_suggestions = false; // Hide suggestions register_state.show_role_suggestions = false; // Hide suggestions
register_state.selected_suggestion_index = None; // Clear selection register_state.selected_suggestion_index = None; // Clear selection
Ok(format!("Selected role: {}", selected_role)) // Return success message Ok(format!("Selected role: {}", selected_role)) // Return success message
} else {
Ok("Selected suggestion index out of bounds.".to_string()) // Error case
}
} else { } else {
Ok("No suggestion selected".to_string()) Ok("No suggestion selected".to_string())
} }
} }
"exit_suggestion_mode" => { // Handle Esc "exit_suggestion_mode" => { // Handle Esc or other conditions
register_state.show_role_suggestions = false; register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None; register_state.selected_suggestion_index = None;
register_state.in_suggestion_mode = false; register_state.in_suggestion_mode = false;
Ok("Suggestions hidden".to_string()) Ok("Suggestions hidden".to_string())
} }
"suggestion_down" | "suggestion_up" | "select_suggestion" => { _ => {
Ok("Suggestion action ignored: Not in suggestion mode.".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())
} }
_ => Ok("".to_string())
} }
} else { } else {
Ok("".to_string()) // It's RegisterState, but not the role field
} Ok("Suggestion action ignored: Not on role field.".to_string())
}
} else { } else {
// Downcast failed - this action is only for RegisterState // Downcast failed - this action is only for RegisterState
Ok(format!("Action '{}' not applicable for this form type.", action)) Ok(format!("Action '{}' not applicable for this state type.", action))
} }
} }
// --- End Autocomplete Actions --- // --- End Autocomplete Actions ---

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,8 +1,8 @@
// 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, auth::RegisterState}; 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;
@@ -17,6 +17,7 @@ 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, register_state: &mut RegisterState,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient, auth_client: &mut AuthClient,
@@ -28,7 +29,7 @@ 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)) Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
let message = register_save(register_state, auth_client, app_state).await?; let message = register_save(register_state, auth_client, app_state).await?;
@@ -54,7 +55,7 @@ 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 { } else if app_state.ui.show_register {
register_save(register_state, auth_client, app_state).await? register_save(register_state, auth_client, app_state).await?
} else { } else {
@@ -75,7 +76,7 @@ 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)) Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
let message = register_revert(register_state, app_state).await; let message = register_revert(register_state, app_state).await;

View File

@@ -2,19 +2,19 @@
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, RegisterState}}; use crate::state::pages::{auth::{LoginState, RegisterState}};
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::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 crate::state::state::AppState; use crate::state::app::state::AppState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
pub async fn handle_edit_event( pub async fn handle_edit_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, register_state: &mut RegisterState,
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
command_message: &mut String, command_message: &mut String,
@@ -44,7 +44,7 @@ pub async fn handle_edit_event(
let message = if app_state.ui.show_login { 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, grpc_client,
current_position, current_position,
total_count total_count
@@ -99,7 +99,7 @@ pub async fn handle_edit_event(
auth_e::execute_edit_action( auth_e::execute_edit_action(
action, action,
key, key,
auth_state, login_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
@@ -143,7 +143,7 @@ pub async fn handle_edit_event(
auth_e::execute_edit_action( auth_e::execute_edit_action(
"insert_char", "insert_char",
key, key,
auth_state, login_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,

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, pages::auth::RegisterState}; 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,7 @@ 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, register_state: &mut RegisterState,
key_sequence_tracker: &mut KeySequenceTracker, key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64, current_position: &mut u64,
@@ -34,8 +34,8 @@ 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 { // Check Login first 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 } else if app_state.ui.show_register { // Then check Register
( (
@@ -51,8 +51,8 @@ pub async fn handle_read_only_event(
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 if app_state.ui.show_register { } else if app_state.ui.show_register {
register_state.set_current_cursor_pos(current_pos + 1); register_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = register_state.current_cursor_pos(); *ideal_cursor_column = register_state.current_cursor_pos();
@@ -95,12 +95,7 @@ pub async fn handle_read_only_event(
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions } 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,
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register{ } else if app_state.ui.show_register{
auth_ro::execute_action( auth_ro::execute_action(
action, action,
@@ -114,7 +109,7 @@ pub async fn handle_read_only_event(
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,
@@ -151,12 +146,7 @@ pub async fn handle_read_only_event(
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions } 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,
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions } else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_ro::execute_action( auth_ro::execute_action(
action, action,
@@ -170,7 +160,7 @@ pub async fn handle_read_only_event(
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,
@@ -206,12 +196,7 @@ pub async fn handle_read_only_event(
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions } 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,
auth_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions } else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_ro::execute_action( auth_ro::execute_action(
action, action,
@@ -225,7 +210,7 @@ pub async fn handle_read_only_event(
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,

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

@@ -3,10 +3,11 @@
use crossterm::event::{Event, KeyCode}; use crossterm::event::{Event, KeyCode};
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::ui::handlers::context::DialogPurpose; use crate::ui::handlers::context::DialogPurpose;
use crate::state::state::AppState; use crate::state::app::state::AppState;
use crate::state::app::buffer::BufferState;
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState; use crate::state::pages::auth::RegisterState;
use crate::services::auth::AuthClient;
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::{login, register}; use crate::tui::functions::common::{login, register};
@@ -18,8 +19,9 @@ pub async fn handle_dialog_event(
config: &Config, config: &Config,
app_state: &mut AppState, app_state: &mut AppState,
auth_state: &mut AuthState, auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState, register_state: &mut RegisterState,
auth_client: &mut AuthClient, buffer_state: &mut BufferState,
) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> { ) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> {
if let Event::Key(key) = event { if let Event::Key(key) = event {
// Always allow Esc to dismiss // Always allow Esc to dismiss
@@ -62,7 +64,7 @@ pub async fn handle_dialog_event(
match selected_index { match selected_index {
0 => { // "Menu" button selected 0 => { // "Menu" button selected
app_state.hide_dialog(); app_state.hide_dialog();
let message = login::back_to_main(auth_state, app_state).await; let message = login::back_to_main(login_state, app_state, buffer_state).await;
return Some(Ok(EventOutcome::Ok(message))); return Some(Ok(EventOutcome::Ok(message)));
} }
1 => { 1 => {
@@ -91,8 +93,7 @@ pub async fn handle_dialog_event(
match selected_index { match selected_index {
0 => { // "OK" button for RegisterSuccess 0 => { // "OK" button for RegisterSuccess
app_state.hide_dialog(); app_state.hide_dialog();
// Go back to intro after successful registration dialog let message = register::back_to_login(register_state, app_state, buffer_state).await;
let message = register::back_to_main(register_state, app_state).await;
return Some(Ok(EventOutcome::Ok(message))); return Some(Ok(EventOutcome::Ok(message)));
} }
_ => { // Default for RegisterSuccess _ => { // Default for RegisterSuccess

View File

@@ -2,10 +2,13 @@
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::intro::IntroState;
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 +17,10 @@ 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,
intro_state: &mut IntroState,
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,27 +28,21 @@ 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, intro_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, intro_state, admin_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
"next_option" => { "next_option" => {
next_option(app_state); next_option(app_state, intro_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
"previous_option" => { "previous_option" => {
previous_option(app_state); previous_option(app_state, intro_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
"toggle_sidebar" => {
toggle_sidebar(app_state);
return Ok(EventOutcome::Ok(format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
"next_field" => { "next_field" => {
next_field(form_state); next_field(form_state);
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
@@ -57,17 +57,16 @@ pub async fn handle_navigation_event(
} }
"select" => { "select" => {
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, 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 { } else if app_state.ui.show_register && app_state.ui.focus_outside_canvas {
(UiContext::Register, app_state.general.selected_item) (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 });
@@ -78,79 +77,63 @@ 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, intro_state: &mut IntroState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register{ 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(); 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, intro_state: &mut IntroState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register { 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(); 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;
} }
} }
pub fn next_option(app_state: &mut AppState) { // Remove option_count parameter pub fn next_option(app_state: &mut AppState, intro_state: &mut IntroState) {
if app_state.ui.show_intro { if app_state.ui.show_intro {
app_state.ui.intro_state.next_option(); intro_state.next_option();
} 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;
} }
} }
pub fn previous_option(app_state: &mut AppState) { pub fn previous_option(app_state: &mut AppState, intro_state: &mut IntroState) {
if app_state.ui.show_intro { if app_state.ui.show_intro {
app_state.ui.intro_state.previous_option(); 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
}; };
} }
} }
pub fn toggle_sidebar(app_state: &mut AppState) {
app_state.ui.show_sidebar = !app_state.ui.show_sidebar;
}
pub fn next_field(form_state: &mut FormState) { pub fn next_field(form_state: &mut FormState) {
if !form_state.fields.is_empty() { if !form_state.fields.is_empty() {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len(); form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();

View File

@@ -1,27 +1,43 @@
// src/modes/handlers/event.rs // src/modes/handlers/event.rs
use crossterm::event::Event; use crossterm::event::Event;
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::core::TerminalCore;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient; use crate::services::auth::AuthClient;
use crate::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::auth::AuthState;
use crate::state::pages::auth::RegisterState;
use crate::state::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::functions::common::buffer;
use crate::tui::functions::common::{login, register}; use crate::tui::{
terminal::core::TerminalCore,
functions::{
common::{
form::SaveOutcome,
login,
register,
},
},
{intro, admin},
};
use crate::state::{
app::{
state::AppState,
buffer::{AppView, BufferState},
},
pages::{
auth::{AuthState, LoginState, RegisterState},
admin::AdminState,
canvas_state::CanvasState,
form::FormState,
intro::IntroState,
},
};
use crate::modes::{ use crate::modes::{
common::command_mode, common::{command_mode, commands::CommandHandler},
handlers::mode_manager::{ModeManager, AppMode},
canvas::{edit, read_only, common_mode}, canvas::{edit, read_only, common_mode},
general::{navigation, dialog}, 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::tui::functions::common::form::SaveOutcome;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventOutcome { pub enum EventOutcome {
@@ -65,18 +81,37 @@ 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,
login_state: &mut LoginState,
register_state: &mut RegisterState, register_state: &mut RegisterState,
app_state: &mut crate::state::state::AppState, intro_state: &mut IntroState,
admin_state: &mut AdminState,
buffer_state: &mut BufferState,
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);
// Determine the current view, including dynamic names
let current_view = {
let ui = &app_state.ui;
if ui.show_intro { AppView::Intro }
else if ui.show_login { AppView::Login }
else if ui.show_register { AppView::Register }
else if ui.show_admin { AppView::Admin }
else if ui.show_form {
let form_name = app_state.selected_profile.clone().unwrap_or_else(|| "Data Form".to_string());
AppView::Form(form_name)
}
else { AppView::Scratch }
};
buffer_state.update_history(current_view);
// --- DIALOG MODALITY --- // --- DIALOG MODALITY ---
if app_state.ui.dialog.dialog_show { if app_state.ui.dialog.dialog_show {
if let Some(dialog_result) = dialog::handle_dialog_event( if let Some(dialog_result) = dialog::handle_dialog_event(
&event, config, app_state, auth_state, register_state, &mut self.auth_client &event, config, app_state, auth_state, login_state, register_state, buffer_state
).await { ).await {
return dialog_result; return dialog_result;
} }
@@ -94,6 +129,33 @@ impl EventHandler {
); );
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
if UiStateHandler::toggle_buffer_list(&mut app_state.ui, config, key_code, modifiers) {
let message = format!("Buffer {}",
if app_state.ui.show_buffer_list { "shown" } else { "hidden" }
);
return Ok(EventOutcome::Ok(message));
}
// --- Buffer Switching (Check Global) ---
if !matches!(current_mode, AppMode::Edit | AppMode::Command) {
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.global, key_code, modifiers // Check global bindings
) {
match action {
"next_buffer" => {
if buffer::switch_buffer(buffer_state, true) {
return Ok(EventOutcome::Ok("Switched to next buffer".to_string()));
}
}
"previous_buffer" => {
if buffer::switch_buffer(buffer_state, false) {
return Ok(EventOutcome::Ok("Switched to previous buffer".to_string()));
}
}
_ => {} // Other global actions could be handled here if needed
}
}
}
// --- End Global UI Toggles ---
match current_mode { match current_mode {
AppMode::General => { AppMode::General => {
@@ -102,7 +164,10 @@ impl EventHandler {
config, config,
form_state, form_state,
app_state, app_state,
auth_state, login_state,
register_state,
intro_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,
@@ -112,26 +177,32 @@ 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, buffer_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 => login::back_to_main(auth_state, app_state).await, 1 => login::back_to_main(login_state, app_state, buffer_state).await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}; };
} }
UiContext::Register => { UiContext::Register => {
message = match index { message = match index {
0 => register::save(register_state, &mut self.auth_client, app_state).await?, 0 => register::save(register_state, &mut self.auth_client, app_state).await?,
1 => register::back_to_main(register_state, app_state).await, 1 => register::back_to_login(register_state, app_state, buffer_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 => {
@@ -157,20 +228,20 @@ 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 || app_state.ui.show_register{ 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 || app_state.ui.show_register{ 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 || app_state.ui.show_register{ 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();
@@ -203,6 +274,7 @@ impl EventHandler {
action, action,
form_state, form_state,
auth_state, auth_state,
login_state,
register_state, register_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
@@ -221,7 +293,7 @@ impl EventHandler {
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state, register_state,
&mut self.key_sequence_tracker, &mut self.key_sequence_tracker,
current_position, current_position,
@@ -240,7 +312,7 @@ impl EventHandler {
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
let has_changes = if app_state.ui.show_login || app_state.ui.show_register{ 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()
}; };
@@ -254,12 +326,12 @@ impl EventHandler {
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = if app_state.ui.show_login || app_state.ui.show_register{ 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 || app_state.ui.show_register{ 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()
}; };
@@ -267,8 +339,8 @@ impl EventHandler {
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 || app_state.ui.show_register{ 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();
@@ -288,6 +360,7 @@ impl EventHandler {
action, action,
form_state, form_state,
auth_state, auth_state,
login_state,
register_state, register_state,
grpc_client, grpc_client,
&mut self.auth_client, &mut self.auth_client,
@@ -305,7 +378,7 @@ impl EventHandler {
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state, register_state,
&mut self.ideal_cursor_column, &mut self.ideal_cursor_column,
&mut self.command_message, &mut self.command_message,
@@ -324,7 +397,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,

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)]

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;

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

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

View File

@@ -0,0 +1,92 @@
// src/state/app/buffer.rs
/// Represents the distinct views or "buffers" the user can navigate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppView {
Intro,
Login,
Register,
Admin,
Form(String),
Scratch,
}
impl AppView {
/// Returns the display name for the view.
pub fn display_name(&self) -> &str {
match self {
AppView::Intro => "Intro",
AppView::Login => "Login",
AppView::Register => "Register",
AppView::Admin => "Admin Panel",
AppView::Form(name) => name.as_str(),
AppView::Scratch => "*scratch*",
}
}
}
/// Holds the state related to buffer management (navigation history).
#[derive(Debug, Clone)]
pub struct BufferState {
pub history: Vec<AppView>,
pub active_index: usize,
}
impl Default for BufferState {
fn default() -> Self {
Self {
history: vec![AppView::Intro], // Start with Intro view
active_index: 0,
}
}
}
impl BufferState {
/// Updates the buffer history and active index.
/// If the view already exists, it sets it as active.
/// Otherwise, it adds the new view and makes it active.
pub fn update_history(&mut self, view: AppView) {
let existing_pos = self.history.iter().position(|v| v == &view);
match existing_pos {
Some(pos) => {
self.active_index = pos;
}
None => {
self.history.push(view.clone());
self.active_index = self.history.len() - 1;
}
}
}
/// Gets the currently active view.
pub fn get_active_view(&self) -> Option<&AppView> {
self.history.get(self.active_index)
}
/// Removes the currently active buffer from the history, unless it's the Intro buffer.
/// Sets the new active buffer to the one preceding the closed one.
/// # Returns
/// * `true` if a non-Intro buffer was closed.
/// * `false` if the active buffer was Intro or only Intro remained.
pub fn close_active_buffer(&mut self) -> bool {
let current_index = self.active_index;
// Rule 1: Cannot close Intro buffer.
if matches!(self.history.get(current_index), Some(AppView::Intro)) {
return false;
}
// Rule 2: Cannot close if only Intro would remain (or already remains).
// This check implicitly covers the case where len <= 1.
if self.history.len() <= 1 {
return false;
}
self.history.remove(current_index);
self.active_index = current_index.saturating_sub(1).min(self.history.len() - 1);
true
}
}

View File

@@ -2,7 +2,6 @@
use std::env; use std::env;
use common::proto::multieko2::table_definition::ProfileTreeResponse; use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::components::IntroState;
use crate::modes::handlers::mode_manager::AppMode; use crate::modes::handlers::mode_manager::AppMode;
use crate::ui::handlers::context::DialogPurpose; use crate::ui::handlers::context::DialogPurpose;
@@ -17,21 +16,16 @@ pub struct DialogState {
pub struct UiState { pub struct UiState {
pub show_sidebar: bool, pub show_sidebar: bool,
pub show_buffer_list: bool,
pub show_intro: bool, pub show_intro: bool,
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 show_register: bool,
pub intro_state: IntroState,
pub focus_outside_canvas: bool, pub focus_outside_canvas: bool,
pub dialog: DialogState, pub dialog: DialogState,
} }
pub struct GeneralState {
pub selected_item: usize,
pub current_option: usize,
}
pub struct AppState { pub struct AppState {
// Core editor state // Core editor state
pub current_dir: String, pub current_dir: String,
@@ -40,10 +34,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 {
@@ -58,11 +52,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,
},
}) })
} }
@@ -140,13 +131,13 @@ impl AppState {
impl Default for UiState { impl Default for UiState {
fn default() -> Self { fn default() -> Self {
Self { Self {
show_sidebar: true, show_sidebar: false,
show_intro: true, show_intro: true,
show_admin: false, show_admin: false,
show_form: false, show_form: false,
show_login: false, show_login: false,
show_register: false, show_register: false,
intro_state: IntroState::new(), show_buffer_list: true,
focus_outside_canvas: false, focus_outside_canvas: false,
dialog: DialogState::default(), dialog: DialogState::default(),
} }

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,6 @@
pub mod form; pub mod form;
pub mod auth; pub mod auth;
pub mod admin;
pub mod intro;
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,5 +1,5 @@
// 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; use lazy_static::lazy_static;
lazy_static! { lazy_static! {
@@ -11,21 +11,28 @@ lazy_static! {
]; ];
} }
/// 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,
} }
#[derive(Default, Clone)] // Add Clone derive /// Represents the state of the Registration form UI
#[derive(Default, Clone)]
pub struct RegisterState { pub struct RegisterState {
pub username: String, pub username: String,
pub email: String, pub email: String,
@@ -43,23 +50,33 @@ pub struct RegisterState {
} }
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 RegisterState { impl RegisterState {
/// Creates a new empty RegisterState
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
username: String::new(), username: String::new(),
@@ -78,7 +95,7 @@ impl RegisterState {
} }
} }
/// Updates role suggestions based on current input. /// Updates role suggestions based on current input
pub fn update_role_suggestions(&mut self) { pub fn update_role_suggestions(&mut self) {
let current_input = self.role.to_lowercase(); let current_input = self.role.to_lowercase();
self.role_suggestions = AVAILABLE_ROLES self.role_suggestions = AVAILABLE_ROLES
@@ -90,7 +107,7 @@ impl RegisterState {
} }
} }
impl CanvasState for AuthState { impl CanvasState for LoginState {
fn current_field(&self) -> usize { fn current_field(&self) -> usize {
self.current_field self.current_field
} }
@@ -124,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"),
} }
} }
@@ -133,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);
} }
@@ -147,26 +163,23 @@ 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;
} }
// --- Autocomplete Support (Not Used for AuthState) ---
fn get_suggestions(&self) -> Option<&[String]> { fn get_suggestions(&self) -> Option<&[String]> {
None // AuthState doesn't provide suggestions None
} }
fn get_selected_suggestion_index(&self) -> Option<usize> { fn get_selected_suggestion_index(&self) -> Option<usize> {
None // AuthState doesn't have selected suggestions None
} }
} }
@@ -229,12 +242,12 @@ impl CanvasState for RegisterState {
"Email (Optional)", "Email (Optional)",
"Password (Optional)", "Password (Optional)",
"Confirm Password", "Confirm Password",
"Role (Oprional)" "Role (Optional)"
] ]
} }
fn set_current_field(&mut self, index: usize) { fn set_current_field(&mut self, index: usize) {
if index < 5 { // RegisterState has 5 fields if index < 5 {
self.current_field = index; self.current_field = index;
let len = match self.current_field { let len = match self.current_field {
0 => self.username.len(), 0 => self.username.len(),
@@ -265,7 +278,6 @@ impl CanvasState for RegisterState {
} }
fn get_suggestions(&self) -> Option<&[String]> { fn get_suggestions(&self) -> Option<&[String]> {
// Only show suggestions for the role field (index 4) when requested
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions { if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
Some(&self.role_suggestions) Some(&self.role_suggestions)
} else { } else {

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,

View File

@@ -0,0 +1,25 @@
// src/state/pages/intro.rs
#[derive(Default, Clone, Debug)]
pub struct IntroState {
pub selected_option: usize,
}
impl IntroState {
pub fn new() -> Self {
Self::default()
}
pub fn next_option(&mut self) {
if self.selected_option < 3 {
self.selected_option += 1;
}
}
pub fn previous_option(&mut self) {
if self.selected_option > 0 {
self.selected_option -= 1
}
}
}

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,22 +2,25 @@
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;
use crate::state::app::buffer::{AppView, BufferState};
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::context::DialogPurpose; 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,25 +31,19 @@ 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,
@@ -66,13 +63,8 @@ pub async fn save(
vec!["OK".to_string()], vec!["OK".to_string()],
DialogPurpose::LoginFailed, 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))
} }
@@ -81,38 +73,39 @@ 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);
"Login reverted".to_string() "Login reverted".to_string()
} }
pub async fn back_to_main( pub async fn back_to_main(
auth_state: &mut AuthState, login_state: &mut LoginState,
app_state: &mut AppState, app_state: &mut AppState,
buffer_state: &mut BufferState,
) -> 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 // Ensure dialog is hidden if revert is called
app_state.hide_dialog(); // Uncomment if needed app_state.hide_dialog(); // Uncomment if needed
// Navigation logic (currently disabled in original code) // Navigation logic
app_state.ui.show_login = false; buffer_state.close_active_buffer();
app_state.ui.show_intro = true; buffer_state.update_history(AppView::Intro);
// Reset focus state // Reset focus state
app_state.ui.focus_outside_canvas = false; app_state.ui.focus_outside_canvas = false;
app_state.general.selected_item = 0; app_state.focused_button_index= 0;
"Returned to main menu".to_string() "Returned to main menu".to_string()
} }

View File

@@ -1,14 +1,13 @@
// src/tui/functions/common/register.rs // src/tui/functions/common/register.rs
use crate::{ use crate::services::auth::AuthClient;
services::auth::AuthClient, use crate::state::{
state::{ pages::auth::RegisterState,
pages::auth::RegisterState, app::state::AppState,
state::AppState, pages::canvas_state::CanvasState,
canvas_state::CanvasState,
},
ui::handlers::context::DialogPurpose,
}; };
use crate::ui::handlers::context::DialogPurpose;
use crate::state::app::buffer::{AppView, BufferState};
/// Attempts to register the user using the provided details via gRPC. /// Attempts to register the user using the provided details via gRPC.
/// Updates RegisterState and AppState on success or failure. /// Updates RegisterState and AppState on success or failure.
@@ -131,9 +130,10 @@ pub async fn revert(
} }
/// Clears the form and returns to the intro screen. /// Clears the form and returns to the intro screen.
pub async fn back_to_main( pub async fn back_to_login(
register_state: &mut RegisterState, register_state: &mut RegisterState,
app_state: &mut AppState, app_state: &mut AppState,
buffer_state: &mut BufferState,
) -> String { ) -> String {
// Clear fields first // Clear fields first
let _ = revert(register_state, app_state).await; let _ = revert(register_state, app_state).await;
@@ -142,12 +142,12 @@ pub async fn back_to_main(
app_state.hide_dialog(); app_state.hide_dialog();
// Navigation logic // Navigation logic
app_state.ui.show_register = false; buffer_state.close_active_buffer();
app_state.ui.show_intro = true; buffer_state.update_history(AppView::Login);
// Reset focus state // Reset focus state
app_state.ui.focus_outside_canvas = false; app_state.ui.focus_outside_canvas = false;
app_state.general.selected_item = 0; // Reset intro selection app_state.focused_button_index = 0;
"Returned to main menu".to_string() "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,30 +1,33 @@
use crate::state::state::AppState; // src/tui/functions/intro.rs
use crate::state::app::state::AppState;
use crate::state::app::buffer::{AppView, BufferState};
pub fn handle_intro_selection(app_state: &mut AppState, index: usize) { // Add index parameter /// Handles intro screen selection by updating view history and managing focus state.
match index { // Use index directly /// 0: Continue (restores last form or default)
0 => { // Continue /// 1: Admin view
app_state.ui.show_form = true; /// 2: Login view
app_state.ui.show_admin = false; /// 3: Register view (with focus reset)
app_state.ui.show_login = false; pub fn handle_intro_selection(
app_state: &mut AppState,
buffer_state: &mut BufferState,
index: usize,
) {
let target_view = match index {
0 => {
let form_name = app_state.selected_profile.clone().unwrap_or_else(|| "Data Form".to_string());
AppView::Form(form_name)
} }
1 => { // Admin 1 => AppView::Admin,
app_state.ui.show_form = false; 2 => AppView::Login,
app_state.ui.show_admin = true; 3 => AppView::Register,
app_state.ui.show_login = false; _ => return,
} };
2 => { // Login
app_state.ui.show_form = false; buffer_state.update_history(target_view);
app_state.ui.show_admin = false;
app_state.ui.show_login = true; // Register view requires focus reset
} if index == 3 {
3 => { // Register app_state.ui.focus_outside_canvas = false;
app_state.ui.show_intro = false; app_state.focused_button_index = 0;
app_state.ui.show_register = true;
app_state.ui.focus_outside_canvas = false;
app_state.general.selected_item = 0;
}
_ => {}
} }
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,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;
@@ -21,4 +21,18 @@ impl UiStateHandler {
false false
} }
pub fn toggle_buffer_list(
ui_state: &mut UiState,
config: &Config,
key: KeyCode,
modifiers: KeyModifiers,
) -> bool {
if let Some(action) = config.get_common_action(key, modifiers) {
if action == "toggle_buffer_list" {
ui_state.show_buffer_list = !ui_state.show_buffer_list;
return true;
}
}
false
}
} }

View File

@@ -2,11 +2,12 @@
use crate::components::{ use crate::components::{
render_background, render_background,
render_buffer_list,
render_command_line, render_command_line,
render_status_line, render_status_line,
intro::intro::render_intro,
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, register::render_register},
}; };
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
@@ -14,14 +15,22 @@ 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::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState; use crate::state::pages::auth::RegisterState;
use crate::state::state::AppState; use crate::state::pages::intro::IntroState;
use crate::state::app::buffer::BufferState;
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, register_state: &RegisterState,
intro_state: &IntroState,
admin_state: &mut AdminState,
buffer_state: &BufferState,
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
total_count: u64, total_count: u64,
@@ -30,22 +39,51 @@ pub fn render_ui(
command_input: &str, command_input: &str,
command_mode: bool, command_mode: bool,
command_message: &str, command_message: &str,
current_fps: f64,
app_state: &AppState, app_state: &AppState,
) { ) {
render_background(f, f.area(), theme); render_background(f, f.area(), theme);
// Adjust layout based on whether buffer list is shown
let constraints = if app_state.ui.show_buffer_list {
vec![
Constraint::Length(1), // Buffer list
Constraint::Min(1), // Main content
Constraint::Length(1), // Status line
Constraint::Length(1), // Command line
]
} else {
vec![
Constraint::Min(1), // Main content
Constraint::Length(1), // Status line (no buffer list)
Constraint::Length(1), // Command line
]
};
let root = Layout::default() let root = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([ .constraints(constraints)
Constraint::Min(1),
Constraint::Length(1),
Constraint::Length(1),
])
.split(f.area()); .split(f.area());
let main_content_area = root[0]; let mut buffer_list_area = None;
let main_content_area;
let status_line_area;
let command_line_area;
// Assign areas based on layout
if app_state.ui.show_buffer_list {
buffer_list_area = Some(root[0]);
main_content_area = root[1];
status_line_area = root[2];
command_line_area = root[3];
} else {
main_content_area = root[0];
status_line_area = root[1];
command_line_area = root[2];
}
if app_state.ui.show_intro { if app_state.ui.show_intro {
app_state.ui.intro_state.render(f, main_content_area, theme); render_intro(f, intro_state, main_content_area, theme);
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
render_register( render_register(
f, f,
@@ -55,35 +93,20 @@ pub fn render_ui(
app_state, app_state,
register_state.current_field < 4 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, 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,
auth_state,
admin_state,
main_content_area, main_content_area,
theme, theme,
&app_state.profile_tree, &app_state.profile_tree,
@@ -145,10 +168,14 @@ pub fn render_ui(
total_count, total_count,
current_position, current_position,
); );
} else{
} }
render_status_line(f, root[1], current_dir, theme, is_edit_mode); // Render buffer list if enabled and area is available
render_command_line(f, root[2], command_input, command_mode, theme, command_message); if let Some(area) = buffer_list_area {
if app_state.ui.show_buffer_list {
render_buffer_list(f, area, theme, buffer_state);
}
}
render_status_line(f, status_line_area, current_dir, theme, is_edit_mode, current_fps);
render_command_line(f, command_line_area, command_input, command_mode, theme, command_message);
} }

View File

@@ -2,60 +2,93 @@
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use crate::modes::common::commands::CommandHandler;
use crate::modes::handlers::event::{EventHandler, EventOutcome}; // Import EventOutcome
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::modes::common::commands::CommandHandler;
use crate::state::pages::auth::AuthState; use crate::modes::handlers::event::{EventHandler, EventOutcome};
use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
use crate::state::pages::canvas_state::CanvasState;
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::pages::auth::RegisterState; use crate::state::pages::auth::RegisterState;
use crate::state::state::AppState; use crate::state::pages::admin::AdminState;
use crate::state::pages::intro::IntroState;
use crate::state::app::buffer::BufferState;
use crate::state::app::buffer::AppView;
use crate::state::app::state::AppState;
// Import SaveOutcome // 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 std::time::Instant;
use crossterm::cursor::SetCursorStyle; use crossterm::cursor::SetCursorStyle;
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> { pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?; let config = Config::load()?;
let theme = Theme::from_str(&config.colors.theme);
let mut terminal = TerminalCore::new()?; let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?; let mut grpc_client = GrpcClient::new().await?;
let mut command_handler = CommandHandler::new(); let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme);
let mut auth_state = AuthState::default();
let mut register_state = RegisterState::default();
// Initialize app_state first let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new();
let mut auth_state = AuthState::default();
let mut login_state = LoginState::default();
let mut register_state = RegisterState::default();
let mut intro_state = IntroState::default();
let mut admin_state = AdminState::default();
let mut buffer_state = BufferState::default();
let mut app_state = AppState::new()?; let mut app_state = AppState::new()?;
// Initialize app state with profile tree and table structure // Initialize app state with profile tree and table structure
let column_names = let column_names =
UiService::initialize_app_state(&mut grpc_client, &mut app_state) UiService::initialize_app_state(&mut grpc_client, &mut app_state)
.await?; .await?;
// Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names); let mut form_state = FormState::new(column_names);
// Initialize EventHandler (which now contains AuthClient)
let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new();
// Fetch the total count of Adresar entries // Fetch the total count of Adresar entries
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state) UiService::initialize_adresar_count(&mut grpc_client, &mut app_state)
.await?; .await?;
form_state.reset_to_empty(); form_state.reset_to_empty();
// --- FPS Calculation State ---
let mut last_frame_time = Instant::now();
let mut current_fps = 0.0;
loop { loop {
// Determine edit mode based on EventHandler state // Determine edit mode based on EventHandler state
let is_edit_mode = event_handler.is_edit_mode; let is_edit_mode = event_handler.is_edit_mode;
// --- Synchronize UI View from Active Buffer ---
if let Some(active_view) = buffer_state.get_active_view() {
// Reset all flags first
app_state.ui.show_intro = false;
app_state.ui.show_login = false;
app_state.ui.show_register = false;
app_state.ui.show_admin = false;
app_state.ui.show_form = false;
match active_view {
AppView::Intro => app_state.ui.show_intro = true,
AppView::Login => app_state.ui.show_login = true,
AppView::Register => app_state.ui.show_register = true,
AppView::Admin => app_state.ui.show_admin = true,
AppView::Form(_) => app_state.ui.show_form = true,
AppView::Scratch => {} // Or show a scratchpad component
}
}
// --- End Synchronization ---
terminal.draw(|f| { terminal.draw(|f| {
render_ui( render_ui(
f, f,
&mut form_state, &mut form_state,
&mut auth_state, &mut auth_state,
&login_state,
&register_state, &register_state,
&intro_state,
&mut admin_state,
&buffer_state,
&theme, &theme,
is_edit_mode, is_edit_mode,
app_state.total_count, app_state.total_count,
@@ -64,6 +97,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
&event_handler.command_input, &event_handler.command_input,
event_handler.command_mode, event_handler.command_mode,
&event_handler.command_message, &event_handler.command_message,
current_fps,
&app_state, &app_state,
); );
})?; })?;
@@ -108,14 +142,18 @@ 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 register_state,
&mut intro_state,
&mut admin_state,
&mut buffer_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;
@@ -255,14 +293,13 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
} }
} else if app_state.ui.show_login { } else if app_state.ui.show_login {
if !event_handler.is_edit_mode { if !event_handler.is_edit_mode {
let current_input = auth_state.get_current_input(); let current_input = login_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 = login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
event_handler.ideal_cursor_column.min(max_cursor_pos);
} }
} }
@@ -271,6 +308,14 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// terminal.cleanup()?; // Optional: Drop handles this // terminal.cleanup()?; // Optional: Drop handles this
return Ok(()); return Ok(());
} }
// --- FPS Calculation ---
let now = Instant::now();
let frame_duration = now.duration_since(last_frame_time);
last_frame_time = now;
if frame_duration.as_secs_f64() > 1e-6 {
current_fps = 1.0 / frame_duration.as_secs_f64();
}
} }
} }

View File

@@ -35,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

@@ -52,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

@@ -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

@@ -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)