Compare commits

...

86 Commits

Author SHA1 Message Date
filipriec
75af0c3be1 the profile name is now passed from admin panel to the add table page 2025-04-17 21:59:19 +02:00
filipriec
6f36b84f85 delete selected button now in the add table page working 2025-04-17 21:21:37 +02:00
filipriec
e723198b72 best ever, working as intended 2025-04-17 21:07:07 +02:00
filipriec
8f74febff1 combined, full width need a table name that is missing now 2025-04-17 20:41:48 +02:00
filipriec
d9bd6f8e1d working, but full width is not working, lets combine it with the full width now 2025-04-17 20:17:21 +02:00
filipriec
bf55417901 professional layout working 2025-04-17 19:50:48 +02:00
filipriec
9511970a1a removed placeholder 2025-04-17 19:12:28 +02:00
filipriec
5c8557b369 adding stuff to the column 2025-04-17 19:06:54 +02:00
filipriec
5e47c53fcf canvas required fields 2025-04-17 18:28:06 +02:00
filipriec
f7493a8bc4 canvas properly updating table name 2025-04-17 18:17:01 +02:00
filipriec
4f39b93edd logic of the add button, needs redesign 2025-04-17 16:48:03 +02:00
filipriec
ff8b4eb0f6 canvas now working properly well 2025-04-17 15:40:07 +02:00
filipriec
e921862a7f compiled, still not working for canvas 2025-04-17 14:41:09 +02:00
filipriec
4d7177f15a mistake fixed 2025-04-17 14:21:39 +02:00
filipriec
c5d7f56399 readonly and edit functionality to add table 2025-04-17 14:14:36 +02:00
filipriec
57f789290d needs improvements but at least it looks like it exists 2025-04-17 11:53:31 +02:00
filipriec
f34317e504 from template to the working page 2025-04-17 11:11:33 +02:00
filipriec
8159a84447 movement 2025-04-16 23:31:28 +02:00
filipriec
f4db0e384c add table page1 2025-04-16 22:23:30 +02:00
filipriec
69953401b1 NEW PAGE ADD TABLE 2025-04-16 22:07:07 +02:00
filipriec
93a3c246c6 buttons are now added in the admin panel 2025-04-16 21:43:21 +02:00
filipriec
6505e18b0b working admin panel, needs to do buttons for navigation next 2025-04-16 21:22:34 +02:00
filipriec
51ab73014f removing debug statement 2025-04-16 19:19:15 +02:00
filipriec
05d9e6e46b working selection in the admin panel for the admin perfectly well 2025-04-16 19:15:05 +02:00
filipriec
8ea9965ee3 temp debug 2025-04-16 19:10:02 +02:00
filipriec
486df65aa3 better admin panel, main problem not fixed, needs fix now 2025-04-16 18:53:09 +02:00
filipriec
8044696d7c needed fix done 2025-04-16 18:33:00 +02:00
filipriec
04a7d86636 better movement 2025-04-16 16:30:11 +02:00
filipriec
d0e2f31ce8 admin panel improvements 2025-04-16 14:11:52 +02:00
filipriec
50fcb09758 admin panel admin width fixed 2025-04-16 13:58:34 +02:00
filipriec
6d3c09d57a CRUCIAL bug fixed in the admin panel non admin user 2025-04-16 13:43:44 +02:00
filipriec
cc994fb940 admin panel for admin 2025-04-16 13:21:59 +02:00
filipriec
eee12513dd admin panel from scratch 2025-04-16 12:56:57 +02:00
filipriec
055b6a0a43 admin panel bombarded like never before 2025-04-16 12:47:33 +02:00
filipriec
26b899df16 fixed highlight logic 2025-04-16 09:48:39 +02:00
filipriec
afc8e1a1e5 highlight mode to full line highlightmode 2025-04-16 09:08:40 +02:00
filipriec
b6c4d3308d its now using enum fully for the highlight mode 2025-04-16 00:11:41 +02:00
filipriec
af4567aa3d highlight is now working properly well, can keep on going 2025-04-15 23:46:57 +02:00
filipriec
415bc2044d highlight through many lines working 2025-04-15 23:07:55 +02:00
filipriec
91ad2b0caf FIXED CRUCIAL BUG of two same shortcuts defined in the config 2025-04-15 22:28:12 +02:00
filipriec
bc6471fa54 misname fixed, highlight kinda working 2025-04-15 21:38:32 +02:00
filipriec
0704668d8d mistakes in config.toml fixed, needs more fixes before the real implementation 2025-04-15 21:22:13 +02:00
filipriec
2e9f8815d2 HIGHLIGHT MODE 2025-04-15 21:17:04 +02:00
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
76 changed files with 3968 additions and 839 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
@@ -45,9 +49,18 @@ move_line_start = ["0"]
move_line_end = ["$"] move_line_end = ["$"]
move_first_line = ["gg"] move_first_line = ["gg"]
move_last_line = ["x"] move_last_line = ["x"]
enter_highlight_mode = ["v"]
enter_highlight_mode_linewise = ["ctrl+v"]
[keybindings.highlight]
exit_highlight_mode = ["esc"]
enter_highlight_mode_linewise = ["ctrl+v"]
[keybindings.edit] [keybindings.edit]
exit_edit_mode = ["esc","ctrl+e"] # BIG CHANGES NOW EXIT HANDLES EITHER IF THOSE
# exit_edit_mode = ["esc","ctrl+e"]
# exit_suggestion_mode = ["esc"]
exit = ["esc", "ctrl+e"]
delete_char_forward = ["delete"] delete_char_forward = ["delete"]
delete_char_backward = ["backspace"] delete_char_backward = ["backspace"]
next_field = ["enter"] next_field = ["enter"]
@@ -57,7 +70,6 @@ move_right = ["right"]
suggestion_down = ["ctrl+n", "tab"] suggestion_down = ["ctrl+n", "tab"]
suggestion_up = ["ctrl+p", "shift+tab"] suggestion_up = ["ctrl+p", "shift+tab"]
select_suggestion = ["enter"] select_suggestion = ["enter"]
exit_suggestion_mode = ["esc"]
[keybindings.command] [keybindings.command]
exit_command_mode = ["ctrl+g", "esc"] exit_command_mode = ["ctrl+g", "esc"]

View File

@@ -1,4 +1,8 @@
// src/components/admin.rs // src/components/admin.rs
pub mod admin_panel; pub mod admin_panel;
pub mod admin_panel_admin;
pub mod add_table;
pub use admin_panel::*; pub use admin_panel::*;
pub use admin_panel_admin::*;
pub use add_table::*;

View File

@@ -0,0 +1,440 @@
// src/components/admin/add_table.rs
use crate::config::colors::themes::Theme;
use crate::state::app::highlight::HighlightState;
use crate::state::app::state::AppState;
use crate::state::pages::add_table::{AddTableFocus, AddTableState};
use crate::state::pages::canvas_state::CanvasState;
// use crate::state::pages::add_table::{ColumnDefinition, LinkDefinition}; // Not directly used here
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table},
Frame,
};
use crate::components::handlers::canvas::render_canvas;
/// Renders the Add New Table page layout, structuring the display of table information,
/// input fields, and action buttons. Adapts layout based on terminal width.
pub fn render_add_table(
f: &mut Frame,
area: Rect,
theme: &Theme,
_app_state: &AppState, // Currently unused, might be needed later
add_table_state: &mut AddTableState,
is_edit_mode: bool, // Determines if canvas inputs are in edit mode
highlight_state: &HighlightState, // For text highlighting in canvas
) {
// --- Configuration ---
// Threshold width to switch between wide and narrow layouts
const NARROW_LAYOUT_THRESHOLD: u16 = 120; // Adjust this value as needed
// --- State Checks ---
let focus_on_canvas_inputs = matches!(
add_table_state.current_focus,
AddTableFocus::InputTableName
| AddTableFocus::InputColumnName
| AddTableFocus::InputColumnType
);
// --- Main Page Block ---
let main_block = Block::default()
.title(" Add New Table ")
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.border))
.style(Style::default().bg(theme.bg));
let inner_area = main_block.inner(area);
f.render_widget(main_block, area);
// --- Area Variable Declarations ---
let top_info_area: Rect;
let columns_area: Rect;
let canvas_area: Rect;
let add_button_area: Rect;
let indexes_area: Rect;
let links_area: Rect;
let bottom_buttons_area: Rect;
// --- Layout Decision ---
if area.width >= NARROW_LAYOUT_THRESHOLD {
// --- WIDE Layout (Based on first screenshot) ---
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Top Info (Profile/Table Name) - Increased to 3 lines
Constraint::Min(10), // Middle Area (Columns | Right Pane)
Constraint::Length(3), // Bottom Buttons
])
.split(inner_area);
top_info_area = main_chunks[0];
let middle_area = main_chunks[1];
bottom_buttons_area = main_chunks[2];
// Split Middle Horizontally
let middle_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(60), // Left: Columns Table
Constraint::Percentage(40), // Right: Inputs etc.
])
.split(middle_area);
columns_area = middle_chunks[0];
let right_pane_area = middle_chunks[1];
// Split Right Pane Vertically
let right_pane_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(5), // Input Canvas Area
Constraint::Length(3), // Add Button Area
Constraint::Min(5), // Indexes & Links Area
])
.split(right_pane_area);
canvas_area = right_pane_chunks[0];
add_button_area = right_pane_chunks[1];
let indexes_links_area = right_pane_chunks[2];
// Split Indexes/Links Horizontally
let indexes_links_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50), // Indexes Table
Constraint::Percentage(50), // Links Table
])
.split(indexes_links_area);
indexes_area = indexes_links_chunks[0];
links_area = indexes_links_chunks[1];
// --- Top Info Rendering (Wide - 2 lines) ---
let profile_text = Paragraph::new(vec![
Line::from(Span::styled(
format!("Profile: {}", add_table_state.profile_name),
theme.fg,
)),
Line::from(Span::styled(
format!("Table name: {}", add_table_state.table_name),
theme.fg,
)),
])
.block(
Block::default()
.borders(Borders::BOTTOM)
.border_style(Style::default().fg(theme.secondary)),
);
f.render_widget(profile_text, top_info_area);
} else {
// --- NARROW Layout (Based on second screenshot) ---
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // Top: Profile & Table Name (Single Row)
Constraint::Length(5), // Column Definition Input Canvas Area
Constraint::Length(3), // Add Button Area
Constraint::Min(5), // Columns Table Area
Constraint::Min(5), // Indexes & Links Area
Constraint::Length(3), // Bottom: Save/Cancel Buttons
])
.split(inner_area);
top_info_area = main_chunks[0];
canvas_area = main_chunks[1];
add_button_area = main_chunks[2];
columns_area = main_chunks[3];
let indexes_links_area = main_chunks[4];
bottom_buttons_area = main_chunks[5];
// Split Indexes/Links Horizontally
let indexes_links_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50), // Indexes Table
Constraint::Percentage(50), // Links Table
])
.split(indexes_links_area);
indexes_area = indexes_links_chunks[0];
links_area = indexes_links_chunks[1];
// --- Top Info Rendering (Narrow - 1 line) ---
let top_info_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50),
Constraint::Percentage(50),
])
.split(top_info_area);
let profile_text = Paragraph::new(Span::styled(
format!("Profile: {}", add_table_state.profile_name),
theme.fg,
))
.alignment(Alignment::Left);
f.render_widget(profile_text, top_info_chunks[0]);
let table_name_text = Paragraph::new(Span::styled(
format!("Table: {}", add_table_state.table_name),
theme.fg,
))
.alignment(Alignment::Left);
f.render_widget(table_name_text, top_info_chunks[1]);
}
// --- Common Widget Rendering (Uses calculated areas) ---
// --- Columns Table Rendering ---
let columns_focused =
add_table_state.current_focus == AddTableFocus::ColumnsTable;
let columns_border_style = if columns_focused {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.secondary)
};
let column_rows: Vec<Row<'_>> = add_table_state
.columns
.iter()
.map(|col_def| {
Row::new(vec![
Cell::from(col_def.name.clone()),
Cell::from(col_def.data_type.clone()),
])
.style(Style::default().fg(theme.fg))
})
.collect();
// Use different headers/constraints based on layout? For now, keep consistent.
let header_cells = ["Name", "Type"]
.iter()
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
let header = Row::new(header_cells).height(1).bottom_margin(1);
let columns_table = Table::new(
column_rows,
[Constraint::Percentage(60), Constraint::Percentage(40)],
)
.header(header)
.block(
Block::default()
.title(Span::styled(" Columns ", theme.fg))
.title_alignment(Alignment::Center)
.borders(Borders::ALL) // Use ALL borders for consistency
.border_type(BorderType::Rounded)
.border_style(columns_border_style),
)
.row_highlight_style(
Style::default()
.add_modifier(Modifier::REVERSED)
.fg(theme.highlight),
)
.highlight_symbol(" > ");
f.render_stateful_widget(
columns_table,
columns_area,
&mut add_table_state.column_table_state,
);
// --- Canvas Rendering (Column Definition Input) ---
let _active_field_rect = render_canvas(
f,
canvas_area,
add_table_state,
&add_table_state.fields(),
&add_table_state.current_field(),
&add_table_state.inputs(),
theme,
is_edit_mode && focus_on_canvas_inputs,
highlight_state,
);
// --- Button Style Helpers ---
let get_button_style = |button_focus: AddTableFocus, current_focus| {
let is_focused = current_focus == button_focus;
let base_style = Style::default().fg(if is_focused {
theme.bg // Reversed text color
} else {
theme.secondary // Normal text color
});
if is_focused {
base_style
.add_modifier(Modifier::BOLD)
.bg(theme.highlight) // Reversed background
} else {
base_style
}
};
let get_button_border_style = |button_focus: AddTableFocus, current_focus| {
if current_focus == button_focus {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.secondary)
}
};
// --- Add Button Rendering ---
let add_button = Paragraph::new(" Add ")
.style(get_button_style(
AddTableFocus::AddColumnButton,
add_table_state.current_focus,
))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(get_button_border_style(
AddTableFocus::AddColumnButton,
add_table_state.current_focus,
)),
);
f.render_widget(add_button, add_button_area); // Render into the calculated area
// --- Indexes Table Rendering ---
let indexes_focused =
add_table_state.current_focus == AddTableFocus::IndexesTable;
let indexes_border_style = if indexes_focused {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.secondary)
};
let index_rows: Vec<Row<'_>> = add_table_state
.indexes
.iter()
.map(|index_name| {
Row::new(vec![Cell::from(index_name.clone())])
.style(Style::default().fg(theme.fg))
})
.collect();
let index_header_cells = ["Column Name"]
.iter()
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
let index_header = Row::new(index_header_cells).height(1).bottom_margin(1);
let indexes_table =
Table::new(index_rows, [Constraint::Percentage(100)])
.header(index_header)
.block(
Block::default()
.title(Span::styled(" Indexes ", theme.fg))
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(indexes_border_style),
)
.row_highlight_style(
Style::default()
.add_modifier(Modifier::REVERSED)
.fg(theme.highlight),
)
.highlight_symbol(" > ");
f.render_stateful_widget(
indexes_table,
indexes_area,
&mut add_table_state.index_table_state,
);
// --- Links Table Rendering ---
let links_focused = add_table_state.current_focus == AddTableFocus::LinksTable;
let links_border_style = if links_focused {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.secondary)
};
let link_rows: Vec<Row<'_>> = add_table_state
.links
.iter()
.map(|link_def| {
Row::new(vec![
Cell::from(link_def.linked_table_name.clone()),
Cell::from(if link_def.is_required { "[X]" } else { "[ ]" }),
])
.style(Style::default().fg(theme.fg))
})
.collect();
let link_header_cells = ["Linked Table", "Req"]
.iter()
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
let link_header = Row::new(link_header_cells).height(1).bottom_margin(1);
let links_table =
Table::new(link_rows, [Constraint::Percentage(80), Constraint::Min(5)])
.header(link_header)
.block(
Block::default()
.title(Span::styled(" Links ", theme.fg))
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(links_border_style),
)
.row_highlight_style(
Style::default()
.add_modifier(Modifier::REVERSED)
.fg(theme.highlight),
)
.highlight_symbol(" > ");
f.render_stateful_widget(
links_table,
links_area,
&mut add_table_state.link_table_state,
);
// --- Save/Cancel Buttons Rendering ---
let bottom_button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(33), // Save Button
Constraint::Percentage(34), // Delete Button
Constraint::Percentage(33), // Cancel Button
])
.split(bottom_buttons_area);
let save_button = Paragraph::new(" Save table ")
.style(get_button_style(
AddTableFocus::SaveButton,
add_table_state.current_focus,
))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(get_button_border_style(
AddTableFocus::SaveButton,
add_table_state.current_focus,
)),
);
f.render_widget(save_button, bottom_button_chunks[0]);
let delete_button = Paragraph::new(" Delete Selected ")
.style(get_button_style(
AddTableFocus::DeleteSelectedButton,
add_table_state.current_focus,
))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(get_button_border_style(
AddTableFocus::DeleteSelectedButton,
add_table_state.current_focus,
)),
);
f.render_widget(delete_button, bottom_button_chunks[1]);
let cancel_button = Paragraph::new(" Cancel ")
.style(get_button_style(
AddTableFocus::CancelButton,
add_table_state.current_focus,
))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(get_button_border_style(
AddTableFocus::CancelButton,
add_table_state.current_focus,
)),
);
f.render_widget(cancel_button, bottom_button_chunks[2]);
}

View File

@@ -1,118 +1,131 @@
// 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::app::state::AppState;
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 super::admin_panel_admin::render_admin_panel_admin;
use crate::config::colors::themes::Theme;
pub struct AdminPanelState { pub fn render_admin_panel(
pub list_state: ListState, f: &mut Frame,
pub profiles: Vec<String>, app_state: &AppState,
auth_state: &AuthState,
admin_state: &mut AdminState,
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);
// 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,
chunks[1],
app_state,
admin_state,
theme,
);
}
} }
impl AdminPanelState { /// Renders the view for non-admin users (profile list and details).
pub fn new(profiles: Vec<String>) -> Self { fn render_admin_panel_non_admin(
let mut list_state = ListState::default(); f: &mut Frame,
if !profiles.is_empty() { admin_state: &AdminState,
list_state.select(Some(0)); content_chunks: &[Rect],
} theme: &Theme,
Self { list_state, profiles } profile_tree: &ProfileTreeResponse,
} selected_profile: &Option<String>,
) {
pub fn next(&mut self) { // Profile list - Use data from admin_state
let i = self.list_state.selected().map_or(0, |i| let items: Vec<ListItem> = admin_state
if i >= self.profiles.len() - 1 { 0 } else { i + 1 }); .profiles
self.list_state.select(Some(i)); .iter()
} .map(|p| {
ListItem::new(Line::from(vec![
pub fn previous(&mut self) {
let i = self.list_state.selected().map_or(0, |i|
if i == 0 { self.profiles.len() - 1 } else { i - 1 });
self.list_state.select(Some(i));
}
pub fn render(
&mut self,
f: &mut Frame,
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);
// Profile details let mut profile_list_state_clone = admin_state.profile_list_state.clone();
if let Some(profile) = self.list_state.selected() f.render_stateful_widget(list, content_chunks[0], &mut profile_list_state_clone);
.and_then(|i| profile_tree.profiles.get(i))
{
let mut text = Text::default();
text.lines.push(Line::from(vec![
Span::styled("Profile: ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]));
text.lines.push(Line::from("")); // Profile details - Use selection info from admin_state
text.lines.push(Line::from(Span::styled("Tables:", Style::default().fg(theme.accent)))); if let Some(profile) = admin_state
.get_selected_index()
for table in &profile.tables { .and_then(|i| profile_tree.profiles.get(i))
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)]; {
if !table.depends_on.is_empty() { let mut text = Text::default();
line.push(Span::styled( text.lines.push(Line::from(vec![
format!("{}", table.depends_on.join(", ")), Span::styled("Profile: ", Style::default().fg(theme.accent)),
Style::default().fg(theme.secondary) Span::styled(&profile.name, Style::default().fg(theme.highlight)),
)); ]));
}
text.lines.push(Line::from(line)); text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
"Tables:",
Style::default().fg(theme.accent),
)));
for table in &profile.tables {
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
if !table.depends_on.is_empty() {
line.push(Span::styled(
format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary),
));
} }
text.lines.push(Line::from(line));
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"));
f.render_widget(details_widget, content_chunks[1]);
} }
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"))
.wrap(Wrap { trim: true });
f.render_widget(details_widget, content_chunks[1]);
} }
} }

View File

@@ -0,0 +1,243 @@
// src/components/admin/admin_panel_admin.rs
use crate::config::colors::themes::Theme;
use crate::state::pages::admin::{AdminFocus, AdminState};
use crate::state::app::state::AppState;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::Style,
text::{Line, Span, Text}, // Added Text
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
Frame,
};
/// Renders the view specific to admin users with a three-pane layout.
pub fn render_admin_panel_admin(
f: &mut Frame,
area: Rect,
app_state: &AppState,
admin_state: &mut AdminState,
theme: &Theme,
) {
// Split vertically: Top for panes, Bottom for buttons
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(0), Constraint::Length(1)].as_ref()) // 1 line for buttons
.split(area);
let panes_area = main_chunks[0];
let buttons_area = main_chunks[1];
// Split the top area into three panes: Profiles | Tables | Dependencies
let pane_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25), // Profiles
Constraint::Percentage(40), // Tables
Constraint::Percentage(35), // Dependencies
].as_ref())
.split(panes_area); // Use the whole area directly
let profiles_pane = pane_chunks[0];
let tables_pane = pane_chunks[1];
let deps_pane = pane_chunks[2];
// --- Profiles Pane (Left) ---
let profile_focus = admin_state.current_focus == AdminFocus::Profiles;
let profile_border_style = if profile_focus {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.border)
};
// Block for the profiles pane
let profiles_block = Block::default()
.title(" Profiles ")
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(profile_border_style);
let profiles_inner_area = profiles_block.inner(profiles_pane); // Get inner area for list
f.render_widget(profiles_block, profiles_pane); // Render the block itself
// Create profile list items
let profile_list_items: Vec<ListItem> = app_state
.profile_tree
.profiles
.iter()
.enumerate()
.map(|(idx, profile)| {
// Check persistent selection for prefix, navigation state for style/highlight
let is_selected = admin_state.selected_profile_index == Some(idx); // Use persistent state for [*]
let is_navigated = admin_state.profile_list_state.selected() == Some(idx); // Use nav state for highlight/>
let prefix = if is_selected { "[*] " } else { "[ ] " };
let style = if is_selected { // Style based on selection too
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
} else {
Style::default().fg(theme.fg)
};
ListItem::new(Line::from(vec![
Span::styled(prefix, style),
Span::styled(&profile.name, style)
]))
})
.collect();
// Build and render profile list inside the block's inner area
let profile_list = List::new(profile_list_items)
// Highlight style depends on focus AND navigation state
.highlight_style(if profile_focus { // Use focus state
Style::default().add_modifier(ratatui::style::Modifier::REVERSED)
} else {
Style::default()
})
.highlight_symbol(if profile_focus { "> " } else { " " });
f.render_stateful_widget(profile_list, profiles_inner_area, &mut admin_state.profile_list_state);
// --- Tables Pane (Middle) ---
let table_focus = admin_state.current_focus == AdminFocus::Tables;
let table_border_style = if table_focus {
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.border)
};
// Get selected profile information
let navigated_profile_idx = admin_state.profile_list_state.selected(); // Use nav state for display
let selected_profile_name = app_state
.profile_tree
.profiles
.get(navigated_profile_idx.unwrap_or(usize::MAX)) // Use nav state for title
.map_or("None", |p| &p.name);
// Block for the tables pane
let tables_block = Block::default()
.title(format!(" Tables (Profile: {}) ", selected_profile_name))
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(table_border_style);
let tables_inner_area = tables_block.inner(tables_pane); // Get inner area for list
f.render_widget(tables_block, tables_pane); // Render the block itself
// Create table list items and get dependencies for the selected table
let (table_list_items, selected_table_deps): (Vec<ListItem>, Vec<String>) = if let Some(
profile, // Get profile based on NAVIGATED profile index
) = navigated_profile_idx.and_then(|idx| app_state.profile_tree.profiles.get(idx)) {
let items: Vec<ListItem> = profile
.tables
.iter()
.enumerate()
.map(|(idx, table)| { // Renamed i to idx for clarity
// Check persistent selection for prefix, navigation state for style/highlight
let is_selected = admin_state.selected_table_index == Some(idx); // Use persistent state for [*]
let is_navigated = admin_state.table_list_state.selected() == Some(idx); // Use nav state for highlight/>
let prefix = if is_selected { "[*] " } else { "[ ] " };
let style = if is_navigated { // Style based on navigation highlight
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
} else {
Style::default().fg(theme.fg)
};
ListItem::new(Line::from(vec![
Span::styled(prefix, style),
Span::styled(&table.name, style),
]))
})
.collect();
// Get dependencies only for the PERSISTENTLY selected table in the PERSISTENTLY selected profile
let chosen_profile_idx = admin_state.selected_profile_index; // Use persistent profile selection
let deps = chosen_profile_idx // Start with the chosen profile index
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx)) // Get the chosen profile
.and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx))) // Get the chosen table using its index
.map_or(Vec::new(), |t| t.depends_on.clone()); // If found, clone its depends_on, otherwise return empty Vec
(items, deps)
} else {
// Default when no profile is selected
(vec![ListItem::new("Select a profile to see tables")], vec![])
};
// Build and render table list inside the block's inner area
let table_list = List::new(table_list_items)
// Highlight style depends on focus AND navigation state
.highlight_style(if table_focus { // Use focus state
Style::default().add_modifier(ratatui::style::Modifier::REVERSED)
} else {
Style::default()
})
.highlight_symbol(if table_focus { "> " } else { " " }); // Focus indicator
f.render_stateful_widget(table_list, tables_inner_area, &mut admin_state.table_list_state);
// --- Dependencies Pane (Right) ---
// Get name based on PERSISTENT selections
let chosen_profile_idx = admin_state.selected_profile_index; // Use persistent profile selection
let selected_table_name = chosen_profile_idx
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx))
.and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx))) // Use persistent table selection
.map_or("N/A", |t| &t.name); // Get name of the selected table
// Block for the dependencies pane
let deps_block = Block::default()
.title(format!(" Dependencies (Table: {}) ", selected_table_name))
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.border)); // No focus highlight for deps pane
let deps_inner_area = deps_block.inner(deps_pane); // Get inner area for content
f.render_widget(deps_block, deps_pane); // Render the block itself
// Prepare content for the dependencies paragraph
let mut deps_content = Text::default();
deps_content.lines.push(Line::from(Span::styled(
"Depends On:",
Style::default().fg(theme.accent), // Use accent color for the label
)));
if !selected_table_deps.is_empty() {
for dep in selected_table_deps {
// List each dependency
deps_content.lines.push(Line::from(Span::styled(format!("- {}", dep), theme.fg)));
}
} else {
// Indicate if there are no dependencies
deps_content.lines.push(Line::from(Span::styled(" None", theme.secondary)));
}
// Build and render dependencies paragraph inside the block's inner area
let deps_paragraph = Paragraph::new(deps_content);
f.render_widget(deps_paragraph, deps_inner_area);
// --- Buttons Row ---
let button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(33),
Constraint::Percentage(34),
Constraint::Percentage(33),
].as_ref())
.split(buttons_area);
let btn_base_style = Style::default().fg(theme.secondary);
// Define the helper closure to get style based on focus
let get_btn_style = |button_focus: AdminFocus| {
if admin_state.current_focus == button_focus {
// Apply highlight style if this button is focused
btn_base_style.add_modifier(ratatui::style::Modifier::REVERSED)
} else {
btn_base_style // Use base style otherwise
}
};
let btn1 = Paragraph::new("Add Logic")
.style(get_btn_style(AdminFocus::Button1))
.alignment(Alignment::Center);
let btn2 = Paragraph::new("Add Table")
.style(get_btn_style(AdminFocus::Button2))
.alignment(Alignment::Center);
let btn3 = Paragraph::new("Change Table")
.style(get_btn_style(AdminFocus::Button3))
.alignment(Alignment::Center);
f.render_widget(btn1, button_chunks[0]);
f.render_widget(btn2, button_chunks[1]);
f.render_widget(btn3, button_chunks[2]);
}

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},
@@ -12,14 +12,16 @@ use ratatui::{
widgets::{Block, BorderType, Borders, Paragraph}, widgets::{Block, BorderType, Borders, Paragraph},
Frame, Frame,
}; };
use crate::state::app::highlight::HighlightState;
pub fn render_login( 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,
highlight_state: &HighlightState,
) { ) {
// Main container // Main container
let block = Block::default() let block = Block::default()
@@ -50,16 +52,17 @@ 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,
highlight_state,
); );
// --- 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 +80,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 +107,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,16 +4,17 @@ 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,
}; };
use crate::state::app::highlight::HighlightState;
pub fn render_register( pub fn render_register(
f: &mut Frame, f: &mut Frame,
@@ -22,6 +23,7 @@ pub fn render_register(
state: &RegisterState, // Use RegisterState state: &RegisterState, // Use RegisterState
app_state: &AppState, app_state: &AppState,
is_edit_mode: bool, is_edit_mode: bool,
highlight_state: &HighlightState,
) { ) {
let block = Block::default() let block = Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
@@ -42,6 +44,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 +57,32 @@ 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 highlight_state,
); );
// --- 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 +90,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 +122,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

@@ -81,10 +81,10 @@ pub fn render_autocomplete_dropdown(
let list = List::new(items); let list = List::new(items);
// State for managing selection highlight (still needed for logic) // State for managing selection highlight (still needed for logic)
let mut list_state = ListState::default(); let mut profile_list_state = ListState::default();
list_state.select(selected_index); profile_list_state.select(selected_index);
// Render the list statefully *over* the background block // Render the list statefully *over* the background block
f.render_stateful_widget(list, dropdown_area, &mut list_state); f.render_stateful_widget(list, dropdown_area, &mut profile_list_state);
} }

View File

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

View File

@@ -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,8 @@ 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::state::app::highlight::HighlightState;
use crate::components::handlers::canvas::render_canvas; use crate::components::handlers::canvas::render_canvas;
pub fn render_form( pub fn render_form(
@@ -18,6 +19,7 @@ pub fn render_form(
inputs: &[&String], inputs: &[&String],
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
highlight_state: &HighlightState,
total_count: u64, total_count: u64,
current_position: u64, current_position: u64,
) { ) {
@@ -62,5 +64,6 @@ pub fn render_form(
inputs, inputs,
theme, theme,
is_edit_mode, is_edit_mode,
highlight_state,
); );
} }

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

@@ -2,33 +2,33 @@
use ratatui::{ use ratatui::{
widgets::{Paragraph, Block, Borders}, widgets::{Paragraph, Block, Borders},
layout::{Layout, Constraint, Direction, Rect}, layout::{Layout, Constraint, Direction, Rect},
style::Style, style::{Style, Modifier},
text::{Line, Span}, text::{Line, Span},
Frame, Frame,
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::state::app::highlight::HighlightState; // Ensure correct import path
use crate::components::render_autocomplete_dropdown; use std::cmp::{min, max};
pub fn render_canvas( pub fn render_canvas(
f: &mut Frame, f: &mut Frame,
area: Rect, area: Rect,
form_state: &impl CanvasState, form_state: &impl CanvasState,
fields: &[&str], fields: &[&str],
current_field: &usize, current_field_idx: &usize,
inputs: &[&String], inputs: &[&String],
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
highlight_state: &HighlightState, // Using the enum state
) -> Option<Rect> { ) -> Option<Rect> {
// Split area into columns // ... (setup code remains the same) ...
let columns = Layout::default() let columns = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)]) .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
.split(area); .split(area);
// Input container styling
let border_style = if form_state.has_unsaved_changes() { let border_style = if form_state.has_unsaved_changes() {
Style::default().fg(theme.warning) Style::default().fg(theme.warning)
} else if is_edit_mode { } else if is_edit_mode {
@@ -41,7 +41,6 @@ pub fn render_canvas(
.border_style(border_style) .border_style(border_style)
.style(Style::default().bg(theme.bg)); .style(Style::default().bg(theme.bg));
// Input block dimensions
let input_block = Rect { let input_block = Rect {
x: columns[1].x, x: columns[1].x,
y: columns[1].y, y: columns[1].y,
@@ -51,7 +50,6 @@ pub fn render_canvas(
f.render_widget(&input_container, input_block); f.render_widget(&input_container, input_block);
// Input rows layout
let input_area = input_container.inner(input_block); let input_area = input_container.inner(input_block);
let input_rows = Layout::default() let input_rows = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
@@ -74,17 +72,113 @@ pub fn render_canvas(
}); });
} }
// Render inputs and cursor // Render inputs and cursor
for (i, input) in inputs.iter().enumerate() { for (i, input) in inputs.iter().enumerate() {
let is_active = i == *current_field; let is_active = i == *current_field_idx;
let input_display = Paragraph::new(input.as_str()) let current_cursor_pos = form_state.current_cursor_pos();
.alignment(Alignment::Left) let text = input.as_str();
.style(if is_active { let text_len = text.chars().count();
Style::default().fg(theme.highlight)
} else {
Style::default().fg(theme.fg)
});
let line: Line;
// --- Use match on the highlight_state enum ---
match highlight_state {
HighlightState::Off => {
// Not in highlight mode, render normally
line = Line::from(Span::styled(
text,
if is_active { Style::default().fg(theme.highlight) } else { Style::default().fg(theme.fg) }
));
}
HighlightState::Characterwise { anchor } => {
// --- Character-wise Highlight Logic ---
let (anchor_field, anchor_char) = *anchor;
let start_field = min(anchor_field, *current_field_idx);
let end_field = max(anchor_field, *current_field_idx);
// Use start_char and end_char consistently
let (start_char, end_char) = if anchor_field == *current_field_idx {
(min(anchor_char, current_cursor_pos), max(anchor_char, current_cursor_pos))
} else if anchor_field < *current_field_idx {
(anchor_char, current_cursor_pos)
} else {
(current_cursor_pos, anchor_char)
};
let highlight_style = Style::default().fg(theme.highlight).bg(theme.highlight_bg).add_modifier(Modifier::BOLD);
let normal_style_in_highlight = Style::default().fg(theme.highlight);
let normal_style_outside = Style::default().fg(theme.fg);
if i >= start_field && i <= end_field {
// This line is within the character-wise highlight range
if start_field == end_field { // Case 1: Single Line Highlight
// Use start_char and end_char here
let clamped_start = start_char.min(text_len);
let clamped_end = end_char.min(text_len); // Use text_len for slicing logic
let before: String = text.chars().take(clamped_start).collect();
let highlighted: String = text.chars().skip(clamped_start).take(clamped_end.saturating_sub(clamped_start) + 1).collect();
// Define 'after' here
let after: String = text.chars().skip(clamped_end + 1).collect();
line = Line::from(vec![
Span::styled(before, normal_style_in_highlight),
Span::styled(highlighted, highlight_style),
Span::styled(after, normal_style_in_highlight), // Use defined 'after'
]);
} else if i == start_field { // Case 2: Multi-Line Highlight - Start Line
// Use start_char here
let safe_start = start_char.min(text_len);
let before: String = text.chars().take(safe_start).collect();
let highlighted: String = text.chars().skip(safe_start).collect();
line = Line::from(vec![
Span::styled(before, normal_style_in_highlight),
Span::styled(highlighted, highlight_style),
]);
} else if i == end_field { // Case 3: Multi-Line Highlight - End Line (Corrected index)
// Use end_char here
let safe_end_inclusive = if text_len > 0 { end_char.min(text_len - 1) } else { 0 };
let highlighted: String = text.chars().take(safe_end_inclusive + 1).collect();
let after: String = text.chars().skip(safe_end_inclusive + 1).collect();
line = Line::from(vec![
Span::styled(highlighted, highlight_style),
Span::styled(after, normal_style_in_highlight),
]);
} else { // Case 4: Multi-Line Highlight - Middle Line (Corrected index)
line = Line::from(Span::styled(text, highlight_style)); // Highlight whole line
}
} else { // Case 5: Line Outside Character-wise Highlight Range
line = Line::from(Span::styled(
text,
// Use normal styling (active or inactive)
if is_active { normal_style_in_highlight } else { normal_style_outside }
));
}
}
HighlightState::Linewise { anchor_line } => {
// --- Linewise Highlight Logic ---
let start_field = min(*anchor_line, *current_field_idx);
let end_field = max(*anchor_line, *current_field_idx);
let highlight_style = Style::default().fg(theme.highlight).bg(theme.highlight_bg).add_modifier(Modifier::BOLD);
let normal_style_in_highlight = Style::default().fg(theme.highlight);
let normal_style_outside = Style::default().fg(theme.fg);
if i >= start_field && i <= end_field {
// Highlight the entire line
line = Line::from(Span::styled(text, highlight_style));
} else {
// Line outside linewise highlight range
line = Line::from(Span::styled(
text,
// Use normal styling (active or inactive)
if is_active { normal_style_in_highlight } else { normal_style_outside }
));
}
}
} // End match highlight_state
let input_display = Paragraph::new(line).alignment(Alignment::Left);
f.render_widget(input_display, input_rows[i]); f.render_widget(input_display, input_rows[i]);
if is_active { if is_active {
@@ -97,3 +191,4 @@ pub fn render_canvas(
active_field_input_rect active_field_input_rect
} }

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

@@ -32,6 +32,8 @@ pub struct ModeKeybindings {
#[serde(default)] #[serde(default)]
pub edit: HashMap<String, Vec<String>>, pub edit: HashMap<String, Vec<String>>,
#[serde(default)] #[serde(default)]
pub highlight: HashMap<String, Vec<String>>,
#[serde(default)]
pub command: HashMap<String, Vec<String>>, pub command: HashMap<String, Vec<String>>,
#[serde(default)] #[serde(default)]
pub common: HashMap<String, Vec<String>>, pub common: HashMap<String, Vec<String>>,
@@ -75,6 +77,14 @@ impl Config {
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers)) .or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
} }
/// Gets an action for a key in Highlight mode, also checking common/global keybindings.
pub fn get_highlight_action_for_key(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.highlight, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.common, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.read_only, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Gets an action for a key in Command mode, also checking common keybindings. /// Gets an action for a key in Command mode, also checking common keybindings.
pub fn get_command_action_for_key(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> { pub fn get_command_action_for_key(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.command, key, modifiers) self.get_action_for_key_in_mode(&self.keybindings.command, key, modifiers)

View File

@@ -10,6 +10,8 @@ pub struct Theme {
pub highlight: Color, pub highlight: Color,
pub warning: Color, pub warning: Color,
pub border: Color, pub border: Color,
pub highlight_bg: Color,
pub inactive_highlight_bg: Color,// admin panel no idea what it really is
} }
impl Theme { impl Theme {
@@ -31,6 +33,8 @@ impl Theme {
highlight: Color::Rgb(152, 251, 152), // Pastel green highlight: Color::Rgb(152, 251, 152), // Pastel green
warning: Color::Rgb(255, 182, 193), // Pastel pink warning: Color::Rgb(255, 182, 193), // Pastel pink
border: Color::Rgb(220, 220, 220), // Light gray border border: Color::Rgb(220, 220, 220), // Light gray border
highlight_bg: Color::Rgb(70, 70, 70), // Darker grey for highlight background
inactive_highlight_bg: Color::Rgb(50, 50, 50),
} }
} }
@@ -44,6 +48,8 @@ impl Theme {
highlight: Color::Rgb(50, 205, 50), // Bright green highlight: Color::Rgb(50, 205, 50), // Bright green
warning: Color::Rgb(255, 99, 71), // Bright red warning: Color::Rgb(255, 99, 71), // Bright red
border: Color::Rgb(100, 100, 100), // Medium gray border border: Color::Rgb(100, 100, 100), // Medium gray border
highlight_bg: Color::Rgb(180, 180, 180), // Lighter grey for highlight background
inactive_highlight_bg: Color::Rgb(50, 50, 50),
} }
} }
@@ -57,6 +63,8 @@ impl Theme {
highlight: Color::Rgb(0, 128, 0), // Green highlight: Color::Rgb(0, 128, 0), // Green
warning: Color::Rgb(255, 0, 0), // Red warning: Color::Rgb(255, 0, 0), // Red
border: Color::Rgb(0, 0, 0), // Black border border: Color::Rgb(0, 0, 0), // Black border
highlight_bg: Color::Rgb(180, 180, 180), // Lighter grey for highlight background
inactive_highlight_bg: Color::Rgb(50, 50, 50),
} }
} }
} }

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 | AppView::AddTable => 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,8 @@
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::*;
pub use navigation::*;

View File

@@ -2,3 +2,4 @@
pub mod form_e; pub mod form_e;
pub mod auth_e; pub mod auth_e;
pub mod add_table_e;

View File

@@ -0,0 +1,343 @@
// src/functions/modes/edit/add_table_e.rs
use crate::state::pages::add_table::AddTableState;
use crate::state::pages::canvas_state::CanvasState; // Use trait
use crossterm::event::{KeyCode, KeyEvent};
use std::error::Error;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos >= len {
return len;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
if get_char_type(chars[pos]) == CharType::Whitespace {
pos = find_next_word_start(text, pos);
}
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}
/// Executes edit actions for the AddTable view canvas.
pub async fn execute_edit_action(
action: &str,
key: KeyEvent, // Needed for insert_char
state: &mut AddTableState,
ideal_cursor_column: &mut usize,
// Add other params like grpc_client if needed for future actions (e.g., validation)
) -> Result<String, Box<dyn Error>> {
// Use the CanvasState trait methods implemented for AddTableState
match action {
"insert_char" => {
if let KeyCode::Char(c) = key.code {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
state.set_current_cursor_pos(cursor_pos + 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos();
}
} else {
return Ok("Error: insert_char called without a char key.".to_string());
}
Ok("".to_string()) // No message needed for char insertion
}
"delete_char_backward" => {
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
let new_pos = cursor_pos - 1;
state.set_current_cursor_pos(new_pos);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = new_pos;
}
}
Ok("".to_string())
}
"delete_char_forward" => {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
chars.remove(cursor_pos);
*field_value = chars.into_iter().collect();
state.set_has_unsaved_changes(true);
*ideal_cursor_column = cursor_pos;
}
Ok("".to_string())
}
"next_field" => {
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let current_field = state.current_field();
let new_field = (current_field + 1) % num_fields;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"prev_field" => {
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let current_field = state.current_field();
let new_field = if current_field == 0 {
num_fields - 1
} else {
current_field - 1
};
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"move_left" => {
let new_pos = state.current_cursor_pos().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_up" => {
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let current_field = state.current_field();
if current_field > 0 {
let new_field = current_field - 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
}
Ok("".to_string())
}
"move_down" => {
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let current_field = state.current_field();
let last_field_index = num_fields - 1;
if current_field < last_field_index {
let new_field = current_field + 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
}
Ok("".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
let new_pos = current_input.len();
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_first_line" => {
if AddTableState::INPUT_FIELD_COUNT > 0 {
state.set_current_field(0);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"move_last_line" => {
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let new_field = num_fields - 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len());
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos == current_pos {
find_word_end(current_input, new_pos + 1)
} else {
new_pos
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
// Actions handled by main event loop (mode changes, save, revert)
"exit_edit_mode" | "save" | "revert" => {
Ok("Action handled by main loop".to_string())
}
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
}
}

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,4 @@
// src/functions/modes/navigation.rs
pub mod admin_nav;
pub mod add_table_nav;

View File

@@ -0,0 +1,283 @@
// src/functions/modes/navigation/add_table_nav.rs
use crate::config::binds::config::Config;
use crate::state::{
app::state::AppState,
pages::add_table::{AddTableFocus, AddTableState},
};
use crossterm::event::{KeyEvent};
use ratatui::widgets::TableState;
use crate::tui::functions::common::add_table::handle_add_column_action;
/// Handles navigation events specifically for the Add Table view.
/// Returns true if the event was handled, false otherwise.
pub fn handle_add_table_navigation(
key: KeyEvent,
config: &Config,
app_state: &mut AppState,
add_table_state: &mut AddTableState,
command_message: &mut String,
) -> bool {
let action = config.get_general_action(key.code, key.modifiers);
let current_focus = add_table_state.current_focus;
let mut handled = true; // Assume handled unless logic determines otherwise
let mut new_focus = current_focus; // Initialize new_focus
// Define focus groups for horizontal navigation
let is_left_pane_focus = matches!(current_focus,
AddTableFocus::ColumnsTable | AddTableFocus::IndexesTable | AddTableFocus::LinksTable
);
let is_right_pane_general_focus = matches!(current_focus, // Non-canvas elements in right pane
AddTableFocus::AddColumnButton | AddTableFocus::SaveButton | AddTableFocus::CancelButton
);
let is_canvas_input_focus = matches!(current_focus,
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType
);
match action.as_deref() {
// --- Vertical Navigation (Up/Down) ---
Some("move_up") => {
match current_focus {
AddTableFocus::InputTableName => new_focus = AddTableFocus::CancelButton, // Wrap top (right pane)
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputTableName,
AddTableFocus::InputColumnType => new_focus = AddTableFocus::InputColumnName,
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::InputColumnType,
AddTableFocus::ColumnsTable => { // Left pane navigation
if !navigate_table_up(&mut add_table_state.column_table_state, add_table_state.columns.len()) {
// If at top of columns, potentially wrap to bottom of left pane (LinksTable) or stay? Let's stay for now.
// Or maybe move to AddColumnButton? Let's try moving up from right pane instead.
new_focus = AddTableFocus::AddColumnButton; // Tentative: move focus up from right pane
}
}
AddTableFocus::IndexesTable => {
if !navigate_table_up(&mut add_table_state.index_table_state, add_table_state.indexes.len()) {
new_focus = AddTableFocus::ColumnsTable;
}
}
AddTableFocus::LinksTable => {
if !navigate_table_up(&mut add_table_state.link_table_state, add_table_state.links.len()) {
new_focus = AddTableFocus::IndexesTable;
}
}
AddTableFocus::SaveButton => new_focus = AddTableFocus::LinksTable, // Move up to left pane bottom
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::SaveButton,
AddTableFocus::CancelButton => new_focus = AddTableFocus::DeleteSelectedButton,
}
}
Some("move_down") => {
match current_focus {
AddTableFocus::InputTableName => new_focus = AddTableFocus::InputColumnName,
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputColumnType,
AddTableFocus::InputColumnType => new_focus = AddTableFocus::AddColumnButton,
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::ColumnsTable, // Move down to left pane top
AddTableFocus::ColumnsTable => { // Left pane navigation
if !navigate_table_down(&mut add_table_state.column_table_state, add_table_state.columns.len()) {
new_focus = AddTableFocus::IndexesTable; // Move to next left pane item
}
}
AddTableFocus::IndexesTable => {
if !navigate_table_down(&mut add_table_state.index_table_state, add_table_state.indexes.len()) {
new_focus = AddTableFocus::LinksTable;
}
}
AddTableFocus::LinksTable => {
if !navigate_table_down(&mut add_table_state.link_table_state, add_table_state.links.len()) {
new_focus = AddTableFocus::SaveButton; // Move down to right pane bottom
}
}
AddTableFocus::SaveButton => new_focus = AddTableFocus::DeleteSelectedButton,
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::CancelButton,
AddTableFocus::CancelButton => new_focus = AddTableFocus::InputTableName, // Wrap bottom (right pane)
}
}
// --- Horizontal Navigation (Left/Right) ---
Some("next_option") => { // 'l' or Right: Move from Left Pane to Right Pane
if is_left_pane_focus {
new_focus = match current_focus {
// Map left pane items to corresponding right pane items (approximate vertical alignment)
AddTableFocus::ColumnsTable => AddTableFocus::InputTableName,
AddTableFocus::IndexesTable => AddTableFocus::InputColumnName, // Or AddColumnButton?
AddTableFocus::LinksTable => AddTableFocus::SaveButton,
_ => current_focus, // Should not happen based on is_left_pane_focus
};
} else if is_right_pane_general_focus || is_canvas_input_focus {
// If already in right pane, maybe wrap Save -> Cancel or stay? Let's handle Save->Cancel only.
if current_focus == AddTableFocus::SaveButton {
new_focus = AddTableFocus::CancelButton;
}
}
}
Some("previous_option") => { // 'h' or Left: Move from Right Pane to Left Pane
if is_right_pane_general_focus {
new_focus = match current_focus {
// Map right pane items back to left pane items (approximate vertical alignment)
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType | AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable, // Go to top of left pane
AddTableFocus::SaveButton | AddTableFocus::CancelButton => AddTableFocus::LinksTable, // Go to bottom of left pane
_ => current_focus, // Should not happen
};
} else if is_left_pane_focus {
// If already in left pane, pressing 'h' could wrap to Cancel button?
new_focus = AddTableFocus::CancelButton; // Wrap left-to-right bottom
}
}
// --- Tab / Shift+Tab Navigation (Keep as vertical cycle) ---
Some("next_field") => { // Tab
new_focus = match current_focus {
AddTableFocus::InputTableName => AddTableFocus::InputColumnName,
AddTableFocus::InputColumnName => AddTableFocus::InputColumnType,
AddTableFocus::InputColumnType => AddTableFocus::AddColumnButton,
AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable,
AddTableFocus::ColumnsTable => AddTableFocus::IndexesTable,
AddTableFocus::IndexesTable => AddTableFocus::LinksTable,
AddTableFocus::LinksTable => AddTableFocus::SaveButton,
AddTableFocus::SaveButton => AddTableFocus::DeleteSelectedButton,
AddTableFocus::DeleteSelectedButton => AddTableFocus::CancelButton,
AddTableFocus::CancelButton => AddTableFocus::InputTableName, // Wrap
};
}
Some("prev_field") => { // Shift+Tab
new_focus = match current_focus {
AddTableFocus::InputTableName => AddTableFocus::CancelButton, // Wrap
AddTableFocus::InputColumnName => AddTableFocus::InputTableName,
AddTableFocus::InputColumnType => AddTableFocus::InputColumnName,
AddTableFocus::AddColumnButton => AddTableFocus::InputColumnType,
AddTableFocus::ColumnsTable => AddTableFocus::AddColumnButton,
AddTableFocus::IndexesTable => AddTableFocus::ColumnsTable,
AddTableFocus::LinksTable => AddTableFocus::IndexesTable,
AddTableFocus::SaveButton => AddTableFocus::LinksTable,
AddTableFocus::DeleteSelectedButton => AddTableFocus::SaveButton,
AddTableFocus::CancelButton => AddTableFocus::DeleteSelectedButton,
};
}
// --- Selection ---
Some("select") => {
match current_focus {
AddTableFocus::AddColumnButton => {
if let Some(focus_after_add) = handle_add_column_action(add_table_state, command_message) {
new_focus = focus_after_add;
}
}
AddTableFocus::SaveButton => {
*command_message = "Action: Save Table (Not Implemented)".to_string();
// TODO: Implement logic
}
AddTableFocus::DeleteSelectedButton => {
*command_message = "Action: Delete selected".to_string();
// TODO: Implement logic
}
AddTableFocus::CancelButton => {
*command_message = "Action: Cancel Add Table".to_string();
// TODO: Implement logic
}
AddTableFocus::ColumnsTable => {
if let Some(index) = add_table_state.column_table_state.selected() {
*command_message = format!("Selected column index {}", index);
} else { *command_message = "No column selected".to_string(); }
}
AddTableFocus::IndexesTable => {
if let Some(index) = add_table_state.index_table_state.selected() {
*command_message = format!("Selected index index {}", index);
} else { *command_message = "No index selected".to_string(); }
}
AddTableFocus::LinksTable => {
if let Some(index) = add_table_state.link_table_state.selected() {
*command_message = format!("Selected link index {}", index);
} else { *command_message = "No link selected".to_string(); }
}
_ => { // Input fields
*command_message = format!("Select on {:?}", current_focus);
handled = false; // Let main loop handle edit mode toggle maybe
}
}
// Keep handled = true for select actions unless specifically set to false
}
// --- Other General Keys ---
Some("toggle_sidebar") | Some("toggle_buffer_list") => {
handled = false;
}
// --- No matching action ---
_ => handled = false,
}
// Update focus state if it changed and was handled
if handled && current_focus != new_focus {
add_table_state.current_focus = new_focus;
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
// --- THIS IS THE KEY PART ---
// Check if the *new* focus target is one of the canvas input fields
let new_is_canvas_input_focus = matches!(new_focus,
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType
);
// Set focus_outside_canvas based on whether the new focus is NOT an input field
app_state.ui.focus_outside_canvas = !new_is_canvas_input_focus; // <--- Sets the flag correctly
// --- END KEY PART ---
// Select first item when focusing a table
match add_table_state.current_focus {
AddTableFocus::ColumnsTable if add_table_state.column_table_state.selected().is_none() && !add_table_state.columns.is_empty() => {
add_table_state.column_table_state.select(Some(0));
}
AddTableFocus::IndexesTable if add_table_state.index_table_state.selected().is_none() && !add_table_state.indexes.is_empty() => {
add_table_state.index_table_state.select(Some(0));
}
AddTableFocus::LinksTable if add_table_state.link_table_state.selected().is_none() && !add_table_state.links.is_empty() => {
add_table_state.link_table_state.select(Some(0));
}_ => {}
}
} else if !handled {
// ...
}
handled
}
// Helper function for navigating up within a table state
// Returns true if navigation happened within the table, false if it reached the top
fn navigate_table_up(table_state: &mut TableState, item_count: usize) -> bool {
if item_count == 0 { return false; }
let current_selection = table_state.selected();
match current_selection {
Some(index) => {
if index > 0 {
table_state.select(Some(index - 1));
true
} else {
false // Was at the top
}
}
None => {
table_state.select(Some(item_count - 1)); // Select last item
true
}
}
}
// Helper function for navigating down within a table state
// Returns true if navigation happened within the table, false if it reached the bottom
fn navigate_table_down(table_state: &mut TableState, item_count: usize) -> bool {
if item_count == 0 { return false; }
let current_selection = table_state.selected();
match current_selection {
Some(index) => {
if index < item_count - 1 {
table_state.select(Some(index + 1));
true
} else {
false // Was at the bottom
}
}
None => {
table_state.select(Some(0)); // Select first item
true
}
}
}

View File

@@ -0,0 +1,213 @@
// src/functions/modes/navigation/admin_nav.rs
use crate::config::binds::config::Config;
use crate::state::{
app::state::AppState,
pages::admin::{AdminFocus, AdminState},
};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::state::app::buffer::AppView;
use crate::state::app::buffer::BufferState;
use crate::state::pages::add_table::AddTableState;
/// Handles navigation events specifically for the Admin Panel view.
/// Returns true if the event was handled, false otherwise.
pub fn handle_admin_navigation(
key: KeyEvent,
config: &Config,
app_state: &mut AppState,
admin_state: &mut AdminState,
buffer_state: &mut BufferState,
command_message: &mut String,
) -> bool {
let action = config.get_general_action(key.code, key.modifiers);
let current_focus = admin_state.current_focus;
let profile_count = app_state.profile_tree.profiles.len();
match action {
// --- Vertical Navigation (Up/Down) ---
Some("move_up") => {
match current_focus {
AdminFocus::Profiles => {
if profile_count > 0 {
// Updates navigation state, resets table state
admin_state.previous_profile(profile_count);
*command_message = "Navigated profiles".to_string();
}
}
AdminFocus::Tables => {
// Updates table navigation state
if let Some(nav_profile_idx) = admin_state.profile_list_state.selected() {
if let Some(profile) = app_state.profile_tree.profiles.get(nav_profile_idx) {
let table_count = profile.tables.len();
if table_count > 0 {
admin_state.previous_table(table_count);
*command_message = "Navigated tables".to_string();
}
}
}
}
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3 => {}
}
true // Event handled
}
Some("move_down") => {
match current_focus {
AdminFocus::Profiles => {
if profile_count > 0 {
// Updates navigation state, resets table state
admin_state.next_profile(profile_count);
*command_message = "Navigated profiles".to_string();
}
}
AdminFocus::Tables => {
if let Some(nav_profile_idx) = admin_state.profile_list_state.selected() {
if let Some(profile) = app_state.profile_tree.profiles.get(nav_profile_idx) {
let table_count = profile.tables.len();
if table_count > 0 {
admin_state.next_table(table_count);
*command_message = "Navigated tables".to_string();
}
}
}
}
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3 => {}
}
true // Event handled
}
// --- Horizontal Navigation (Focus Change) ---
Some("next_option") | Some("previous_option") => {
let old_focus = admin_state.current_focus;
let is_next = action == Some("next_option"); // Check if 'l' or 'h'
admin_state.current_focus = match old_focus {
AdminFocus::Profiles => if is_next { AdminFocus::Tables } else { AdminFocus::Button3 }, // P -> T (l) or P -> B3 (h)
AdminFocus::Tables => if is_next { AdminFocus::Button1 } else { AdminFocus::Profiles }, // T -> B1 (l) or T -> P (h)
AdminFocus::Button1 => if is_next { AdminFocus::Button2 } else { AdminFocus::Tables }, // B1 -> B2 (l) or B1 -> T (h)
AdminFocus::Button2 => if is_next { AdminFocus::Button3 } else { AdminFocus::Button1 }, // B2 -> B3 (l) or B2 -> B1 (h)
AdminFocus::Button3 => if is_next { AdminFocus::Profiles } else { AdminFocus::Button2 }, // B3 -> P (l) or B3 -> B2 (h)
};
let new_focus = admin_state.current_focus;
*command_message = format!("Focus set to {:?}", new_focus);
// Auto-select first item only when moving from Profiles to Tables via 'l'
if old_focus == AdminFocus::Profiles && new_focus == AdminFocus::Tables && is_next {
if let Some(profile_idx) = admin_state.profile_list_state.selected() {
if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
if !profile.tables.is_empty() {
admin_state.table_list_state.select(Some(0));
} else {
admin_state.table_list_state.select(None);
}
} else {
admin_state.table_list_state.select(None);
}
} else {
admin_state.table_list_state.select(None);
}
}
// Clear table nav selection if moving away from Tables
if old_focus == AdminFocus::Tables && new_focus != AdminFocus::Tables {
admin_state.table_list_state.select(None);
}
// Clear profile nav selection if moving away from Profiles
if old_focus == AdminFocus::Profiles && new_focus != AdminFocus::Profiles {
// Maybe keep profile nav highlight? Let's try clearing it.
// admin_state.profile_list_state.select(None); // Optional: clear profile nav highlight
}
true // Event handled
}
// --- Selection ---
Some("select") => {
match current_focus {
AdminFocus::Profiles => {
// Set the persistent selection to the currently navigated item
if let Some(nav_idx) = admin_state.profile_list_state.selected() {
admin_state.selected_profile_index = Some(nav_idx); // Set persistent selection
// Move focus to Tables (like pressing 'l')
admin_state.current_focus = AdminFocus::Tables;
// Select the first table for navigation highlight
admin_state.table_list_state.select(None); // Clear table nav first
admin_state.selected_table_index = None; // Clear persistent table selection
if let Some(profile) = app_state.profile_tree.profiles.get(nav_idx) {
if !profile.tables.is_empty() {
// Set table nav highlight
admin_state.table_list_state.select(Some(0));
}
}
*command_message = format!("Selected profile idx {}, focus on Tables", nav_idx);
} else {
*command_message = "No profile selected".to_string();
}
}
AdminFocus::Tables => {
// Set the persistent selection to the currently navigated item
if let Some(nav_idx) = admin_state.table_list_state.selected() {
admin_state.selected_table_index = Some(nav_idx); // Set persistent selection
*command_message = format!("Selected table index {}", nav_idx);
} else {
*command_message = "No table highlighted".to_string();
}
// We don't change focus here for now.
}
AdminFocus::Button1 => {
*command_message = "Action: Add Logic (Not Implemented)".to_string();
// TODO: Trigger action for Button 1
}
AdminFocus::Button2 => {
// --- Prepare AddTableState based on persistent selections ---
if let Some(p_idx) = admin_state.selected_profile_index {
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
let selected_profile_name = profile.name.clone();
// Create and populate the new AddTableState
let new_add_table_state = AddTableState {
profile_name: selected_profile_name,
// Reset other fields to defaults for a fresh start
..AddTableState::default()
};
// Assign the prepared state
admin_state.add_table_state = new_add_table_state;
// Switch view
buffer_state.update_history(AppView::AddTable);
app_state.ui.focus_outside_canvas = false;
*command_message = format!(
"Navigating to Add Table for profile '{}'...",
admin_state.add_table_state.profile_name
);
} else {
*command_message = "Error: Selected profile index out of bounds.".to_string();
}
} else {
*command_message = "Please select a profile ([*]) first.".to_string();
}
// --- End preparation ---
}
AdminFocus::Button3 => {
*command_message = "Action: Change Table (Not Implemented)".to_string();
// TODO: Trigger action for Button 3
}
}
true // Event handled
}
// --- Other General Keys (Ignore for admin nav) ---
Some("toggle_sidebar") | Some("toggle_buffer_list") | Some("next_field") | Some("prev_field") => {
// These are handled globally or not applicable here.
false
}
// --- No matching action ---
_ => false, // Event not handled by admin navigation
}
}

View File

@@ -2,3 +2,4 @@
pub mod auth_ro; pub mod auth_ro;
pub mod form_ro; pub mod form_ro;
pub mod add_table_ro;

View File

@@ -0,0 +1,244 @@
// src/functions/modes/read_only/add_table_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::pages::add_table::AddTableState;
use crate::state::pages::canvas_state::CanvasState; // Use trait for common actions
use crate::state::app::state::AppState;
use std::error::Error;
// Re-use word navigation helpers if they are public or move them to a common module
// For now, duplicating them here for simplicity. Consider refactoring later.
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() { CharType::Whitespace }
else if c.is_alphanumeric() { CharType::Alphanumeric }
else { CharType::Punctuation }
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos >= len { return len; }
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == initial_type { pos += 1; }
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace { pos += 1; }
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 { return 0; }
let mut pos = current_pos.min(len - 1);
if get_char_type(chars[pos]) == CharType::Whitespace {
pos = find_next_word_start(text, pos);
}
if pos >= len { return len.saturating_sub(1); }
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type { pos += 1; }
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 { return 0; }
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace { pos -= 1; }
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace { return 0; }
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type { pos -= 1; }
pos
}
// Note: find_prev_word_end might need adjustments based on desired behavior.
// This version finds the end of the word *before* the previous word start.
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let prev_start = find_prev_word_start(text, current_pos);
if prev_start == 0 { return 0; }
// Find the end of the word that starts at prev_start - 1
find_word_end(text, prev_start.saturating_sub(1))
}
/// Executes read-only actions for the AddTable view canvas.
pub async fn execute_action(
action: &str,
app_state: &mut AppState, // Needed for focus_outside_canvas
state: &mut AddTableState,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String, // Keep for potential messages
) -> Result<String, Box<dyn Error>> {
// Use the CanvasState trait methods implemented for AddTableState
match action {
"move_up" => {
key_sequence_tracker.reset();
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields == 0 { return Ok("No fields.".to_string()); }
let current_field = state.current_field(); // Gets the index (0, 1, or 2)
if current_field > 0 {
// This handles moving from field 2 -> 1, or 1 -> 0
let new_field = current_field - 1;
state.set_current_field(new_field);
// ... (rest of the logic to set cursor position) ...
} else {
// --- THIS IS WHERE THE FIX GOES ---
// current_field is 0 (InputTableName), and user pressed Up.
// We need to move focus *outside* the canvas.
// Set the flag to indicate focus is leaving the canvas
app_state.ui.focus_outside_canvas = true;
// Decide which element gets focus. Based on your layout and the
// downward navigation (CancelButton wraps to InputTableName),
// moving up from InputTableName should likely go to CancelButton.
state.current_focus = crate::state::pages::add_table::AddTableFocus::CancelButton;
// Reset the sequence tracker as the action is complete
key_sequence_tracker.reset();
// Return a message indicating the focus change
return Ok("Focus moved above canvas".to_string());
// --- END FIX ---
}
// If we moved within the canvas (e.g., 1 -> 0), return empty string
Ok("".to_string())
}
"move_down" => {
key_sequence_tracker.reset();
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields == 0 { return Ok("No fields.".to_string()); }
let current_field = state.current_field();
let last_field_index = num_fields - 1;
if current_field < last_field_index {
let new_field = current_field + 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = current_input.len(); // Allow cursor at end
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
} else {
// Move focus outside canvas when moving down from the last field
app_state.ui.focus_outside_canvas = true;
// Set focus to the first element outside canvas (AddColumnButton)
state.current_focus = crate::state::pages::add_table::AddTableFocus::AddColumnButton;
key_sequence_tracker.reset();
return Ok("Focus moved below canvas".to_string());
}
Ok("".to_string())
}
"move_first_line" => {
key_sequence_tracker.reset();
if AddTableState::INPUT_FIELD_COUNT > 0 {
state.set_current_field(0);
let current_input = state.get_current_input();
let max_cursor_pos = current_input.len();
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos; // Update ideal column
}
Ok("".to_string())
}
"move_last_line" => {
key_sequence_tracker.reset();
let num_fields = AddTableState::INPUT_FIELD_COUNT;
if num_fields > 0 {
let last_field_index = num_fields - 1;
state.set_current_field(last_field_index);
let current_input = state.get_current_input();
let max_cursor_pos = current_input.len();
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos; // Update ideal column
}
Ok("".to_string())
}
"move_left" => {
let current_pos = state.current_cursor_pos();
let new_pos = current_pos.saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
// Allow moving cursor one position past the end
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len()); // Allow cursor at end
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
// If find_word_end returns current_pos, try starting search from next char
let final_pos = if new_pos == current_pos && current_pos < current_input.len() {
find_word_end(current_input, current_pos + 1)
} else {
new_pos
};
let max_valid_index = current_input.len(); // Allow cursor at end
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
let new_pos = current_input.len(); // Allow cursor at end
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
// Actions handled by main event loop (mode changes)
"enter_edit_mode_before" | "enter_edit_mode_after" | "enter_command_mode" | "exit_highlight_mode" => {
key_sequence_tracker.reset();
Ok("Mode change handled by main loop".to_string())
}
_ => {
key_sequence_tracker.reset();
command_message.clear(); // Clear message for unhandled actions
Ok(format!("Unknown read-only action: {}", action))
},
}
}

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

@@ -1,110 +1,192 @@
// src/modes/canvas/edit.rs // src/modes/canvas/edit.rs
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::{
use crate::state::canvas_state::CanvasState; auth::{LoginState, RegisterState},
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::state::pages::add_table::AddTableState; // Added
use crate::modes::handlers::event::EventOutcome; use crate::modes::handlers::event::EventOutcome;
use crate::state::state::AppState; use crate::functions::modes::edit::{auth_e, form_e};
use crate::functions::modes::edit::add_table_e; // Added
use crate::state::app::state::AppState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditEventOutcome {
Message(String), // Return a message, stay in Edit mode
ExitEditMode, // Signal to exit Edit mode
}
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,
add_table_state: &mut AddTableState, // Added
ideal_cursor_column: &mut usize, ideal_cursor_column: &mut usize,
command_message: &mut String,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
app_state: &AppState, app_state: &AppState,
) -> Result<String, Box<dyn std::error::Error>> { ) -> Result<EditEventOutcome, Box<dyn std::error::Error>> {
// Global command mode check (should ideally be handled before calling this function)
// Global command mode check
if let Some("enter_command_mode") = config.get_action_for_key_in_mode( if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
&config.keybindings.global, &config.keybindings.global,
key.code, key.code,
key.modifiers key.modifiers,
) { ) {
*command_message = "Switching to Command Mode...".to_string(); // This mode change should likely be handled in event.rs
return Ok(command_message.clone()); // Returning a message here might prevent the mode switch.
// Consider if this check is necessary here.
return Ok(EditEventOutcome::Message(
"Command mode entry handled globally.".to_string(),
));
} }
// Common actions (save/revert)
if let Some(action) = config.get_action_for_key_in_mode( if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common, &config.keybindings.common,
key.code, key.code,
key.modifiers key.modifiers,
) { ).as_deref() {
if matches!(action, "save" | "revert") { if matches!(action, "save" | "revert") {
let message = if app_state.ui.show_login { let message_string: String = 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,
).await )
.await?
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
// Keeping this block as requested
auth_e::execute_common_action( auth_e::execute_common_action(
action, action,
register_state, register_state,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
} else { .await? // Results in String on success
form_e::execute_common_action( } else if app_state.ui.show_add_table {
// Placeholder - common actions for AddTable might be different
format!(
"Action '{}' not fully implemented for Add Table view here.",
action
)
} else { // Assuming FormState otherwise
let outcome = form_e::execute_common_action(
action, action,
form_state, // Concrete FormState form_state,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.map(|outcome| match outcome { .await?;
match outcome {
EventOutcome::Ok(msg) => msg, EventOutcome::Ok(msg) => msg,
EventOutcome::Exit(msg) => format!("Exit requested: {}", msg), EventOutcome::DataSaved(_, msg) => msg,
EventOutcome::DataSaved(save_outcome, msg) => format!("Data saved ({:?}): {}", save_outcome, msg), _ => format!(
EventOutcome::ButtonSelected { context, index } => { "Unexpected outcome from common action: {:?}",
"Unexpected action in edit mode".to_string() outcome
} ),
}) }
}?; };
return Ok(message); return Ok(EditEventOutcome::Message(message_string));
} }
} }
// Edit-specific actions // Edit-specific actions
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) { if let Some(action) =
// --- Special Handling for Tab/Shift+Tab in Role Field --- config.get_edit_action_for_key(key.code, key.modifiers)
.as_deref() {
if action == "exit" {
// Handle exiting suggestion mode in Register view first
if app_state.ui.show_register && register_state.in_suggestion_mode {
let msg = auth_e::execute_edit_action(
"exit_suggestion_mode", // Specific action for suggestion exit
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count,
)
.await?;
return Ok(EditEventOutcome::Message(msg));
} else {
// Signal exit from Edit mode
return Ok(EditEventOutcome::ExitEditMode);
}
}
// Special handling for role field suggestions (Register view only)
if app_state.ui.show_register && register_state.current_field() == 4 { if app_state.ui.show_register && register_state.current_field() == 4 {
if !register_state.in_suggestion_mode && key.code == KeyCode::Tab && key.modifiers == KeyModifiers::NONE { // Check if Tab was pressed to *enter* suggestion mode
if !register_state.in_suggestion_mode
&& key.code == KeyCode::Tab
&& key.modifiers == KeyModifiers::NONE
{
register_state.update_role_suggestions(); register_state.update_role_suggestions();
if !register_state.role_suggestions.is_empty() { if !register_state.role_suggestions.is_empty() {
register_state.in_suggestion_mode = true; register_state.in_suggestion_mode = true;
register_state.selected_suggestion_index = Some(0); // Select first suggestion register_state.selected_suggestion_index = Some(0); // Select first suggestion
return Ok("Suggestions shown".to_string()); return Ok(EditEventOutcome::Message(
"Suggestions shown".to_string(),
));
} else { } else {
return Ok("No suggestions available".to_string()); return Ok(EditEventOutcome::Message(
"No suggestions available".to_string(),
));
} }
} }
// Handle suggestion navigation/selection if already in suggestion mode
if register_state.in_suggestion_mode
&& matches!(
action,
"suggestion_down"
| "suggestion_up"
| "select_suggestion"
)
{
let msg = auth_e::execute_edit_action(
action, // Pass the specific suggestion action
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count,
)
.await?;
return Ok(EditEventOutcome::Message(msg));
}
} }
// --- End Special Handling ---
return if app_state.ui.show_login { // Execute other edit actions based on the current view
let msg = if app_state.ui.show_login {
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,
total_count total_count,
).await )
.await?
} else if app_state.ui.show_add_table {
add_table_e::execute_edit_action(
action,
key,
add_table_state,
ideal_cursor_column,
// Pass other necessary params if add_table_e needs them
)
.await?
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
auth_e::execute_edit_action( auth_e::execute_edit_action(
action, action,
@@ -113,9 +195,11 @@ pub async fn handle_edit_event(
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
} else { } else {
// Assuming FormState otherwise
form_e::execute_edit_action( form_e::execute_edit_action(
action, action,
key, key,
@@ -123,32 +207,42 @@ pub async fn handle_edit_event(
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
}; };
return Ok(EditEventOutcome::Message(msg));
} }
// Character insertion // --- Character insertion ---
if let KeyCode::Char(_) = key.code { if let KeyCode::Char(c) = key.code {
// If in suggestion mode, exit it before inserting char // Exit suggestion mode in Register view if a character is typed
if app_state.ui.show_register && register_state.in_suggestion_mode { if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false; register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false; register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None; register_state.selected_suggestion_index = None;
} }
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
// --- End Autocomplete Trigger --- // Execute insert_char action based on the current view
let msg = if app_state.ui.show_login {
return if app_state.ui.show_login {
auth_e::execute_edit_action( auth_e::execute_edit_action(
"insert_char", "insert_char",
key, key, // Pass the key event containing the char
auth_state, login_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
} else if app_state.ui.show_add_table {
add_table_e::execute_edit_action(
"insert_char",
key,
add_table_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
auth_e::execute_edit_action( auth_e::execute_edit_action(
"insert_char", "insert_char",
@@ -157,9 +251,11 @@ pub async fn handle_edit_event(
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
} else { } else {
// Assuming FormState otherwise
form_e::execute_edit_action( form_e::execute_edit_action(
"insert_char", "insert_char",
key, key,
@@ -167,40 +263,85 @@ pub async fn handle_edit_event(
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
}; };
// Update role suggestions after insertion if needed (Register view)
if app_state.ui.show_register && register_state.current_field() == 4 {
register_state.update_role_suggestions();
}
return Ok(EditEventOutcome::Message(msg));
} }
// Handle Backspace/Delete for Autocomplete Trigger // --- Handle Backspace/Delete ---
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) { if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
// If in suggestion mode, exit it before deleting char // Exit suggestion mode in Register view
if app_state.ui.show_register && register_state.in_suggestion_mode { if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false; register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false; register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None; register_state.selected_suggestion_index = None;
} }
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
// Execute the action first let action_str = if key.code == KeyCode::Backspace {
let result = if app_state.ui.show_register { "delete_char_backward"
auth_e::execute_edit_action( } else {
"delete_char_forward"
};
// Execute delete action based on the current view
let result_msg: String = if app_state.ui.show_login {
auth_e::execute_edit_action(
action_str,
key,
login_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count,
)
.await?
} else if app_state.ui.show_add_table {
add_table_e::execute_edit_action(
action_str,
key,
add_table_state,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register {
auth_e::execute_edit_action(
action_str, action_str,
key, key,
register_state, register_state,
ideal_cursor_column, ideal_cursor_column,
grpc_client, grpc_client,
current_position, current_position,
total_count total_count,
).await )
.await?
} else { } else {
// Handle for login/form if needed, assuming auth_e covers RegisterState // Assuming FormState otherwise
Ok("Action not applicable here".to_string()) // Placeholder form_e::execute_edit_action(
}?; action_str,
key,
form_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await?
};
// Update role suggestions after deletion if needed (Register view)
if app_state.ui.show_register && register_state.current_field() == 4 {
register_state.update_role_suggestions();
}
return Ok(result); return Ok(EditEventOutcome::Message(result_msg));
} }
Ok(command_message.clone()) // Default return if no other handler matched
Ok(EditEventOutcome::Message("".to_string()))
} }

View File

@@ -3,11 +3,12 @@
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::pages::add_table::AddTableState;
use crate::functions::modes::read_only::{auth_ro, form_ro}; use crate::state::app::state::AppState;
use crate::functions::modes::read_only::{auth_ro, form_ro, add_table_ro};
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
pub async fn handle_read_only_event( pub async fn handle_read_only_event(
@@ -15,8 +16,9 @@ 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,
add_table_state: &mut AddTableState,
key_sequence_tracker: &mut KeySequenceTracker, key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
@@ -32,34 +34,17 @@ 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 // Determine target state to adjust cursor
( let target_state: &mut dyn CanvasState = if app_state.ui.show_login { login_state }
auth_state.get_current_input(), else if app_state.ui.show_register { register_state }
auth_state.current_cursor_pos(), else if app_state.ui.show_add_table { add_table_state }
) else { form_state };
} else if app_state.ui.show_register { // Then check Register let current_input = target_state.get_current_input();
( let current_pos = target_state.current_cursor_pos();
register_state.get_current_input(),
register_state.current_cursor_pos(),
)
} else {
(
form_state.get_current_input(),
form_state.current_cursor_pos(),
) // Default to Form
};
if !current_input.is_empty() && current_pos < current_input.len() { if !current_input.is_empty() && current_pos < current_input.len() {
if app_state.ui.show_login { target_state.set_current_cursor_pos(current_pos + 1);
auth_state.set_current_cursor_pos(current_pos + 1); *ideal_cursor_column = target_state.current_cursor_pos();
*ideal_cursor_column = auth_state.current_cursor_pos();
} else if app_state.ui.show_register {
register_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = register_state.current_cursor_pos();
} else { // Default to Form
form_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = form_state.current_cursor_pos();
}
} }
*edit_mode_cooldown = true; *edit_mode_cooldown = true;
*command_message = "Entering Edit mode (after cursor)".to_string(); *command_message = "Entering Edit mode (after cursor)".to_string();
@@ -83,7 +68,7 @@ pub async fn handle_read_only_event(
key_sequence_tracker.add_key(key.code); key_sequence_tracker.add_key(key.code);
let sequence = key_sequence_tracker.get_sequence(); let sequence = key_sequence_tracker.get_sequence();
if let Some(action) = config.matches_key_sequence_generalized(&sequence) { if let Some(action) = config.matches_key_sequence_generalized(&sequence).as_deref() {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) { let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
@@ -95,12 +80,16 @@ 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?
} else if app_state.ui.show_add_table {
add_table_ro::execute_action(
action, action,
auth_state, app_state,
add_table_state,
ideal_cursor_column, ideal_cursor_column,
) key_sequence_tracker,
.await? command_message,
).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 +103,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,
@@ -139,7 +128,7 @@ pub async fn handle_read_only_event(
} }
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) { if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers).as_deref() {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) { let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
@@ -151,12 +140,16 @@ 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?
} else if app_state.ui.show_add_table {
add_table_ro::execute_action(
action, action,
auth_state, app_state,
add_table_state,
ideal_cursor_column, ideal_cursor_column,
) key_sequence_tracker,
.await? command_message,
).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 +163,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,
@@ -194,7 +187,7 @@ pub async fn handle_read_only_event(
} else { } else {
key_sequence_tracker.reset(); key_sequence_tracker.reset();
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) { if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers).as_deref() {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) { let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action( crate::tui::functions::form::handle_action(
action, action,
@@ -205,13 +198,17 @@ pub async fn handle_read_only_event(
ideal_cursor_column, ideal_cursor_column,
) )
.await? .await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions } else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
crate::tui::functions::login::handle_action( crate::tui::functions::login::handle_action(action).await?
} else if app_state.ui.show_add_table {
add_table_ro::execute_action(
action, action,
auth_state, app_state,
add_table_state,
ideal_cursor_column, ideal_cursor_column,
) key_sequence_tracker,
.await? command_message,
).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 +222,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,47 @@
// 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::{
highlight::HighlightState,
state::AppState,
buffer::{AppView, BufferState},
},
pages::{
auth::{AuthState, LoginState, RegisterState},
admin::AdminState,
canvas_state::CanvasState,
add_table::AddTableState,
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},
highlight::highlight,
general::{navigation, dialog}, general::{navigation, dialog},
}; };
use crate::functions::modes::navigation::{admin_nav, add_table_nav};
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 {
@@ -36,6 +56,7 @@ pub struct EventHandler {
pub command_input: String, pub command_input: String,
pub command_message: String, pub command_message: String,
pub is_edit_mode: bool, pub is_edit_mode: bool,
pub highlight_state: HighlightState,
pub edit_mode_cooldown: bool, pub edit_mode_cooldown: bool,
pub ideal_cursor_column: usize, pub ideal_cursor_column: usize,
pub key_sequence_tracker: KeySequenceTracker, pub key_sequence_tracker: KeySequenceTracker,
@@ -49,6 +70,7 @@ impl EventHandler {
command_input: String::new(), command_input: String::new(),
command_message: String::new(), command_message: String::new(),
is_edit_mode: false, is_edit_mode: false,
highlight_state: HighlightState::Off,
edit_mode_cooldown: false, edit_mode_cooldown: false,
ideal_cursor_column: 0, ideal_cursor_column: 0,
key_sequence_tracker: KeySequenceTracker::new(800), key_sequence_tracker: KeySequenceTracker::new(800),
@@ -65,24 +87,41 @@ 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);
// --- DIALOG MODALITY --- 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_add_table { AppView::AddTable }
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);
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;
} }
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
// --- END DIALOG MODALITY CHECK ---
if let Event::Key(key) = event { if let Event::Key(key) = event {
let key_code = key.code; let key_code = key.code;
@@ -94,83 +133,173 @@ 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));
}
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
) {
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()));
}
}
_ => {}
}
}
}
match current_mode { match current_mode {
AppMode::General => { AppMode::General => {
// Prioritize Admin Panel navigation if it's visible
if app_state.ui.show_admin
&& auth_state.role.as_deref() == Some("admin") {
if admin_nav::handle_admin_navigation(
key,
config,
app_state,
admin_state,
buffer_state,
&mut self.command_message,
) {
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
}
// --- Add Table Page Navigation ---
if app_state.ui.show_add_table {
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
if add_table_nav::handle_add_table_navigation(
key,
config,
app_state,
&mut admin_state.add_table_state,
&mut self.command_message,
) {
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
}
}
let nav_outcome = navigation::handle_navigation_event( let nav_outcome = navigation::handle_navigation_event(
key, key,
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,
).await; ).await;
match nav_outcome { match nav_outcome {
Ok(EventOutcome::ButtonSelected { context, index }) => { Ok(EventOutcome::ButtonSelected { context, index }) => {
let mut message = String::from("Selected"); // Default message let mut message = String::from("Selected");
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 {
if !app_state.profile_tree.profiles.is_empty() {
admin_state.profile_list_state.select(Some(0));
}
}
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 => {
message = "Internal error: Unexpected dialog state".to_string(); message = "Internal error: Unexpected dialog state".to_string();
} }
} }
return Ok(EventOutcome::Ok(message)); // Return Ok with message return Ok(EventOutcome::Ok(message));
} }
other => return other, // Pass through Ok, Err, DataSaved directly other => return other,
} }
}, },
AppMode::ReadOnly => { AppMode::ReadOnly => {
if config.is_enter_edit_mode_before(key_code, modifiers) && // Check for Linewise highlight first
ModeManager::can_enter_edit_mode(current_mode) { if config.get_read_only_action_for_key(key_code, modifiers) == Some("enter_highlight_mode_linewise")
&& ModeManager::can_enter_highlight_mode(current_mode)
{
let current_field_index = if app_state.ui.show_login { login_state.current_field() }
else if app_state.ui.show_register { register_state.current_field() }
else { form_state.current_field() };
self.highlight_state = HighlightState::Linewise { anchor_line: current_field_index };
self.command_message = "-- LINE HIGHLIGHT --".to_string();
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
// Check for Character-wise highlight
else if config.get_read_only_action_for_key(key_code, modifiers) == Some("enter_highlight_mode")
&& ModeManager::can_enter_highlight_mode(current_mode)
{
let current_field_index = if app_state.ui.show_login { login_state.current_field() }
else if app_state.ui.show_register { register_state.current_field() }
else { form_state.current_field() };
let current_cursor_pos = if app_state.ui.show_login { login_state.current_cursor_pos() }
else if app_state.ui.show_register { register_state.current_cursor_pos() }
else { form_state.current_cursor_pos() };
let anchor = (current_field_index, current_cursor_pos);
self.highlight_state = HighlightState::Characterwise { anchor };
self.command_message = "-- HIGHLIGHT --".to_string();
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
// Check for entering edit mode (before cursor)
else if config.get_read_only_action_for_key(key_code, modifiers).as_deref() == Some("enter_edit_mode_before")
&& ModeManager::can_enter_edit_mode(current_mode) {
self.is_edit_mode = true; self.is_edit_mode = true;
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
self.command_message = "Edit mode".to_string(); self.command_message = "Edit mode".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?; terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(self.command_message.clone()));
} }
// Check for entering edit mode (after cursor)
if config.is_enter_edit_mode_after(key_code, modifiers) && else if config.get_read_only_action_for_key(key_code, modifiers).as_deref() == Some("enter_edit_mode_after")
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();
@@ -178,31 +307,29 @@ impl EventHandler {
} }
self.is_edit_mode = true; self.is_edit_mode = true;
self.edit_mode_cooldown = true; self.edit_mode_cooldown = true;
app_state.ui.focus_outside_canvas = false;
self.command_message = "Edit mode (after cursor)".to_string(); self.command_message = "Edit mode (after cursor)".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?; terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(self.command_message.clone()));
} }
// Check for entering command mode
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) { else if config.get_read_only_action_for_key(key_code, modifiers) == Some("enter_command_mode")
if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) { && ModeManager::can_enter_command_mode(current_mode) {
self.command_mode = true; self.command_mode = true;
self.command_input.clear(); self.command_input.clear();
self.command_message.clear(); self.command_message.clear();
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
}
} }
if let Some(action) = config.get_action_for_key_in_mode( // Check for common actions (save, quit, etc.) only if no mode change happened
&config.keybindings.common, if let Some(action) = config.get_common_action(key_code, modifiers) {
key_code,
modifiers
) {
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit" | "revert" => {
return common_mode::handle_core_action( return common_mode::handle_core_action(
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,
@@ -216,13 +343,15 @@ impl EventHandler {
} }
} }
// If no mode change or specific common action handled, delegate to read_only handler
let (_should_exit, message) = read_only::handle_read_only_event( let (_should_exit, message) = read_only::handle_read_only_event(
app_state, app_state,
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state, register_state,
&mut admin_state.add_table_state,
&mut self.key_sequence_tracker, &mut self.key_sequence_tracker,
current_position, current_position,
total_count, total_count,
@@ -231,63 +360,55 @@ impl EventHandler {
&mut self.edit_mode_cooldown, &mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column, &mut self.ideal_cursor_column,
).await?; ).await?;
// Note: handle_read_only_event should ignore mode entry keys internally now
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
}, }, // End AppMode::ReadOnly
AppMode::Highlight => {
// --- Handle Highlight Mode Specific Keys ---
// 1. Check for Exit first
if config.get_highlight_action_for_key(key_code, modifiers) == Some("exit_highlight_mode") {
self.highlight_state = HighlightState::Off;
self.command_message = "Exited highlight mode".to_string();
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
// 2. Check for Switch to Linewise
else if config.get_highlight_action_for_key(key_code, modifiers) == Some("enter_highlight_mode_linewise") {
// Only switch if currently characterwise
if let HighlightState::Characterwise { anchor } = self.highlight_state {
self.highlight_state = HighlightState::Linewise { anchor_line: anchor.0 };
self.command_message = "-- LINE HIGHLIGHT --".to_string();
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
return Ok(EventOutcome::Ok("".to_string()));
}
let (_should_exit, message) = read_only::handle_read_only_event(
app_state, key, config, form_state, login_state,
register_state, &mut admin_state.add_table_state, &mut self.key_sequence_tracker,
current_position, total_count, grpc_client,
&mut self.command_message, &mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column,
)
.await?;
return Ok(EventOutcome::Ok(message));
}
AppMode::Edit => { AppMode::Edit => {
if config.is_exit_edit_mode(key_code, modifiers) { // First, check for common actions (save, revert, etc.) that apply in Edit mode
self.is_edit_mode = false; // These might take precedence or have different behavior than the edit handler
self.edit_mode_cooldown = true; if let Some(action) = config.get_common_action(key_code, modifiers) {
// Handle common actions like save, revert, force_quit, save_and_quit
let has_changes = if app_state.ui.show_login || app_state.ui.show_register{ // Ensure these actions return EventOutcome directly if they might exit the app
auth_state.has_unsaved_changes()
} else {
form_state.has_unsaved_changes()
};
self.command_message = if has_changes {
"Exited edit mode (unsaved changes remain)".to_string()
} else {
"Read-only mode".to_string()
};
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.get_current_input()
} else {
form_state.get_current_input()
};
let current_cursor_pos = if app_state.ui.show_login || app_state.ui.show_register{
auth_state.current_cursor_pos()
} else {
form_state.current_cursor_pos()
};
if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
let new_pos = current_input.len() - 1;
if app_state.ui.show_login || app_state.ui.show_register{
auth_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = auth_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = form_state.current_cursor_pos();
}
}
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit" | "revert" => {
// This call likely returns EventOutcome, handle it directly
return common_mode::handle_core_action( return common_mode::handle_core_action(
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,
@@ -297,34 +418,81 @@ impl EventHandler {
total_count, total_count,
).await; ).await;
}, },
// Handle other common actions if necessary
_ => {} _ => {}
} }
// If a common action was handled but didn't return/exit,
// we might want to stop further processing for this key event.
// Depending on the action, you might return Ok(EventOutcome::Ok(...)) here.
// For now, assume common actions either exit or don't prevent further processing.
} }
let message = edit::handle_edit_event( // If no common action took precedence, delegate to the edit-specific handler
let edit_result = edit::handle_edit_event(
key, key,
config, config,
form_state, form_state,
auth_state, login_state,
register_state, register_state,
&mut admin_state.add_table_state,
&mut self.ideal_cursor_column, &mut self.ideal_cursor_column,
&mut self.command_message,
current_position, current_position,
total_count, total_count,
grpc_client, grpc_client,
app_state, app_state,
).await?; ).await;
self.key_sequence_tracker.reset(); match edit_result {
return Ok(EventOutcome::Ok(message)); Ok(edit::EditEventOutcome::ExitEditMode) => {
}, // The edit handler signaled to exit the mode
self.is_edit_mode = false;
self.edit_mode_cooldown = true;
let has_changes = if app_state.ui.show_login { login_state.has_unsaved_changes() }
else if app_state.ui.show_register { register_state.has_unsaved_changes() }
else { form_state.has_unsaved_changes() };
self.command_message = if has_changes {
"Exited edit mode (unsaved changes remain)".to_string()
} else {
"Read-only mode".to_string()
};
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
// Adjust cursor position if needed
let current_input = if app_state.ui.show_login { login_state.get_current_input() }
else if app_state.ui.show_register { register_state.get_current_input() }
else { form_state.get_current_input() };
let current_cursor_pos = if app_state.ui.show_login { login_state.current_cursor_pos() }
else if app_state.ui.show_register { register_state.current_cursor_pos() }
else { form_state.current_cursor_pos() };
if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
let new_pos = current_input.len() - 1;
let target_state: &mut dyn CanvasState = if app_state.ui.show_login { login_state } else if app_state.ui.show_register { register_state } else { form_state };
target_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = new_pos;
}
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
Ok(edit::EditEventOutcome::Message(msg)) => {
// Stay in edit mode, update message if not empty
if !msg.is_empty() {
self.command_message = msg;
}
self.key_sequence_tracker.reset(); // Reset sequence tracker on successful edit action
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
Err(e) => {
// Handle error from the edit handler
return Err(e);
}
}
}, // End AppMode::Edit
AppMode::Command => { AppMode::Command => {
let outcome = command_mode::handle_command_event( let outcome = command_mode::handle_command_event(
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,12 +1,16 @@
// 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;
use crate::state::app::highlight::HighlightState;
use crate::state::pages::add_table::AddTableFocus;
use crate::state::pages::admin::AdminState;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode { pub enum AppMode {
General, // For intro and admin screens General, // For intro and admin screens
ReadOnly, // Canvas read-only mode ReadOnly, // Canvas read-only mode
Edit, // Canvas edit mode Edit, // Canvas edit mode
Highlight, // Cnavas highlight/visual mode
Command, // Command mode overlay Command, // Command mode overlay
} }
@@ -19,21 +23,28 @@ impl ModeManager {
return AppMode::Command; return AppMode::Command;
} }
if !matches!(event_handler.highlight_state, HighlightState::Off) {
return AppMode::Highlight;
}
if app_state.ui.focus_outside_canvas { if app_state.ui.focus_outside_canvas {
return AppMode::General; return AppMode::General;
} }
if app_state.ui.show_login || app_state.ui.show_register { let is_canvas_view = app_state.ui.show_login
if event_handler.is_edit_mode { || app_state.ui.show_register
AppMode::Edit || app_state.ui.show_form
|| app_state.ui.show_add_table;
if is_canvas_view {
if app_state.ui.focus_outside_canvas {
AppMode::General
} else { } else {
AppMode::ReadOnly if event_handler.is_edit_mode {
} AppMode::Edit
} else if app_state.ui.show_form { } else {
if event_handler.is_edit_mode { AppMode::ReadOnly
AppMode::Edit }
} else {
AppMode::ReadOnly
} }
} else { } else {
AppMode::General AppMode::General
@@ -50,6 +61,10 @@ impl ModeManager {
} }
pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool { pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::Edit | AppMode::Command) matches!(current_mode, AppMode::Edit | AppMode::Command | AppMode::Highlight)
}
pub fn can_enter_highlight_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::ReadOnly)
} }
} }

View File

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

View File

@@ -0,0 +1,65 @@
// src/modes/highlight/highlight.rs
// (This file is intentionally simple for now, reusing ReadOnly logic)
use crate::config::binds::config::Config;
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::services::grpc_client::GrpcClient;
use crate::state::app::state::AppState;
use crate::state::pages::auth::{LoginState, RegisterState};
use crate::state::pages::add_table::AddTableState;
use crate::state::pages::form::FormState;
use crate::modes::handlers::event::EventOutcome;
use crate::modes::read_only; // Import the ReadOnly handler
use crossterm::event::KeyEvent;
/// Handles events when in Highlight mode.
/// Currently, it mostly delegates to the read_only handler for movement.
/// Exiting highlight mode is handled directly in the main event handler.
pub async fn handle_highlight_event(
app_state: &mut AppState,
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
add_table_state: &mut AddTableState,
key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
command_message: &mut String,
edit_mode_cooldown: &mut bool,
ideal_cursor_column: &mut usize,
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
// Delegate movement and other actions to the read_only handler
// The rendering logic will use the highlight_anchor to draw the selection
let (should_exit, message) = read_only::handle_read_only_event(
app_state,
key,
config,
form_state,
login_state,
register_state,
add_table_state,
key_sequence_tracker,
current_position,
total_count,
grpc_client,
command_message, // Pass the message buffer
edit_mode_cooldown,
ideal_cursor_column,
)
.await?;
// ReadOnly handler doesn't return EventOutcome directly, adapt if needed
// For now, assume Ok outcome unless ReadOnly signals an exit (which we ignore here)
if should_exit {
// This exit is likely for the whole app, let the main loop handle it
// We just return the message from read_only
Ok(EventOutcome::Ok(message))
} else {
Ok(EventOutcome::Ok(message))
}
}

View File

@@ -3,8 +3,10 @@ pub mod handlers;
pub mod canvas; pub mod canvas;
pub mod general; pub mod general;
pub mod common; pub mod common;
pub mod highlight;
pub use handlers::*; pub use handlers::*;
pub use canvas::*; pub use canvas::*;
pub use general::*; pub use general::*;
pub use common::*; pub use common::*;
pub use highlight::*;

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;

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

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

View File

@@ -0,0 +1,94 @@
// 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,
AddTable,
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::AddTable => "Add_Table",
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

@@ -0,0 +1,20 @@
// src/state/app/highlight.rs
/// Represents the different states of text highlighting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HighlightState {
/// Highlighting is inactive.
Off,
/// Highlighting character by character. Stores the anchor point (line index, char index).
Characterwise { anchor: (usize, usize) },
/// Highlighting line by line. Stores the anchor line index.
Linewise { anchor_line: usize },
}
impl Default for HighlightState {
/// The default state is no highlighting.
fn default() -> Self {
HighlightState::Off
}
}

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,17 @@ 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_add_table: 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 +35,10 @@ pub struct AppState {
pub profile_tree: ProfileTreeResponse, pub profile_tree: ProfileTreeResponse,
pub selected_profile: Option<String>, pub selected_profile: Option<String>,
pub current_mode: AppMode, pub current_mode: AppMode,
pub focused_button_index: usize,
// UI preferences // UI preferences
pub ui: UiState, pub ui: UiState,
pub general: GeneralState,
} }
impl AppState { impl AppState {
@@ -58,11 +53,8 @@ impl AppState {
profile_tree: ProfileTreeResponse::default(), profile_tree: ProfileTreeResponse::default(),
selected_profile: None, selected_profile: None,
current_mode: AppMode::General, current_mode: AppMode::General,
focused_button_index: 0,
ui: UiState::default(), ui: UiState::default(),
general: GeneralState {
selected_item: 0,
current_option: 0,
},
}) })
} }
@@ -140,13 +132,14 @@ 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_add_table: 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,7 @@
pub mod form; pub mod form;
pub mod auth; pub mod auth;
pub mod admin;
pub mod intro;
pub mod add_table;
pub mod canvas_state;

View File

@@ -0,0 +1,165 @@
// src/state/pages/add_table.rs
use crate::state::pages::canvas_state::CanvasState;
use ratatui::widgets::TableState;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnDefinition {
pub name: String,
pub data_type: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkDefinition {
pub linked_table_name: String,
pub is_required: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AddTableFocus {
#[default]
InputTableName, // Field 0 for CanvasState
InputColumnName, // Field 1 for CanvasState
InputColumnType, // Field 2 for CanvasState
AddColumnButton,
// Result Tables
ColumnsTable,
IndexesTable,
LinksTable,
// Buttons
SaveButton,
DeleteSelectedButton,
CancelButton,
}
#[derive(Debug, Clone)]
pub struct AddTableState {
pub profile_name: String,
pub table_name: String,
pub table_name_input: String,
pub column_name_input: String,
pub column_type_input: String,
pub columns: Vec<ColumnDefinition>,
pub indexes: Vec<String>,
pub links: Vec<LinkDefinition>,
pub current_focus: AddTableFocus,
pub column_table_state: TableState,
pub index_table_state: TableState,
pub link_table_state: TableState,
pub table_name_cursor_pos: usize,
pub column_name_cursor_pos: usize,
pub column_type_cursor_pos: usize,
pub has_unsaved_changes: bool,
}
impl Default for AddTableState {
fn default() -> Self {
// Initialize with some dummy data for demonstration
AddTableState {
profile_name: "default".to_string(),
table_name: String::new(),
table_name_input: String::new(),
column_name_input: String::new(),
column_type_input: String::new(),
columns: Vec::new(),
indexes: Vec::new(),
links: Vec::new(),
current_focus: AddTableFocus::InputTableName,
column_table_state: TableState::default(),
index_table_state: TableState::default(),
link_table_state: TableState::default(),
table_name_cursor_pos: 0,
column_name_cursor_pos: 0,
column_type_cursor_pos: 0,
has_unsaved_changes: false,
}
}
}
impl AddTableState {
pub const INPUT_FIELD_COUNT: usize = 3;
}
// Implement CanvasState for the input fields
impl CanvasState for AddTableState {
fn current_field(&self) -> usize {
match self.current_focus {
AddTableFocus::InputTableName => 0,
AddTableFocus::InputColumnName => 1,
AddTableFocus::InputColumnType => 2,
// If focus is elsewhere, default to the first field for canvas rendering logic
_ => 0,
}
}
fn current_cursor_pos(&self) -> usize {
match self.current_focus {
AddTableFocus::InputTableName => self.table_name_cursor_pos,
AddTableFocus::InputColumnName => self.column_name_cursor_pos,
AddTableFocus::InputColumnType => self.column_type_cursor_pos,
_ => 0, // Default if focus is not on an input field
}
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
vec![&self.table_name_input, &self.column_name_input, &self.column_type_input]
}
fn get_current_input(&self) -> &str {
match self.current_focus {
AddTableFocus::InputTableName => &self.table_name_input,
AddTableFocus::InputColumnName => &self.column_name_input,
AddTableFocus::InputColumnType => &self.column_type_input,
_ => "", // Should not happen if called correctly
}
}
fn get_current_input_mut(&mut self) -> &mut String {
match self.current_focus {
AddTableFocus::InputTableName => &mut self.table_name_input,
AddTableFocus::InputColumnName => &mut self.column_name_input,
AddTableFocus::InputColumnType => &mut self.column_type_input,
_ => &mut self.table_name_input,
}
}
fn fields(&self) -> Vec<&str> {
// These must match the order used in render_add_table
vec!["Table name", "Name", "Type"]
}
fn set_current_field(&mut self, index: usize) {
self.current_focus = match index {
0 => AddTableFocus::InputTableName,
1 => AddTableFocus::InputColumnName,
2 => AddTableFocus::InputColumnType,
_ => self.current_focus, // Stay on current focus if index is out of bounds
};
}
fn set_current_cursor_pos(&mut self, pos: usize) {
match self.current_focus {
AddTableFocus::InputTableName => self.table_name_cursor_pos = pos,
AddTableFocus::InputColumnName => self.column_name_cursor_pos = pos,
AddTableFocus::InputColumnType => self.column_type_cursor_pos = pos,
_ => {} // Do nothing if focus is not on an input field
}
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
// --- Autocomplete Support (Not needed for this form yet) ---
fn get_suggestions(&self) -> Option<&[String]> {
None
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
None
}
}

View File

@@ -0,0 +1,178 @@
// src/state/pages/admin.rs
use ratatui::widgets::ListState;
use crate::state::pages::add_table::AddTableState;
// Define the focus states for the admin panel panes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AdminFocus {
#[default] // Default focus is on the profiles list
Profiles,
Tables,
Button1,
Button2,
Button3,
}
#[derive(Default, Clone, Debug)]
pub struct AdminState {
pub profiles: Vec<String>, // Holds profile names (used by non-admin view)
pub profile_list_state: ListState, // Tracks navigation highlight (>) in profiles
pub table_list_state: ListState, // Tracks navigation highlight (>) in tables
pub selected_profile_index: Option<usize>, // Index with [*] in profiles (persistent)
pub selected_table_index: Option<usize>, // Index with [*] in tables (persistent)
pub current_focus: AdminFocus, // Tracks which pane is focused
pub add_table_state: AddTableState,
}
impl AdminState {
/// Gets the index of the currently selected item.
pub fn get_selected_index(&self) -> Option<usize> {
self.profile_list_state.selected()
}
/// Gets the name of the currently selected profile.
pub fn get_selected_profile_name(&self) -> Option<&String> {
self.profile_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.profile_list_state.selected();
self.profiles = new_profiles;
if self.profiles.is_empty() {
self.profile_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.profile_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.profile_list_state.select(None);
return;
}
let i = match self.profile_list_state.selected() {
Some(i) => if i >= self.profiles.len() - 1 { 0 } else { i + 1 },
None => 0,
};
self.profile_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.profile_list_state.select(None);
return;
}
let i = match self.profile_list_state.selected() {
Some(i) => if i == 0 { self.profiles.len() - 1 } else { i - 1 },
None => self.profiles.len() - 1,
};
self.profile_list_state.select(Some(i));
}
/// Gets the index of the currently selected profile.
pub fn get_selected_profile_index(&self) -> Option<usize> {
self.profile_list_state.selected()
}
/// Gets the index of the currently selected table.
pub fn get_selected_table_index(&self) -> Option<usize> {
self.table_list_state.selected()
}
/// Selects a profile by index and resets table selection.
pub fn select_profile(&mut self, index: Option<usize>) {
self.profile_list_state.select(index);
self.table_list_state.select(None);
}
/// Selects a table by index.
pub fn select_table(&mut self, index: Option<usize>) {
self.table_list_state.select(index);
}
/// Selects the next profile, wrapping around.
/// `profile_count` should be the total number of profiles available.
pub fn next_profile(&mut self, profile_count: usize) {
if profile_count == 0 {
return;
}
let i = match self.get_selected_profile_index() {
Some(i) => {
if i >= profile_count - 1 {
0
} else {
i + 1
}
}
None => 0,
};
self.select_profile(Some(i)); // Use the helper method
}
/// Selects the previous profile, wrapping around.
/// `profile_count` should be the total number of profiles available.
pub fn previous_profile(&mut self, profile_count: usize) {
if profile_count == 0 {
return;
}
let i = match self.get_selected_profile_index() {
Some(i) => {
if i == 0 {
profile_count - 1
} else {
i - 1
}
}
None => 0, // Or profile_count - 1 if you prefer wrapping from None
};
self.select_profile(Some(i)); // Use the helper method
}
/// Selects the next table, wrapping around.
/// `table_count` should be the number of tables in the *currently selected* profile.
pub fn next_table(&mut self, table_count: usize) {
if table_count == 0 {
return;
}
let i = match self.get_selected_table_index() {
Some(i) => {
if i >= table_count - 1 {
0
} else {
i + 1
}
}
None => 0,
};
self.select_table(Some(i));
}
/// Selects the previous table, wrapping around.
/// `table_count` should be the number of tables in the *currently selected* profile.
pub fn previous_table(&mut self, table_count: usize) {
if table_count == 0 {
return;
}
let i = match self.get_selected_table_index() {
Some(i) => {
if i == 0 {
table_count - 1
} else {
i - 1
}
}
None => 0, // Or table_count - 1
};
self.select_table(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,12 +2,13 @@
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::app::highlight::HighlightState;
use crate::state::pages::canvas_state::CanvasState;
pub struct FormState { pub struct FormState {
pub id: i64, pub id: i64,
pub fields: Vec<String>, // Use Vec<String> for dynamic field names pub fields: Vec<String>,
pub values: Vec<String>, // Store field values dynamically pub values: Vec<String>,
pub current_field: usize, pub current_field: usize,
pub has_unsaved_changes: bool, pub has_unsaved_changes: bool,
pub current_cursor_pos: usize, pub current_cursor_pos: usize,
@@ -33,6 +34,7 @@ impl FormState {
area: Rect, area: Rect,
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
highlight_state: &HighlightState,
total_count: u64, total_count: u64,
current_position: u64, current_position: u64,
) { ) {
@@ -48,6 +50,7 @@ impl FormState {
&values, &values,
theme, theme,
is_edit_mode, is_edit_mode,
highlight_state,
total_count, total_count,
current_position, current_position,
); );

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

@@ -3,3 +3,4 @@
pub mod form; pub mod form;
pub mod login; pub mod login;
pub mod register; pub mod register;
pub mod add_table;

View File

@@ -0,0 +1,75 @@
// src/tui/functions/common/add_table.rs
use crate::state::pages::add_table::{
AddTableFocus, AddTableState, ColumnDefinition,
};
/// Handles the logic for adding a column when the "Add" button is activated.
///
/// Takes the mutable state and command message string.
/// Returns `Some(AddTableFocus)` indicating the desired focus state after a successful add,
/// or `None` if the action failed (e.g., validation error).
pub fn handle_add_column_action(
add_table_state: &mut AddTableState,
command_message: &mut String,
) -> Option<AddTableFocus> {
// Trim and create owned Strings from inputs
let table_name_in = add_table_state.table_name_input.trim();
let column_name_in = add_table_state.column_name_input.trim();
let column_type_in = add_table_state.column_type_input.trim();
// Validate all inputs needed for this combined action
let has_table_name = !table_name_in.is_empty();
let has_column_name = !column_name_in.is_empty();
let has_column_type = !column_type_in.is_empty();
match (has_table_name, has_column_name, has_column_type) {
// Case 1: Both column fields have input (Table name is optional here)
(_, true, true) => {
let mut msg = String::new();
// Optionally update table name if provided
if has_table_name {
add_table_state.table_name = table_name_in.to_string();
msg.push_str(&format!("Table name set to '{}'. ", add_table_state.table_name));
}
// Add the column
let new_column = ColumnDefinition {
name: column_name_in.to_string(),
data_type: column_type_in.to_string(),
};
add_table_state.columns.push(new_column.clone()); // Clone for msg
msg.push_str(&format!("Column '{}' added.", new_column.name));
*command_message = msg;
// Clear all inputs and reset cursors
add_table_state.table_name_input.clear();
add_table_state.column_name_input.clear();
add_table_state.column_type_input.clear();
add_table_state.table_name_cursor_pos = 0;
add_table_state.column_name_cursor_pos = 0;
add_table_state.column_type_cursor_pos = 0;
add_table_state.has_unsaved_changes = true;
Some(AddTableFocus::InputColumnName) // Focus for next column
}
// Case 2: Only one column field has input (Error)
(_, true, false) | (_, false, true) => {
*command_message = "Both Column Name and Type are required to add a column.".to_string();
None // Indicate validation failure
}
// Case 3: Only Table name has input (No column input)
(true, false, false) => {
add_table_state.table_name = table_name_in.to_string();
*command_message = format!("Table name set to '{}'.", add_table_state.table_name);
// Clear only table name input
add_table_state.table_name_input.clear();
add_table_state.table_name_cursor_pos = 0;
add_table_state.has_unsaved_changes = true;
Some(AddTableFocus::InputTableName) // Keep focus here
}
// Case 4: All fields are empty
(false, false, false) => {
*command_message = "No input provided.".to_string();
None
}
}
}

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,13 @@
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}, admin::render_add_table,
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,38 +16,77 @@ 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;
use crate::state::app::highlight::HighlightState;
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,
highlight_state: &HighlightState,
total_count: u64, total_count: u64,
current_position: u64, current_position: u64,
current_dir: &str, current_dir: &str,
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,
@@ -53,37 +94,35 @@ pub fn render_ui(
theme, theme,
register_state, register_state,
app_state, app_state,
register_state.current_field < 4 register_state.current_field < 4,
highlight_state,
); );
}else if app_state.ui.show_login { } else if app_state.ui.show_add_table {
render_login( render_add_table(
f, f,
main_content_area, main_content_area,
theme, theme,
auth_state,
app_state, app_state,
auth_state.current_field < 2 &mut admin_state.add_table_state,
login_state.current_field < 3,
highlight_state,
);
} else if app_state.ui.show_login {
render_login(
f,
main_content_area,
theme,
login_state,
app_state,
login_state.current_field < 2,
highlight_state,
); );
} 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,
app_state,
auth_state,
admin_state,
main_content_area, main_content_area,
theme, theme,
&app_state.profile_tree, &app_state.profile_tree,
@@ -142,13 +181,18 @@ pub fn render_ui(
&values, &values,
theme, theme,
is_edit_mode, is_edit_mode,
highlight_state,
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,68 +2,111 @@
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_add_table = 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;
let profile_names = app_state.profile_tree.profiles.iter()
.map(|p| p.name.clone())
.collect();
admin_state.set_profiles(profile_names);
}
AppView::AddTable => app_state.ui.show_add_table = 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,
&event_handler.highlight_state,
app_state.total_count, app_state.total_count,
app_state.current_position, app_state.current_position,
&app_state.current_dir, &app_state.current_dir,
&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,
); );
})?; })?;
@@ -74,6 +117,10 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
AppMode::Edit => { AppMode::Edit => {
terminal.show_cursor()?; terminal.show_cursor()?;
} }
AppMode::Highlight => {
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
terminal.show_cursor()?;
}
AppMode::ReadOnly => { AppMode::ReadOnly => {
if !app_state.ui.focus_outside_canvas { if !app_state.ui.focus_outside_canvas {
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
@@ -108,14 +155,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 +306,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 +321,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)