Compare commits
113 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c7a0a1ec0 | ||
|
|
a8eef8107b | ||
|
|
75cd942f39 | ||
|
|
fc04af148d | ||
|
|
d7d7fd614b | ||
|
|
10e9c3ead0 | ||
|
|
70678432c6 | ||
|
|
bb103fac6c | ||
|
|
0e1fc3f5fa | ||
|
|
7830ebdb3b | ||
|
|
b061dd3395 | ||
|
|
a6f2fa8a88 | ||
|
|
37f12ea6f0 | ||
|
|
e29b576102 | ||
|
|
b1b3cf6136 | ||
|
|
173c4c98b8 | ||
|
|
5a3067c8e5 | ||
|
|
803c748738 | ||
|
|
5879b40e8c | ||
|
|
c3decdac13 | ||
|
|
1baf89dde6 | ||
|
|
0219dc0ede | ||
|
|
1c662888c6 | ||
|
|
7fd1c1e41d | ||
|
|
1eaa716f42 | ||
|
|
704bb7401a | ||
|
|
b0c3fdbdc6 | ||
|
|
1d0ceb7045 | ||
|
|
ce85a050d3 | ||
|
|
94ecbcd639 | ||
|
|
ef1d8bcc9c | ||
|
|
1a7bbdc541 | ||
|
|
3dc5a89459 | ||
|
|
9f6268dbc9 | ||
|
|
2e912dd261 | ||
|
|
6d6fff474f | ||
|
|
e725c70570 | ||
|
|
07aeecbbfc | ||
|
|
9bfac04c44 | ||
|
|
6acf0d6378 | ||
|
|
1a09624242 | ||
|
|
9e36385e63 | ||
|
|
43edadde0c | ||
|
|
d577ff6715 | ||
|
|
ca75c90ee9 | ||
|
|
8e0fae26ee | ||
|
|
bee95c3755 | ||
|
|
306f4de14f | ||
|
|
b2fc681e73 | ||
|
|
060cff3f0f | ||
|
|
07c48985e4 | ||
|
|
3d266c2ad0 | ||
|
|
e2c326bf1e | ||
|
|
7f5b671084 | ||
|
|
3ccf71ed0f | ||
|
|
efb59c5571 | ||
|
|
26cf06df14 | ||
|
|
c82b62f72b | ||
|
|
87cdb8048d | ||
|
|
f71498703a | ||
|
|
94eea47b76 | ||
|
|
ac833294c4 | ||
|
|
81f0527085 | ||
|
|
dd4d9e88c6 | ||
|
|
f66d67c238 | ||
|
|
9cf25afa52 | ||
|
|
2ed2419f9e | ||
|
|
e19b30f4f4 | ||
|
|
f6e21b6a61 | ||
|
|
2180d8decf | ||
|
|
12aec72141 | ||
|
|
0568441e46 | ||
|
|
301189bd85 | ||
|
|
81767f376f | ||
|
|
e36b1817bc | ||
|
|
13d4db6bdc | ||
|
|
b5a5ebd7c0 | ||
|
|
6e04c1f267 | ||
|
|
a0d96cb87a | ||
|
|
4052a5b81b | ||
|
|
ed99ebf541 | ||
|
|
0a4f59cf8e | ||
|
|
fd6a9b73be | ||
|
|
dc994f6ee1 | ||
|
|
e234dd1785 | ||
|
|
6e0943f0cc | ||
|
|
9622e0bd3c | ||
|
|
ee666e91ed | ||
|
|
4f8f2f4a40 | ||
|
|
f21953147b | ||
|
|
48b2658b55 | ||
|
|
37b08fdd10 | ||
|
|
d4efdf4833 | ||
|
|
b408abe8c6 | ||
|
|
722c63af54 | ||
|
|
4601ba4094 | ||
|
|
3e2b8a36df | ||
|
|
11214734ae | ||
|
|
92045a4e67 | ||
|
|
9564bd8524 | ||
|
|
ad64df2ec3 | ||
|
|
aab11c1cba | ||
|
|
1fe139e0c5 | ||
|
|
4ced1a36d4 | ||
|
|
45fff34c4c | ||
|
|
c84fa4a692 | ||
|
|
eba3f56ba3 | ||
|
|
71ab588c16 | ||
|
|
195375c083 | ||
|
|
34dafcc23e | ||
|
|
507f86fcf1 | ||
|
|
f40654d2c4 | ||
|
|
cd32c175a4 |
@@ -4,3 +4,5 @@ RUST_DB_USER=multi_psql_dev
|
|||||||
RUST_DB_PASSWORD=3
|
RUST_DB_PASSWORD=3
|
||||||
RUST_DB_HOST=localhost
|
RUST_DB_HOST=localhost
|
||||||
RUST_DB_PORT=5432
|
RUST_DB_PORT=5432
|
||||||
|
|
||||||
|
JWT_SECRET=<YOUR-JWT-HERE>
|
||||||
|
|||||||
72
Cargo.lock
generated
72
Cargo.lock
generated
@@ -170,9 +170,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "async-trait"
|
name = "async-trait"
|
||||||
version = "0.1.87"
|
version = "0.1.88"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97"
|
checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -421,8 +421,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "client"
|
name = "client"
|
||||||
version = "0.2.0"
|
version = "0.3.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
"common",
|
"common",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"dirs 6.0.0",
|
"dirs 6.0.0",
|
||||||
@@ -457,7 +458,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "common"
|
name = "common"
|
||||||
version = "0.2.0"
|
version = "0.3.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"prost",
|
"prost",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -1024,8 +1025,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
|
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
"wasi 0.11.0+wasi-snapshot-preview1",
|
||||||
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1541,6 +1544,21 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jsonwebtoken"
|
||||||
|
version = "9.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"js-sys",
|
||||||
|
"pem",
|
||||||
|
"ring",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"simple_asn1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lasso"
|
name = "lasso"
|
||||||
version = "0.7.3"
|
version = "0.7.3"
|
||||||
@@ -1928,6 +1946,16 @@ version = "1.0.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pem"
|
||||||
|
version = "3.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pem-rfc7468"
|
name = "pem-rfc7468"
|
||||||
version = "0.7.0"
|
version = "0.7.0"
|
||||||
@@ -2345,6 +2373,20 @@ dependencies = [
|
|||||||
"tstr",
|
"tstr",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ring"
|
||||||
|
version = "0.17.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"getrandom 0.2.15",
|
||||||
|
"libc",
|
||||||
|
"untrusted",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rsa"
|
name = "rsa"
|
||||||
version = "0.9.7"
|
version = "0.9.7"
|
||||||
@@ -2547,13 +2589,14 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "server"
|
name = "server"
|
||||||
version = "0.2.0"
|
version = "0.3.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bcrypt",
|
"bcrypt",
|
||||||
"chrono",
|
"chrono",
|
||||||
"common",
|
"common",
|
||||||
"dashmap",
|
"dashmap",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
|
"jsonwebtoken",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
"prost",
|
"prost",
|
||||||
"regex",
|
"regex",
|
||||||
@@ -2641,6 +2684,18 @@ dependencies = [
|
|||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simple_asn1"
|
||||||
|
version = "0.6.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
|
||||||
|
dependencies = [
|
||||||
|
"num-bigint",
|
||||||
|
"num-traits",
|
||||||
|
"thiserror 2.0.12",
|
||||||
|
"time",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sized-chunks"
|
name = "sized-chunks"
|
||||||
version = "0.6.5"
|
version = "0.6.5"
|
||||||
@@ -3521,6 +3576,12 @@ version = "0.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
|
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "untrusted"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "url"
|
name = "url"
|
||||||
version = "2.5.4"
|
version = "2.5.4"
|
||||||
@@ -3551,6 +3612,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
|
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom 0.3.1",
|
"getrandom 0.3.1",
|
||||||
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ resolver = "2"
|
|||||||
[workspace.package]
|
[workspace.package]
|
||||||
# TODO: idk how to do the name, fix later
|
# TODO: idk how to do the name, fix later
|
||||||
# name = "Multieko2"
|
# name = "Multieko2"
|
||||||
version = "0.2.0"
|
version = "0.3.3"
|
||||||
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>"]
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
async-trait = "0.1.88"
|
||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
|
|
||||||
crossterm = "0.28.1"
|
crossterm = "0.28.1"
|
||||||
|
|||||||
5
client/src/components/auth.rs
Normal file
5
client/src/components/auth.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
// src/components/form.rs
|
||||||
|
pub mod login;
|
||||||
|
pub mod register;
|
||||||
|
|
||||||
|
pub use login::*;
|
||||||
146
client/src/components/auth/login.rs
Normal file
146
client/src/components/auth/login.rs
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
// src/components/auth/login.rs
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
config::colors::themes::Theme,
|
||||||
|
state::pages::auth::AuthState,
|
||||||
|
components::common::dialog,
|
||||||
|
state::state::AppState,
|
||||||
|
};
|
||||||
|
use crate::modes::handlers::mode_manager::AppMode;
|
||||||
|
use ratatui::{
|
||||||
|
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
|
||||||
|
style::{Style, Modifier, Color},
|
||||||
|
widgets::{Block, BorderType, Borders, Paragraph},
|
||||||
|
Frame,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn render_login(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: Rect,
|
||||||
|
theme: &Theme,
|
||||||
|
state: &AuthState,
|
||||||
|
app_state: &AppState,
|
||||||
|
is_edit_mode: bool,
|
||||||
|
) {
|
||||||
|
// Main container
|
||||||
|
let block = Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Plain)
|
||||||
|
.border_style(Style::default().fg(theme.border))
|
||||||
|
.title(" Login ")
|
||||||
|
.style(Style::default().bg(theme.bg));
|
||||||
|
|
||||||
|
f.render_widget(block, area);
|
||||||
|
|
||||||
|
let inner_area = area.inner(Margin {
|
||||||
|
horizontal: 1,
|
||||||
|
vertical: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Layout chunks
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(4), // Form (2 fields + padding)
|
||||||
|
Constraint::Length(1), // Error message
|
||||||
|
Constraint::Length(3), // Buttons
|
||||||
|
])
|
||||||
|
.split(inner_area);
|
||||||
|
|
||||||
|
// --- FORM RENDERING ---
|
||||||
|
crate::components::handlers::canvas::render_canvas(
|
||||||
|
f,
|
||||||
|
chunks[0],
|
||||||
|
state,
|
||||||
|
&["Username/Email", "Password"],
|
||||||
|
&state.current_field,
|
||||||
|
&[&state.username, &state.password],
|
||||||
|
theme,
|
||||||
|
is_edit_mode,
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- ERROR MESSAGE ---
|
||||||
|
if let Some(err) = &state.error_message {
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(err.as_str())
|
||||||
|
.style(Style::default().fg(Color::Red))
|
||||||
|
.alignment(Alignment::Center),
|
||||||
|
chunks[1],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- BUTTONS ---
|
||||||
|
let button_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||||
|
.split(chunks[2]);
|
||||||
|
|
||||||
|
// Login Button
|
||||||
|
let login_button_index = 0;
|
||||||
|
let login_active = if app_state.ui.focus_outside_canvas {
|
||||||
|
app_state.general.selected_item == login_button_index
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
let mut login_style = Style::default().fg(theme.fg);
|
||||||
|
let mut login_border = Style::default().fg(theme.border);
|
||||||
|
if login_active {
|
||||||
|
login_style = login_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
|
||||||
|
login_border = login_border.fg(theme.accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new("Login")
|
||||||
|
.style(login_style)
|
||||||
|
.alignment(Alignment::Center)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Plain)
|
||||||
|
.border_style(login_border),
|
||||||
|
),
|
||||||
|
button_chunks[0],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Return Button
|
||||||
|
let return_button_index = 1; // Assuming Return is the second general element
|
||||||
|
let return_active = if app_state.ui.focus_outside_canvas {
|
||||||
|
app_state.general.selected_item == return_button_index
|
||||||
|
} else {
|
||||||
|
false // Not active if focus is in canvas or other modes
|
||||||
|
};
|
||||||
|
let mut return_style = Style::default().fg(theme.fg);
|
||||||
|
let mut return_border = Style::default().fg(theme.border);
|
||||||
|
if return_active {
|
||||||
|
return_style = return_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
|
||||||
|
return_border = return_border.fg(theme.accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new("Return")
|
||||||
|
.style(return_style)
|
||||||
|
.alignment(Alignment::Center)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Plain)
|
||||||
|
.border_style(return_border),
|
||||||
|
),
|
||||||
|
button_chunks[1],
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- DIALOG ---
|
||||||
|
// Check the correct field name for showing the dialog
|
||||||
|
if app_state.ui.dialog.dialog_show {
|
||||||
|
// Pass all 7 arguments correctly
|
||||||
|
dialog::render_dialog(
|
||||||
|
f,
|
||||||
|
f.area(),
|
||||||
|
theme,
|
||||||
|
&app_state.ui.dialog.dialog_title,
|
||||||
|
&app_state.ui.dialog.dialog_message,
|
||||||
|
&app_state.ui.dialog.dialog_buttons, // Pass buttons slice
|
||||||
|
app_state.ui.dialog.dialog_active_button_index, // Pass active index
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
0
client/src/components/auth/register.rs
Normal file
0
client/src/components/auth/register.rs
Normal file
@@ -2,7 +2,9 @@
|
|||||||
pub mod command_line;
|
pub mod command_line;
|
||||||
pub mod status_line;
|
pub mod status_line;
|
||||||
pub mod background;
|
pub mod background;
|
||||||
|
pub mod dialog;
|
||||||
|
|
||||||
pub use command_line::*;
|
pub use command_line::*;
|
||||||
pub use status_line::*;
|
pub use status_line::*;
|
||||||
pub use background::*;
|
pub use background::*;
|
||||||
|
pub use dialog::*;
|
||||||
|
|||||||
146
client/src/components/common/dialog.rs
Normal file
146
client/src/components/common/dialog.rs
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
// src/components/common/dialog.rs
|
||||||
|
use crate::config::colors::themes::Theme;
|
||||||
|
use ratatui::{
|
||||||
|
layout::{Constraint, Direction, Layout, Margin, Rect},
|
||||||
|
prelude::Alignment,
|
||||||
|
style::{Modifier, Style},
|
||||||
|
text::{Line, Span, Text},
|
||||||
|
widgets::{Block, BorderType, Borders, Paragraph, Clear}, // Added Clear
|
||||||
|
Frame,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn render_dialog(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: Rect,
|
||||||
|
theme: &Theme,
|
||||||
|
dialog_title: &str,
|
||||||
|
dialog_message: &str,
|
||||||
|
dialog_buttons: &[String],
|
||||||
|
dialog_active_button_index: usize,
|
||||||
|
) {
|
||||||
|
let message_lines: Vec<_> = dialog_message.lines().collect();
|
||||||
|
let message_height = message_lines.len() as u16;
|
||||||
|
let button_row_height = if dialog_buttons.is_empty() { 0 } else { 3 };
|
||||||
|
let vertical_padding = 2; // Block borders (top/bottom)
|
||||||
|
let inner_vertical_margin = 2; // Margin inside block (top/bottom)
|
||||||
|
|
||||||
|
let required_inner_height =
|
||||||
|
message_height + button_row_height + inner_vertical_margin;
|
||||||
|
// Add block border height
|
||||||
|
let required_total_height = required_inner_height + vertical_padding;
|
||||||
|
|
||||||
|
// Use a fixed percentage width, clamped to min/max
|
||||||
|
let width_percentage: u16 = 60;
|
||||||
|
let dialog_width = (area.width * width_percentage / 100)
|
||||||
|
.max(20) // Minimum width
|
||||||
|
.min(area.width); // Maximum width
|
||||||
|
|
||||||
|
// Ensure height doesn't exceed available area
|
||||||
|
let dialog_height = required_total_height.min(area.height);
|
||||||
|
|
||||||
|
// Calculate centered area manually
|
||||||
|
let dialog_x = area.x + (area.width.saturating_sub(dialog_width)) / 2;
|
||||||
|
let dialog_y = area.y + (area.height.saturating_sub(dialog_height)) / 2;
|
||||||
|
let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
|
||||||
|
|
||||||
|
// Clear the area first before drawing the dialog
|
||||||
|
f.render_widget(Clear, dialog_area);
|
||||||
|
|
||||||
|
let block = Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(Style::default().fg(theme.accent))
|
||||||
|
.title(format!(" {} ", dialog_title)) // Add padding to title
|
||||||
|
.style(Style::default().bg(theme.bg));
|
||||||
|
|
||||||
|
f.render_widget(block, dialog_area);
|
||||||
|
|
||||||
|
// Calculate inner area *after* defining the block
|
||||||
|
let inner_area = dialog_area.inner(Margin {
|
||||||
|
horizontal: 2, // Left/Right padding inside border
|
||||||
|
vertical: 1, // Top/Bottom padding inside border
|
||||||
|
});
|
||||||
|
|
||||||
|
// Layout for Message and Buttons
|
||||||
|
let mut constraints = vec![
|
||||||
|
// Allocate space for message, ensuring at least 1 line height
|
||||||
|
Constraint::Min(message_height.max(1)),
|
||||||
|
];
|
||||||
|
if button_row_height > 0 {
|
||||||
|
constraints.push(Constraint::Length(button_row_height));
|
||||||
|
}
|
||||||
|
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints(constraints)
|
||||||
|
.split(inner_area);
|
||||||
|
|
||||||
|
// Render Message
|
||||||
|
let message_text = Text::from(
|
||||||
|
message_lines
|
||||||
|
.into_iter()
|
||||||
|
.map(|l| Line::from(Span::styled(l, Style::default().fg(theme.fg))))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let message_paragraph =
|
||||||
|
Paragraph::new(message_text).alignment(Alignment::Center);
|
||||||
|
// Render message in the first chunk
|
||||||
|
f.render_widget(message_paragraph, chunks[0]);
|
||||||
|
|
||||||
|
// Render Buttons if they exist and there's a chunk for them
|
||||||
|
if !dialog_buttons.is_empty() && chunks.len() > 1 {
|
||||||
|
let button_area = chunks[1];
|
||||||
|
let button_count = dialog_buttons.len();
|
||||||
|
|
||||||
|
// Use Ratio for potentially more even distribution with few buttons
|
||||||
|
let button_constraints = std::iter::repeat(Constraint::Ratio(
|
||||||
|
1,
|
||||||
|
button_count as u32,
|
||||||
|
))
|
||||||
|
.take(button_count)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let button_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints(button_constraints)
|
||||||
|
.horizontal_margin(1) // Add space between buttons
|
||||||
|
.split(button_area);
|
||||||
|
|
||||||
|
for (i, button_label) in dialog_buttons.iter().enumerate() {
|
||||||
|
// Ensure we don't try to render into a non-existent chunk
|
||||||
|
if i >= button_chunks.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let is_active = i == dialog_active_button_index;
|
||||||
|
let (button_style, border_style) = if is_active {
|
||||||
|
(
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.highlight)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
Style::default().fg(theme.accent), // Highlight border
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
Style::default().fg(theme.fg),
|
||||||
|
Style::default().fg(theme.border), // Normal border
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let button_block = Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Plain)
|
||||||
|
.border_style(border_style);
|
||||||
|
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(button_label.as_str())
|
||||||
|
.block(button_block)
|
||||||
|
.style(button_style)
|
||||||
|
.alignment(Alignment::Center),
|
||||||
|
button_chunks[i],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// src/components/handlers/form.rs
|
// src/components/form/form.rs
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
widgets::{Paragraph, Block, Borders},
|
widgets::{Paragraph, Block, Borders},
|
||||||
layout::{Layout, Constraint, Direction, Rect, Margin, Alignment},
|
layout::{Layout, Constraint, Direction, Rect, Margin, Alignment},
|
||||||
@@ -6,13 +6,13 @@ use ratatui::{
|
|||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use crate::ui::form::FormState;
|
use crate::state::canvas_state::CanvasState;
|
||||||
use crate::components::handlers::canvas::render_canvas;
|
use crate::components::handlers::canvas::render_canvas;
|
||||||
|
|
||||||
pub fn render_form(
|
pub fn render_form(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
form_state: &FormState,
|
form_state: &impl CanvasState,
|
||||||
fields: &[&str],
|
fields: &[&str],
|
||||||
current_field: &usize,
|
current_field: &usize,
|
||||||
inputs: &[&String],
|
inputs: &[&String],
|
||||||
|
|||||||
@@ -8,12 +8,12 @@ use ratatui::{
|
|||||||
prelude::Alignment,
|
prelude::Alignment,
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use crate::ui::form::FormState;
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
pub fn render_canvas(
|
pub fn render_canvas(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
form_state: &FormState,
|
form_state: &impl CanvasState,
|
||||||
fields: &[&str],
|
fields: &[&str],
|
||||||
current_field: &usize,
|
current_field: &usize,
|
||||||
inputs: &[&String],
|
inputs: &[&String],
|
||||||
@@ -27,13 +27,16 @@ pub fn render_canvas(
|
|||||||
.split(area);
|
.split(area);
|
||||||
|
|
||||||
// Input container styling
|
// Input container styling
|
||||||
|
let border_style = if form_state.has_unsaved_changes() {
|
||||||
|
Style::default().fg(theme.warning)
|
||||||
|
} else if is_edit_mode {
|
||||||
|
Style::default().fg(theme.accent)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.secondary)
|
||||||
|
};
|
||||||
let input_container = Block::default()
|
let input_container = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_style(if is_edit_mode {
|
.border_style(border_style)
|
||||||
form_state.has_unsaved_changes.then(|| theme.warning).unwrap_or(theme.accent)
|
|
||||||
} else {
|
|
||||||
theme.secondary
|
|
||||||
})
|
|
||||||
.style(Style::default().bg(theme.bg));
|
.style(Style::default().bg(theme.bg));
|
||||||
|
|
||||||
// Input block dimensions
|
// Input block dimensions
|
||||||
@@ -81,7 +84,7 @@ pub fn render_canvas(
|
|||||||
f.render_widget(input_display, input_rows[i]);
|
f.render_widget(input_display, input_rows[i]);
|
||||||
|
|
||||||
if is_active {
|
if is_active {
|
||||||
let cursor_x = input_rows[i].x + form_state.current_cursor_pos as u16;
|
let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16;
|
||||||
let cursor_y = input_rows[i].y;
|
let cursor_y = input_rows[i].y;
|
||||||
f.set_cursor_position((cursor_x, cursor_y));
|
f.set_cursor_position((cursor_x, cursor_y));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// src/components/handlers/intro.rs
|
// src/components/intro/intro.rs
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::Style,
|
style::Style,
|
||||||
@@ -32,9 +32,9 @@ impl IntroState {
|
|||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Percentage(35),
|
Constraint::Percentage(40),
|
||||||
Constraint::Length(5),
|
Constraint::Length(5), // Increased to accommodate 3 buttons
|
||||||
Constraint::Percentage(35),
|
Constraint::Percentage(40),
|
||||||
])
|
])
|
||||||
.split(inner_area);
|
.split(inner_area);
|
||||||
|
|
||||||
@@ -48,10 +48,14 @@ impl IntroState {
|
|||||||
.alignment(Alignment::Center);
|
.alignment(Alignment::Center);
|
||||||
f.render_widget(title_para, chunks[1]);
|
f.render_widget(title_para, chunks[1]);
|
||||||
|
|
||||||
// Buttons
|
// Buttons - now with 3 options
|
||||||
let button_area = Layout::default()
|
let button_area = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
.constraints([
|
||||||
|
Constraint::Percentage(33),
|
||||||
|
Constraint::Percentage(33),
|
||||||
|
Constraint::Percentage(33),
|
||||||
|
])
|
||||||
.split(chunks[1].inner(Margin {
|
.split(chunks[1].inner(Margin {
|
||||||
horizontal: 1,
|
horizontal: 1,
|
||||||
vertical: 1
|
vertical: 1
|
||||||
@@ -71,6 +75,13 @@ impl IntroState {
|
|||||||
self.selected_option == 1,
|
self.selected_option == 1,
|
||||||
theme,
|
theme,
|
||||||
);
|
);
|
||||||
|
self.render_button(
|
||||||
|
f,
|
||||||
|
button_area[2],
|
||||||
|
"Login",
|
||||||
|
self.selected_option == 2,
|
||||||
|
theme,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_button(&self, f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
|
fn render_button(&self, f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
|
||||||
@@ -100,11 +111,11 @@ impl IntroState {
|
|||||||
f.render_widget(button, area);
|
f.render_widget(button, area);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn next_option(&mut self) {
|
pub fn next_option(&mut self) {
|
||||||
self.selected_option = (self.selected_option + 1) % 2;
|
self.selected_option = (self.selected_option + 1) % 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn previous_option(&mut self) {
|
pub fn previous_option(&mut self) {
|
||||||
self.selected_option = if self.selected_option == 0 { 1 } else { 0 };
|
self.selected_option = if self.selected_option == 0 { 2 } else { self.selected_option - 1 };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ pub mod intro;
|
|||||||
pub mod admin;
|
pub mod admin;
|
||||||
pub mod common;
|
pub mod common;
|
||||||
pub mod form;
|
pub mod form;
|
||||||
|
pub mod auth;
|
||||||
|
|
||||||
pub use handlers::*;
|
pub use handlers::*;
|
||||||
pub use intro::*;
|
pub use intro::*;
|
||||||
pub use admin::*;
|
pub use admin::*;
|
||||||
pub use common::*;
|
pub use common::*;
|
||||||
pub use form::*;
|
pub use form::*;
|
||||||
|
pub use auth::*;
|
||||||
|
|||||||
2
client/src/functions/common.rs
Normal file
2
client/src/functions/common.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
// src/functions/common.rs
|
||||||
|
|
||||||
6
client/src/functions/mod.rs
Normal file
6
client/src/functions/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
// src/functions/mod.rs
|
||||||
|
|
||||||
|
pub mod common;
|
||||||
|
pub mod modes;
|
||||||
|
|
||||||
|
pub use modes::*;
|
||||||
8
client/src/functions/modes.rs
Normal file
8
client/src/functions/modes.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
// src/functions/modes.rs
|
||||||
|
|
||||||
|
pub mod read_only;
|
||||||
|
pub mod edit;
|
||||||
|
|
||||||
|
|
||||||
|
pub use read_only::*;
|
||||||
|
pub use edit::*;
|
||||||
4
client/src/functions/modes/edit.rs
Normal file
4
client/src/functions/modes/edit.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
// src/functions/modes/edit.rs
|
||||||
|
|
||||||
|
pub mod form_e;
|
||||||
|
pub mod auth_e;
|
||||||
425
client/src/functions/modes/edit/auth_e.rs
Normal file
425
client/src/functions/modes/edit/auth_e.rs
Normal file
@@ -0,0 +1,425 @@
|
|||||||
|
// src/functions/modes/edit/auth_e.rs
|
||||||
|
|
||||||
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use crate::state::pages::{auth::AuthState, form::FormState};
|
||||||
|
use crate::tui::functions::common::form::{revert, save};
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use std::any::Any;
|
||||||
|
|
||||||
|
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||||
|
action: &str,
|
||||||
|
state: &mut S,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"save" | "revert" => {
|
||||||
|
if !state.has_unsaved_changes() {
|
||||||
|
return Ok("No changes to save or revert.".to_string());
|
||||||
|
}
|
||||||
|
if let Some(form_state) =
|
||||||
|
(state as &mut dyn Any).downcast_mut::<FormState>()
|
||||||
|
{
|
||||||
|
match action {
|
||||||
|
"save" => {
|
||||||
|
let outcome = save(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let message = format!("Save successful: {:?}", outcome); // Simple message for now
|
||||||
|
Ok(message)
|
||||||
|
}
|
||||||
|
"revert" => {
|
||||||
|
revert(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(format!(
|
||||||
|
"Action '{}' not implemented for this state type.",
|
||||||
|
action
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Ok(format!("Common action '{}' not handled here.", action)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_edit_action<S: CanvasState>(
|
||||||
|
action: &str,
|
||||||
|
key: KeyEvent,
|
||||||
|
state: &mut S,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"insert_char" => {
|
||||||
|
if let KeyCode::Char(c) = key.code {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.insert(cursor_pos, c);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_current_cursor_pos(cursor_pos + 1);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = state.current_cursor_pos();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Ok("Error: insert_char called without a char key."
|
||||||
|
.to_string());
|
||||||
|
}
|
||||||
|
Ok("working?".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"delete_char_backward" => {
|
||||||
|
if state.current_cursor_pos() > 0 {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.remove(cursor_pos - 1);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
let new_pos = cursor_pos - 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"delete_char_forward" => {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos < chars.len() {
|
||||||
|
chars.remove(cursor_pos);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = cursor_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"next_field" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = (current_field + 1) % num_fields;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"prev_field" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = if current_field == 0 {
|
||||||
|
num_fields - 1
|
||||||
|
} else {
|
||||||
|
current_field - 1
|
||||||
|
};
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_left" => {
|
||||||
|
let new_pos = state.current_cursor_pos().saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
if current_pos < current_input.len() {
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_up" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = current_field.saturating_sub(1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_down" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let new_field = (state.current_field() + 1).min(num_fields - 1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_first_line" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("Moved to first field".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_last_line" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let new_field = num_fields - 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("Moved to last field".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_next_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
let final_pos = new_pos.min(current_input.len());
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
|
||||||
|
let final_pos = if new_pos == current_pos {
|
||||||
|
find_word_end(current_input, new_pos + 1)
|
||||||
|
} else {
|
||||||
|
new_pos
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_valid_index = current_input.len().saturating_sub(1);
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_end(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("Moved to previous word end".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
CharType::Whitespace
|
||||||
|
} else if c.is_alphanumeric() {
|
||||||
|
CharType::Alphanumeric
|
||||||
|
} else {
|
||||||
|
CharType::Punctuation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos >= len {
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == initial_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
|
||||||
|
if get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos >= len {
|
||||||
|
return len.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos > 0 {
|
||||||
|
pos - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
440
client/src/functions/modes/edit/form_e.rs
Normal file
440
client/src/functions/modes/edit/form_e.rs
Normal file
@@ -0,0 +1,440 @@
|
|||||||
|
// src/functions/modes/edit/form_e.rs
|
||||||
|
|
||||||
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::tui::functions::common::form::{revert, save};
|
||||||
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use std::any::Any;
|
||||||
|
|
||||||
|
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||||
|
action: &str,
|
||||||
|
state: &mut S,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"save" | "revert" => {
|
||||||
|
if !state.has_unsaved_changes() {
|
||||||
|
return Ok(EventOutcome::Ok("No changes to save or revert.".to_string()));
|
||||||
|
}
|
||||||
|
if let Some(form_state) =
|
||||||
|
(state as &mut dyn Any).downcast_mut::<FormState>()
|
||||||
|
{
|
||||||
|
match action {
|
||||||
|
"save" => {
|
||||||
|
let save_result = save(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match save_result {
|
||||||
|
Ok(save_outcome) => {
|
||||||
|
let message = match save_outcome {
|
||||||
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
|
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
||||||
|
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
|
||||||
|
};
|
||||||
|
Ok(EventOutcome::DataSaved(save_outcome, message))
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"revert" => {
|
||||||
|
let revert_result = revert(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match revert_result {
|
||||||
|
Ok(message) => Ok(EventOutcome::Ok(message)),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(EventOutcome::Ok(format!(
|
||||||
|
"Action '{}' not implemented for this state type.",
|
||||||
|
action
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Ok(EventOutcome::Ok(format!("Common action '{}' not handled here.", action))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_edit_action<S: CanvasState>(
|
||||||
|
action: &str,
|
||||||
|
key: KeyEvent,
|
||||||
|
state: &mut S,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"insert_char" => {
|
||||||
|
if let KeyCode::Char(c) = key.code {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.insert(cursor_pos, c);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_current_cursor_pos(cursor_pos + 1);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = state.current_cursor_pos();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Ok("Error: insert_char called without a char key."
|
||||||
|
.to_string());
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"delete_char_backward" => {
|
||||||
|
if state.current_cursor_pos() > 0 {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.remove(cursor_pos - 1);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
let new_pos = cursor_pos - 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"delete_char_forward" => {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos < chars.len() {
|
||||||
|
chars.remove(cursor_pos);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = cursor_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"next_field" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = (current_field + 1) % num_fields;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"prev_field" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = if current_field == 0 {
|
||||||
|
num_fields - 1
|
||||||
|
} else {
|
||||||
|
current_field - 1
|
||||||
|
};
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_left" => {
|
||||||
|
let new_pos = state.current_cursor_pos().saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
if current_pos < current_input.len() {
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_up" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = current_field.saturating_sub(1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_down" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let new_field = (state.current_field() + 1).min(num_fields - 1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_first_line" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("Moved to first field".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_last_line" => {
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields > 0 {
|
||||||
|
let new_field = num_fields - 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(
|
||||||
|
(*ideal_cursor_column).min(max_pos),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok("Moved to last field".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_next_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
let final_pos = new_pos.min(current_input.len());
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
|
||||||
|
let final_pos = if new_pos == current_pos {
|
||||||
|
find_word_end(current_input, new_pos + 1)
|
||||||
|
} else {
|
||||||
|
new_pos
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_valid_index = current_input.len().saturating_sub(1);
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_end(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("Moved to previous word end".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
CharType::Whitespace
|
||||||
|
} else if c.is_alphanumeric() {
|
||||||
|
CharType::Alphanumeric
|
||||||
|
} else {
|
||||||
|
CharType::Punctuation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos >= len {
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == initial_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
|
||||||
|
if get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos >= len {
|
||||||
|
return len.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos > 0 {
|
||||||
|
pos - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
4
client/src/functions/modes/read_only.rs
Normal file
4
client/src/functions/modes/read_only.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
// src/functions/modes/read_only.rs
|
||||||
|
|
||||||
|
pub mod auth_ro;
|
||||||
|
pub mod form_ro;
|
||||||
367
client/src/functions/modes/read_only/auth_ro.rs
Normal file
367
client/src/functions/modes/read_only/auth_ro.rs
Normal file
@@ -0,0 +1,367 @@
|
|||||||
|
// src/functions/modes/read_only/auth_ro.rs
|
||||||
|
|
||||||
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use crate::state::state::AppState;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_action<S: CanvasState>(
|
||||||
|
action: &str,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
state: &mut S,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
|
command_message: &mut String,
|
||||||
|
) -> Result<String, Box<dyn Error>> {
|
||||||
|
match action {
|
||||||
|
"previous_entry" | "next_entry" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok(format!(
|
||||||
|
"Action '{}' should be handled by context-specific logic",
|
||||||
|
action
|
||||||
|
))
|
||||||
|
}
|
||||||
|
"move_up" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate.".to_string());
|
||||||
|
}
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = current_field.saturating_sub(1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
|
||||||
|
Ok("move up from functions/modes/read_only/auth_ro.rs".to_string())
|
||||||
|
}
|
||||||
|
"move_down" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate.".to_string());
|
||||||
|
}
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
|
||||||
|
if current_field == last_field_index {
|
||||||
|
// Already on the last field, move focus outside
|
||||||
|
app_state.ui.focus_outside_canvas = true;
|
||||||
|
app_state.general.selected_item = 0; // Focus first general item (e.g., Login button)
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok("Focus moved below canvas".to_string())
|
||||||
|
} else {
|
||||||
|
// Move to the next field within the canvas
|
||||||
|
let new_field = (current_field + 1).min(last_field_index);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
Ok("".to_string()) // Clear previous debug message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"move_first_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate to.".to_string());
|
||||||
|
}
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_last_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate to.".to_string());
|
||||||
|
}
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
state.set_current_field(last_field_index);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"exit_edit_mode" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
command_message.clear();
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_left" => {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = current_pos.saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
if !current_input.is_empty()
|
||||||
|
&& current_pos < current_input.len().saturating_sub(1)
|
||||||
|
{
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos =
|
||||||
|
find_next_word_start(current_input, state.current_cursor_pos());
|
||||||
|
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
|
||||||
|
let final_pos = if new_pos != current_pos {
|
||||||
|
new_pos
|
||||||
|
} else {
|
||||||
|
find_word_end(current_input, new_pos + 1)
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_valid_index = current_input.len().saturating_sub(1);
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_end(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("Moved to previous word end".to_string())
|
||||||
|
}
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = current_input.len().saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
} else {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok(format!("Unknown read-only action: {}", action))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
CharType::Whitespace
|
||||||
|
} else if c.is_alphanumeric() {
|
||||||
|
CharType::Alphanumeric
|
||||||
|
} else {
|
||||||
|
CharType::Punctuation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let current_pos = current_pos.min(chars.len());
|
||||||
|
|
||||||
|
if current_pos == chars.len() {
|
||||||
|
return current_pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next_start = find_next_word_start(text, current_pos);
|
||||||
|
|
||||||
|
if next_start >= chars.len() {
|
||||||
|
return chars.len().saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = next_start;
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
let original_pos = pos;
|
||||||
|
|
||||||
|
let current_type = get_char_type(chars[pos]);
|
||||||
|
if current_type != CharType::Whitespace {
|
||||||
|
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
return pos.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
if pos >= len {
|
||||||
|
return len.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if get_char_type(chars[pos]) != CharType::Whitespace {
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if pos == 0 && get_char_type(chars[0]) != CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos > 0 {
|
||||||
|
pos - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
353
client/src/functions/modes/read_only/form_ro.rs
Normal file
353
client/src/functions/modes/read_only/form_ro.rs
Normal file
@@ -0,0 +1,353 @@
|
|||||||
|
// src/functions/modes/read_only/form_ro.rs
|
||||||
|
|
||||||
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_action<S: CanvasState>(
|
||||||
|
action: &str,
|
||||||
|
state: &mut S,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
|
command_message: &mut String,
|
||||||
|
) -> Result<String, Box<dyn Error>> {
|
||||||
|
match action {
|
||||||
|
"previous_entry" | "next_entry" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok(format!(
|
||||||
|
"Action '{}' should be handled by context-specific logic",
|
||||||
|
action
|
||||||
|
))
|
||||||
|
}
|
||||||
|
"move_up" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate.".to_string());
|
||||||
|
}
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = current_field.saturating_sub(1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_down" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate.".to_string());
|
||||||
|
}
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let new_field = (current_field + 1).min(num_fields - 1);
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_first_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate to.".to_string());
|
||||||
|
}
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_last_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = state.fields().len();
|
||||||
|
if num_fields == 0 {
|
||||||
|
return Ok("No fields to navigate to.".to_string());
|
||||||
|
}
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
state.set_current_field(last_field_index);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = if current_input.is_empty() {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
current_input.len().saturating_sub(1)
|
||||||
|
};
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"exit_edit_mode" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
command_message.clear();
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_left" => {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = current_pos.saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
if !current_input.is_empty()
|
||||||
|
&& current_pos < current_input.len().saturating_sub(1)
|
||||||
|
{
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos =
|
||||||
|
find_next_word_start(current_input, state.current_cursor_pos());
|
||||||
|
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
|
||||||
|
let final_pos = if new_pos != current_pos {
|
||||||
|
new_pos
|
||||||
|
} else {
|
||||||
|
find_word_end(current_input, new_pos + 1)
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_valid_index = current_input.len().saturating_sub(1);
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_start(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_end(
|
||||||
|
current_input,
|
||||||
|
state.current_cursor_pos(),
|
||||||
|
);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("Moved to previous word end".to_string())
|
||||||
|
}
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = current_input.len().saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
} else {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok(format!("Unknown read-only action: {}", action))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
CharType::Whitespace
|
||||||
|
} else if c.is_alphanumeric() {
|
||||||
|
CharType::Alphanumeric
|
||||||
|
} else {
|
||||||
|
CharType::Punctuation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let current_pos = current_pos.min(chars.len());
|
||||||
|
|
||||||
|
if current_pos == chars.len() {
|
||||||
|
return current_pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next_start = find_next_word_start(text, current_pos);
|
||||||
|
|
||||||
|
if next_start >= chars.len() {
|
||||||
|
return chars.len().saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = next_start;
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
let original_pos = pos;
|
||||||
|
|
||||||
|
let current_type = get_char_type(chars[pos]);
|
||||||
|
if current_type != CharType::Whitespace {
|
||||||
|
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
return pos.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
if pos >= len {
|
||||||
|
return len.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if get_char_type(chars[pos]) != CharType::Whitespace {
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if pos == 0 && get_char_type(chars[0]) != CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos > 0 {
|
||||||
|
pos - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ pub mod config;
|
|||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod components;
|
pub mod components;
|
||||||
pub mod modes;
|
pub mod modes;
|
||||||
|
pub mod functions;
|
||||||
|
pub mod services;
|
||||||
|
|
||||||
pub use ui::run_ui;
|
pub use ui::run_ui;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// src/client/modes/canvas.rs
|
// src/client/modes/canvas.rs
|
||||||
pub mod edit;
|
pub mod edit;
|
||||||
pub mod common;
|
pub mod common_mode;
|
||||||
pub mod read_only;
|
pub mod read_only;
|
||||||
|
|||||||
85
client/src/modes/canvas/common_mode.rs
Normal file
85
client/src/modes/canvas/common_mode.rs
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
// src/modes/canvas/common_mode.rs
|
||||||
|
|
||||||
|
use crate::tui::terminal::core::TerminalCore;
|
||||||
|
use crate::state::pages::{form::FormState, auth::AuthState};
|
||||||
|
use crate::state::state::AppState;
|
||||||
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::services::auth::AuthClient;
|
||||||
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use crate::tui::functions::common::{
|
||||||
|
form::{save as form_save, revert as form_revert},
|
||||||
|
login::{save as login_save, revert as login_revert}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub async fn handle_core_action(
|
||||||
|
action: &str,
|
||||||
|
form_state: &mut FormState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
auth_client: &mut AuthClient,
|
||||||
|
terminal: &mut TerminalCore,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"save" => {
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
let message = login_save(auth_state, auth_client, app_state).await?;
|
||||||
|
Ok(EventOutcome::Ok(message))
|
||||||
|
} else {
|
||||||
|
let save_outcome = form_save(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
).await?;
|
||||||
|
let message = match save_outcome {
|
||||||
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
|
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
||||||
|
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
|
||||||
|
};
|
||||||
|
Ok(EventOutcome::DataSaved(save_outcome, message))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"force_quit" => {
|
||||||
|
terminal.cleanup()?;
|
||||||
|
Ok(EventOutcome::Exit("Force exiting without saving.".to_string()))
|
||||||
|
},
|
||||||
|
"save_and_quit" => {
|
||||||
|
let message = if app_state.ui.show_login {
|
||||||
|
login_save(auth_state, auth_client, app_state).await?
|
||||||
|
} else {
|
||||||
|
let save_outcome = form_save(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
).await?;
|
||||||
|
match save_outcome {
|
||||||
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
|
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
||||||
|
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
terminal.cleanup()?;
|
||||||
|
Ok(EventOutcome::Exit(format!("{}. Exiting application.", message)))
|
||||||
|
},
|
||||||
|
"revert" => {
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
let message = login_revert(auth_state, app_state).await;
|
||||||
|
Ok(EventOutcome::Ok(message))
|
||||||
|
} else {
|
||||||
|
let message = form_revert(
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
).await?;
|
||||||
|
Ok(EventOutcome::Ok(message))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => Ok(EventOutcome::Ok(format!("Core action not handled: {}", action))),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,474 +1,120 @@
|
|||||||
// src/modes/canvas/edit.rs
|
// src/modes/canvas/edit.rs
|
||||||
|
|
||||||
// TODO THIS is freaking bloated with functions it never uses REFACTOR 200 LOC can be gone
|
|
||||||
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
|
|
||||||
use crate::tui::terminal::{
|
|
||||||
grpc_client::GrpcClient,
|
|
||||||
};
|
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::ui::handlers::form::FormState;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::modes::canvas::common;
|
use crate::state::pages::{auth::AuthState, form::FormState};
|
||||||
|
use crate::functions::modes::edit::{auth_e, form_e};
|
||||||
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
|
||||||
pub async fn handle_edit_event_internal(
|
pub async fn handle_edit_event(
|
||||||
|
is_auth_context: bool,
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
is_saved: &mut bool,
|
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(&config.keybindings.global, key.code, key.modifiers) {
|
|
||||||
// Ignore in edit mode and process as normal input
|
// Global command mode check
|
||||||
handle_edit_specific_input(key, form_state, ideal_cursor_column);
|
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
|
||||||
|
&config.keybindings.global,
|
||||||
|
key.code,
|
||||||
|
key.modifiers
|
||||||
|
) {
|
||||||
|
*command_message = "Switching to Command Mode...".to_string();
|
||||||
return Ok(command_message.clone());
|
return Ok(command_message.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check common actions first
|
// Common actions (save/revert)
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.common, key.code, key.modifiers) {
|
if let Some(action) = config.get_action_for_key_in_mode(
|
||||||
return execute_common_action(
|
&config.keybindings.common,
|
||||||
action,
|
key.code,
|
||||||
form_state,
|
key.modifiers
|
||||||
grpc_client,
|
) {
|
||||||
is_saved,
|
if matches!(action, "save" | "revert") {
|
||||||
current_position,
|
let message = if is_auth_context {
|
||||||
total_count,
|
auth_e::execute_common_action(
|
||||||
).await;
|
action,
|
||||||
|
auth_state, // Concrete AuthState
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count
|
||||||
|
).await
|
||||||
|
} else {
|
||||||
|
form_e::execute_common_action(
|
||||||
|
action,
|
||||||
|
form_state, // Concrete FormState
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count
|
||||||
|
).await
|
||||||
|
.map(|outcome| match outcome {
|
||||||
|
EventOutcome::Ok(msg) => msg,
|
||||||
|
EventOutcome::Exit(msg) => format!("Exit requested: {}", msg), // Or handle differently
|
||||||
|
EventOutcome::DataSaved(save_outcome, msg) => format!("Data saved ({:?}): {}", save_outcome, msg),
|
||||||
|
EventOutcome::ButtonSelected { context, index } => {
|
||||||
|
"Unexpected action in edit mode".to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}?;
|
||||||
|
return Ok(message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Edit-specific actions
|
||||||
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
|
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
|
||||||
return execute_edit_action(
|
return if is_auth_context {
|
||||||
action,
|
auth_e::execute_edit_action(
|
||||||
form_state,
|
action,
|
||||||
ideal_cursor_column,
|
key,
|
||||||
grpc_client, // Changed from AppTerminal
|
auth_state, // Full access to AuthState fields
|
||||||
is_saved,
|
ideal_cursor_column,
|
||||||
current_position,
|
grpc_client,
|
||||||
total_count,
|
current_position,
|
||||||
).await;
|
total_count
|
||||||
|
).await
|
||||||
|
} else {
|
||||||
|
form_e::execute_edit_action(
|
||||||
|
action,
|
||||||
|
key,
|
||||||
|
form_state, // Full access to FormState fields
|
||||||
|
ideal_cursor_column,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count
|
||||||
|
).await
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_edit_specific_input(
|
// Character insertion
|
||||||
key,
|
if let KeyCode::Char(_) = key.code {
|
||||||
form_state,
|
return if is_auth_context {
|
||||||
ideal_cursor_column,
|
auth_e::execute_edit_action(
|
||||||
);
|
"insert_char",
|
||||||
|
key,
|
||||||
|
auth_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count
|
||||||
|
).await
|
||||||
|
} else {
|
||||||
|
form_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
form_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count
|
||||||
|
).await
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
Ok(command_message.clone())
|
Ok(command_message.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_common_action(
|
|
||||||
action: &str,
|
|
||||||
form_state: &mut FormState,
|
|
||||||
grpc_client: &mut GrpcClient,
|
|
||||||
is_saved: &mut bool,
|
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
|
||||||
"save" => {
|
|
||||||
common::save(
|
|
||||||
form_state,
|
|
||||||
grpc_client,
|
|
||||||
is_saved,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await
|
|
||||||
},
|
|
||||||
"revert" => {
|
|
||||||
common::revert(
|
|
||||||
form_state,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await
|
|
||||||
},
|
|
||||||
"move_up" | "move_down" => {
|
|
||||||
// Reuse edit mode's existing logic
|
|
||||||
execute_edit_action(
|
|
||||||
action,
|
|
||||||
form_state,
|
|
||||||
&mut 0, // Dummy ideal_cursor_column (not used here)
|
|
||||||
grpc_client,
|
|
||||||
is_saved,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await
|
|
||||||
},
|
|
||||||
_ => Ok(format!("Common action not handled: {}", action)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_edit_specific_input(
|
|
||||||
key: KeyEvent,
|
|
||||||
form_state: &mut FormState,
|
|
||||||
ideal_cursor_column: &mut usize,
|
|
||||||
) {
|
|
||||||
match key.code {
|
|
||||||
KeyCode::Char(c) => {
|
|
||||||
let cursor_pos = form_state.current_cursor_pos;
|
|
||||||
let field_value = form_state.get_current_input_mut();
|
|
||||||
let mut chars: Vec<char> = field_value.chars().collect();
|
|
||||||
if cursor_pos <= chars.len() {
|
|
||||||
chars.insert(cursor_pos, c);
|
|
||||||
*field_value = chars.into_iter().collect();
|
|
||||||
form_state.current_cursor_pos = cursor_pos + 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
form_state.has_unsaved_changes = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Backspace => {
|
|
||||||
if form_state.current_cursor_pos > 0 {
|
|
||||||
let cursor_pos = form_state.current_cursor_pos;
|
|
||||||
let field_value = form_state.get_current_input_mut();
|
|
||||||
let mut chars: Vec<char> = field_value.chars().collect();
|
|
||||||
if cursor_pos <= chars.len() && cursor_pos > 0 {
|
|
||||||
chars.remove(cursor_pos - 1);
|
|
||||||
*field_value = chars.into_iter().collect();
|
|
||||||
form_state.current_cursor_pos = cursor_pos - 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
form_state.has_unsaved_changes = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Delete => {
|
|
||||||
let cursor_pos = form_state.current_cursor_pos;
|
|
||||||
let field_value = form_state.get_current_input_mut();
|
|
||||||
let chars: Vec<char> = field_value.chars().collect();
|
|
||||||
if cursor_pos < chars.len() {
|
|
||||||
let mut new_chars = chars.clone();
|
|
||||||
new_chars.remove(cursor_pos);
|
|
||||||
*field_value = new_chars.into_iter().collect();
|
|
||||||
form_state.has_unsaved_changes = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Tab => {
|
|
||||||
if key.modifiers.contains(KeyModifiers::SHIFT) {
|
|
||||||
if form_state.current_field == 0 {
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
} else {
|
|
||||||
form_state.current_field = form_state.current_field.saturating_sub(1);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
|
|
||||||
}
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
}
|
|
||||||
KeyCode::Enter => {
|
|
||||||
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn execute_edit_action(
|
|
||||||
action: &str,
|
|
||||||
form_state: &mut FormState,
|
|
||||||
ideal_cursor_column: &mut usize,
|
|
||||||
grpc_client: &mut GrpcClient, // Changed from AppTerminal
|
|
||||||
is_saved: &mut bool,
|
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
|
||||||
"save" => {
|
|
||||||
common::save(
|
|
||||||
form_state,
|
|
||||||
grpc_client, // Changed from AppTerminal
|
|
||||||
is_saved,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await
|
|
||||||
},
|
|
||||||
"move_left" => {
|
|
||||||
form_state.current_cursor_pos = form_state.current_cursor_pos.saturating_sub(1);
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_right" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if form_state.current_cursor_pos < current_input.len() {
|
|
||||||
form_state.current_cursor_pos += 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_up" => {
|
|
||||||
if form_state.current_field == 0 {
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
} else {
|
|
||||||
form_state.current_field = form_state.current_field.saturating_sub(1);
|
|
||||||
}
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_down" => {
|
|
||||||
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_line_start" => {
|
|
||||||
form_state.current_cursor_pos = 0;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_line_end" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
form_state.current_cursor_pos = current_input.len();
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_first_line" => {
|
|
||||||
form_state.current_field = 0;
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("Moved to first line".to_string())
|
|
||||||
}
|
|
||||||
"move_last_line" => {
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("Moved to last line".to_string())
|
|
||||||
}
|
|
||||||
// Word movement actions
|
|
||||||
"move_word_next" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos.min(current_input.len());
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_end" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos.min(current_input.len());
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_prev" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_end_prev" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
// Edit-specific actions that can be bound to keys
|
|
||||||
"delete_char_forward" => {
|
|
||||||
let cursor_pos = form_state.current_cursor_pos;
|
|
||||||
let field_value = form_state.get_current_input_mut();
|
|
||||||
let chars: Vec<char> = field_value.chars().collect();
|
|
||||||
if cursor_pos < chars.len() {
|
|
||||||
let mut new_chars = chars.clone();
|
|
||||||
new_chars.remove(cursor_pos);
|
|
||||||
*field_value = new_chars.into_iter().collect();
|
|
||||||
form_state.has_unsaved_changes = true;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"delete_char_backward" => {
|
|
||||||
if form_state.current_cursor_pos > 0 {
|
|
||||||
let cursor_pos = form_state.current_cursor_pos;
|
|
||||||
let field_value = form_state.get_current_input_mut();
|
|
||||||
let mut chars: Vec<char> = field_value.chars().collect();
|
|
||||||
if cursor_pos <= chars.len() && cursor_pos > 0 {
|
|
||||||
chars.remove(cursor_pos - 1);
|
|
||||||
*field_value = chars.into_iter().collect();
|
|
||||||
form_state.current_cursor_pos = cursor_pos - 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
form_state.has_unsaved_changes = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"insert_char" => {
|
|
||||||
// This could be expanded to allow configurable character insertion
|
|
||||||
// For now, it's a placeholder that would need additional parameters
|
|
||||||
Ok("Character insertion requires configuration".to_string())
|
|
||||||
}
|
|
||||||
"next_field" => {
|
|
||||||
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"prev_field" => {
|
|
||||||
if form_state.current_field == 0 {
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
} else {
|
|
||||||
form_state.current_field = form_state.current_field.saturating_sub(1);
|
|
||||||
}
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = current_input.len();
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
// Fallback for unrecognized actions
|
|
||||||
_ => Ok(format!("Unknown action: {}", action)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reuse these character and word navigation helper functions
|
|
||||||
#[derive(PartialEq)]
|
|
||||||
enum CharType {
|
|
||||||
Whitespace,
|
|
||||||
Alphanumeric,
|
|
||||||
Punctuation,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_char_type(c: char) -> CharType {
|
|
||||||
if c.is_whitespace() {
|
|
||||||
CharType::Whitespace
|
|
||||||
} else if c.is_alphanumeric() {
|
|
||||||
CharType::Alphanumeric
|
|
||||||
} else {
|
|
||||||
CharType::Punctuation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos >= chars.len() {
|
|
||||||
return current_pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos;
|
|
||||||
let initial_type = get_char_type(chars[pos]);
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if current_pos >= chars.len() - 1 {
|
|
||||||
return chars.len() - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos;
|
|
||||||
|
|
||||||
if get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let current_type = get_char_type(chars[pos]);
|
|
||||||
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
|
|
||||||
pos += 1;
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos >= chars.len() {
|
|
||||||
return chars.len() - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos == 0 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos.saturating_sub(1);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if get_char_type(chars[pos]) != CharType::Whitespace {
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos <= 1 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos.saturating_sub(1);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos > 0 && get_char_type(chars[pos]) != CharType::Whitespace {
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos > 0 {
|
|
||||||
pos -= 1;
|
|
||||||
let prev_word_type = get_char_type(chars[pos]);
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos < chars.len() - 1 &&
|
|
||||||
get_char_type(chars[pos + 1]) == prev_word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
// src/modes/handlers/read_only.rs
|
// src/modes/canvas/read_only.rs
|
||||||
|
|
||||||
use crossterm::event::{KeyEvent};
|
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::ui::handlers::form::FormState;
|
|
||||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
use crate::tui::terminal::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
#[derive(PartialEq)]
|
use crate::state::pages::auth::AuthState;
|
||||||
enum CharType {
|
use crate::state::pages::form::FormState;
|
||||||
Whitespace,
|
use crate::state::state::AppState;
|
||||||
Alphanumeric,
|
use crate::functions::modes::read_only::{auth_ro, form_ro};
|
||||||
Punctuation,
|
use crossterm::event::KeyEvent;
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_read_only_event(
|
pub async fn handle_read_only_event(
|
||||||
|
app_state: &mut AppState,
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
@@ -25,7 +24,6 @@ pub async fn handle_read_only_event(
|
|||||||
edit_mode_cooldown: &mut bool,
|
edit_mode_cooldown: &mut bool,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||||
// Check for entering Edit mode from Read-Only mode
|
|
||||||
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
|
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
|
||||||
*edit_mode_cooldown = true;
|
*edit_mode_cooldown = true;
|
||||||
*command_message = "Entering Edit mode".to_string();
|
*command_message = "Entering Edit mode".to_string();
|
||||||
@@ -33,426 +31,193 @@ pub async fn handle_read_only_event(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
|
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
|
||||||
let current_input = form_state.get_current_input();
|
let (current_input, current_pos) = if app_state.ui.show_login {
|
||||||
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
|
(
|
||||||
form_state.current_cursor_pos += 1;
|
auth_state.get_current_input(),
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
auth_state.current_cursor_pos(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
form_state.get_current_input(),
|
||||||
|
form_state.current_cursor_pos(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if !current_input.is_empty() && current_pos < current_input.len() {
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
auth_state.set_current_cursor_pos(current_pos + 1);
|
||||||
|
*ideal_cursor_column = auth_state.current_cursor_pos();
|
||||||
|
} else {
|
||||||
|
form_state.set_current_cursor_pos(current_pos + 1);
|
||||||
|
*ideal_cursor_column = form_state.current_cursor_pos();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
*edit_mode_cooldown = true;
|
*edit_mode_cooldown = true;
|
||||||
*command_message = "Entering Edit mode (after cursor)".to_string();
|
*command_message = "Entering Edit mode (after cursor)".to_string();
|
||||||
return Ok((false, command_message.clone()));
|
return Ok((false, command_message.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle Read-Only mode keybindings
|
const CONTEXT_ACTIONS_FORM: &[&str] = &[
|
||||||
|
"previous_entry",
|
||||||
|
"next_entry",
|
||||||
|
];
|
||||||
|
const CONTEXT_ACTIONS_LOGIN: &[&str] = &[
|
||||||
|
"previous_entry",
|
||||||
|
"next_entry",
|
||||||
|
];
|
||||||
|
|
||||||
if key.modifiers.is_empty() {
|
if key.modifiers.is_empty() {
|
||||||
key_sequence_tracker.add_key(key.code);
|
key_sequence_tracker.add_key(key.code);
|
||||||
let sequence = key_sequence_tracker.get_sequence();
|
let sequence = key_sequence_tracker.get_sequence();
|
||||||
|
|
||||||
// Try to match the current sequence against Read-Only mode bindings
|
|
||||||
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
|
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
|
||||||
let result = execute_action(
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
action,
|
crate::tui::functions::form::handle_action(
|
||||||
form_state,
|
action,
|
||||||
ideal_cursor_column,
|
form_state,
|
||||||
key_sequence_tracker,
|
grpc_client,
|
||||||
command_message,
|
current_position,
|
||||||
current_position,
|
total_count,
|
||||||
total_count,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
).await?;
|
.await?
|
||||||
key_sequence_tracker.reset();
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
return Ok((false, result));
|
crate::tui::functions::login::handle_action(
|
||||||
}
|
action,
|
||||||
|
auth_state,
|
||||||
// Check if this might be a prefix of a longer sequence
|
ideal_cursor_column,
|
||||||
if config.is_key_sequence_prefix(&sequence) {
|
)
|
||||||
return Ok((false, command_message.clone()));
|
.await?
|
||||||
}
|
} else if app_state.ui.show_login {
|
||||||
|
auth_ro::execute_action(
|
||||||
// Since it's not part of a multi-key sequence, check for a direct action
|
action,
|
||||||
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
|
app_state,
|
||||||
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
|
auth_state,
|
||||||
let result = execute_action(
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
form_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
key_sequence_tracker,
|
key_sequence_tracker,
|
||||||
command_message,
|
command_message,
|
||||||
current_position,
|
)
|
||||||
total_count,
|
.await?
|
||||||
grpc_client,
|
};
|
||||||
).await?;
|
key_sequence_tracker.reset();
|
||||||
|
return Ok((false, result));
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.is_key_sequence_prefix(&sequence) {
|
||||||
|
return Ok((false, command_message.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
|
crate::tui::functions::form::handle_action(
|
||||||
|
action,
|
||||||
|
form_state,
|
||||||
|
grpc_client,
|
||||||
|
current_position,
|
||||||
|
total_count,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
|
crate::tui::functions::login::handle_action(
|
||||||
|
action,
|
||||||
|
auth_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_login {
|
||||||
|
auth_ro::execute_action(
|
||||||
|
action,
|
||||||
|
app_state,
|
||||||
|
auth_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
form_ro::execute_action(
|
||||||
|
action,
|
||||||
|
form_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
};
|
||||||
key_sequence_tracker.reset();
|
key_sequence_tracker.reset();
|
||||||
return Ok((false, result));
|
return Ok((false, result));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
key_sequence_tracker.reset();
|
||||||
} else {
|
} else {
|
||||||
// If modifiers are pressed, check for direct key bindings
|
|
||||||
key_sequence_tracker.reset();
|
key_sequence_tracker.reset();
|
||||||
|
|
||||||
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
|
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
|
||||||
let result = execute_action(
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
action,
|
crate::tui::functions::form::handle_action(
|
||||||
form_state,
|
action,
|
||||||
ideal_cursor_column,
|
form_state,
|
||||||
key_sequence_tracker,
|
grpc_client,
|
||||||
command_message,
|
current_position,
|
||||||
current_position,
|
total_count,
|
||||||
total_count,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
).await?;
|
.await?
|
||||||
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
|
crate::tui::functions::login::handle_action(
|
||||||
|
action,
|
||||||
|
auth_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_login {
|
||||||
|
auth_ro::execute_action(
|
||||||
|
action,
|
||||||
|
app_state,
|
||||||
|
auth_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
form_ro::execute_action(
|
||||||
|
action,
|
||||||
|
form_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
};
|
||||||
return Ok((false, result));
|
return Ok((false, result));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show a helpful message when no binding was found
|
|
||||||
if !*edit_mode_cooldown {
|
if !*edit_mode_cooldown {
|
||||||
let default_key = "i".to_string();
|
let default_key = "i".to_string();
|
||||||
let edit_key = config.keybindings.read_only.get("enter_edit_mode_before")
|
let edit_key = config
|
||||||
|
.keybindings
|
||||||
|
.read_only
|
||||||
|
.get("enter_edit_mode_before")
|
||||||
.and_then(|keys| keys.first())
|
.and_then(|keys| keys.first())
|
||||||
.unwrap_or(&default_key);
|
.map(|k| k.to_string())
|
||||||
|
.unwrap_or(default_key);
|
||||||
*command_message = format!("Read-only mode - press {} to edit", edit_key);
|
*command_message = format!("Read-only mode - press {} to edit", edit_key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
*edit_mode_cooldown = false;
|
||||||
|
|
||||||
Ok((false, command_message.clone()))
|
Ok((false, command_message.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_action(
|
|
||||||
action: &str,
|
|
||||||
form_state: &mut FormState,
|
|
||||||
ideal_cursor_column: &mut usize,
|
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
|
||||||
command_message: &mut String,
|
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
grpc_client: &mut GrpcClient,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
|
||||||
"previous_entry" => {
|
|
||||||
let new_position = current_position.saturating_sub(1);
|
|
||||||
if new_position >= 1 {
|
|
||||||
*current_position = new_position;
|
|
||||||
match grpc_client.get_adresar_by_position(*current_position).await {
|
|
||||||
Ok(response) => {
|
|
||||||
form_state.id = response.id;
|
|
||||||
form_state.values = vec![
|
|
||||||
response.firma, response.kz, response.drc,
|
|
||||||
response.ulica, response.psc, response.mesto,
|
|
||||||
response.stat, response.banka, response.ucet,
|
|
||||||
response.skladm, response.ico, response.kontakt,
|
|
||||||
response.telefon, response.skladu, response.fax,
|
|
||||||
];
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else { 0 };
|
|
||||||
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
*command_message = format!("Loaded entry {}", *current_position);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
*command_message = format!("Error loading entry: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
key_sequence_tracker.reset();
|
|
||||||
}
|
|
||||||
Ok(command_message.clone())
|
|
||||||
}
|
|
||||||
"next_entry" => {
|
|
||||||
if *current_position <= total_count {
|
|
||||||
*current_position += 1;
|
|
||||||
if *current_position <= total_count {
|
|
||||||
match grpc_client.get_adresar_by_position(*current_position).await {
|
|
||||||
Ok(response) => {
|
|
||||||
form_state.id = response.id;
|
|
||||||
form_state.values = vec![
|
|
||||||
response.firma, response.kz, response.drc,
|
|
||||||
response.ulica, response.psc, response.mesto,
|
|
||||||
response.stat, response.banka, response.ucet,
|
|
||||||
response.skladm, response.ico, response.kontakt,
|
|
||||||
response.telefon, response.skladu, response.fax,
|
|
||||||
];
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else { 0 };
|
|
||||||
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
*command_message = format!("Loaded entry {}", *current_position);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
*command_message = format!("Error loading entry: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
form_state.reset_to_empty();
|
|
||||||
form_state.current_field = 0;
|
|
||||||
form_state.current_cursor_pos = 0;
|
|
||||||
*ideal_cursor_column = 0;
|
|
||||||
*command_message = "New entry mode".to_string();
|
|
||||||
}
|
|
||||||
key_sequence_tracker.reset();
|
|
||||||
}
|
|
||||||
Ok(command_message.clone())
|
|
||||||
}
|
|
||||||
"exit_edit_mode" => {
|
|
||||||
key_sequence_tracker.reset();
|
|
||||||
command_message.clear();
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_left" => {
|
|
||||||
let current_pos = form_state.current_cursor_pos;
|
|
||||||
form_state.current_cursor_pos = current_pos.saturating_sub(1);
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_right" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let current_pos = form_state.current_cursor_pos;
|
|
||||||
if !current_input.is_empty() && current_pos < current_input.len() - 1 {
|
|
||||||
form_state.current_cursor_pos += 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_up" => {
|
|
||||||
// Change field first
|
|
||||||
if form_state.current_field == 0 {
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
} else {
|
|
||||||
form_state.current_field = form_state.current_field.saturating_sub(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current input AFTER changing field
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_down" => {
|
|
||||||
// Change field first
|
|
||||||
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
|
|
||||||
|
|
||||||
// Get current input AFTER changing field
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_next" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_end" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_prev" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_word_end_prev" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
|
|
||||||
form_state.current_cursor_pos = new_pos;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("Moved to previous word end".to_string())
|
|
||||||
}
|
|
||||||
"move_line_start" => {
|
|
||||||
form_state.current_cursor_pos = 0;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_line_end" => {
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
if !current_input.is_empty() {
|
|
||||||
form_state.current_cursor_pos = current_input.len() - 1;
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos;
|
|
||||||
}
|
|
||||||
Ok("".to_string())
|
|
||||||
}
|
|
||||||
"move_first_line" => {
|
|
||||||
// Change field first
|
|
||||||
form_state.current_field = 0;
|
|
||||||
|
|
||||||
// Get current input AFTER changing field
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else {
|
|
||||||
current_input.len()
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("Moved to first line".to_string())
|
|
||||||
}
|
|
||||||
"move_last_line" => {
|
|
||||||
// Change field first
|
|
||||||
form_state.current_field = form_state.fields.len() - 1;
|
|
||||||
|
|
||||||
// Get current input AFTER changing field
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else {
|
|
||||||
current_input.len()
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
|
||||||
Ok("Moved to last line".to_string())
|
|
||||||
}
|
|
||||||
_ => Ok(format!("Unknown action: {}", action)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_char_type(c: char) -> CharType {
|
|
||||||
if c.is_whitespace() {
|
|
||||||
CharType::Whitespace
|
|
||||||
} else if c.is_alphanumeric() {
|
|
||||||
CharType::Alphanumeric
|
|
||||||
} else {
|
|
||||||
CharType::Punctuation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos >= chars.len() {
|
|
||||||
return current_pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos;
|
|
||||||
let initial_type = get_char_type(chars[pos]);
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if current_pos >= chars.len() - 1 {
|
|
||||||
return chars.len() - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos;
|
|
||||||
|
|
||||||
if get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let current_type = get_char_type(chars[pos]);
|
|
||||||
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
|
|
||||||
pos += 1;
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos >= chars.len() {
|
|
||||||
return chars.len() - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos == 0 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos.saturating_sub(1);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if get_char_type(chars[pos]) != CharType::Whitespace {
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() || current_pos <= 1 {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = current_pos.saturating_sub(1);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos > 0 && get_char_type(chars[pos]) != CharType::Whitespace {
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if pos > 0 {
|
|
||||||
pos -= 1;
|
|
||||||
let prev_word_type = get_char_type(chars[pos]);
|
|
||||||
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
while pos < chars.len() - 1 &&
|
|
||||||
get_char_type(chars[pos + 1]) == prev_word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pos
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
// src/client/modes/common.rs
|
// src/client/modes/common.rs
|
||||||
pub mod command_mode;
|
pub mod command_mode;
|
||||||
pub mod highlight;
|
pub mod highlight;
|
||||||
|
pub mod commands;
|
||||||
|
|
||||||
|
pub use commands::*;
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
// src/modes/handlers/command_mode.rs
|
// src/modes/common/command_mode.rs
|
||||||
|
|
||||||
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
|
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
|
||||||
use crate::tui::terminal::grpc_client::GrpcClient;
|
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::ui::handlers::form::FormState;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::tui::controls::commands::CommandHandler;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::{state::AppState, pages::auth::AuthState};
|
||||||
|
use crate::modes::common::commands::CommandHandler;
|
||||||
use crate::tui::terminal::core::TerminalCore;
|
use crate::tui::terminal::core::TerminalCore;
|
||||||
use crate::modes::{
|
use crate::tui::functions::common::form::{save, revert};
|
||||||
canvas::{common},
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
};
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
pub async fn handle_command_event(
|
pub async fn handle_command_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
|
app_state: &AppState,
|
||||||
|
auth_state: &AuthState,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
@@ -21,15 +25,12 @@ pub async fn handle_command_event(
|
|||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome, Box<dyn Error>> {
|
||||||
|
|
||||||
// Return value: (should_exit, message, should_exit_command_mode)
|
|
||||||
|
|
||||||
// Exit command mode (via configurable keybinding)
|
// Exit command mode (via configurable keybinding)
|
||||||
if config.is_exit_command_mode(key.code, key.modifiers) {
|
if config.is_exit_command_mode(key.code, key.modifiers) {
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
*command_message = "".to_string();
|
*command_message = "".to_string();
|
||||||
return Ok((false, "".to_string(), true));
|
return Ok(EventOutcome::Ok("Exited command mode".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute command (via configurable keybinding, defaults to Enter)
|
// Execute command (via configurable keybinding, defaults to Enter)
|
||||||
@@ -37,6 +38,8 @@ pub async fn handle_command_event(
|
|||||||
return process_command(
|
return process_command(
|
||||||
config,
|
config,
|
||||||
form_state,
|
form_state,
|
||||||
|
app_state,
|
||||||
|
auth_state,
|
||||||
command_input,
|
command_input,
|
||||||
command_message,
|
command_message,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
@@ -50,7 +53,7 @@ pub async fn handle_command_event(
|
|||||||
// Backspace (via configurable keybinding, defaults to Backspace)
|
// Backspace (via configurable keybinding, defaults to Backspace)
|
||||||
if config.is_command_backspace(key.code, key.modifiers) {
|
if config.is_command_backspace(key.code, key.modifiers) {
|
||||||
command_input.pop();
|
command_input.pop();
|
||||||
return Ok((false, "".to_string(), false));
|
return Ok(EventOutcome::Ok("".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Regular character input - accept any character in command mode
|
// Regular character input - accept any character in command mode
|
||||||
@@ -58,17 +61,19 @@ pub async fn handle_command_event(
|
|||||||
// Accept regular or shifted characters (e.g., 'a' or 'A')
|
// Accept regular or shifted characters (e.g., 'a' or 'A')
|
||||||
if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT {
|
if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT {
|
||||||
command_input.push(c);
|
command_input.push(c);
|
||||||
return Ok((false, "".to_string(), false));
|
return Ok(EventOutcome::Ok("".to_string()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ignore all other keys
|
// Ignore all other keys
|
||||||
Ok((false, "".to_string(), false))
|
Ok(EventOutcome::Ok("".to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn process_command(
|
async fn process_command(
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
|
app_state: &AppState,
|
||||||
|
auth_state: &AuthState,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
@@ -76,12 +81,12 @@ async fn process_command(
|
|||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome, Box<dyn Error>> {
|
||||||
// Clone the trimmed command to avoid borrow issues
|
// Clone the trimmed command to avoid borrow issues
|
||||||
let command = command_input.trim().to_string();
|
let command = command_input.trim().to_string();
|
||||||
if command.is_empty() {
|
if command.is_empty() {
|
||||||
*command_message = "Empty command".to_string();
|
*command_message = "Empty command".to_string();
|
||||||
return Ok((false, command_message.clone(), false));
|
return Ok(EventOutcome::Ok(command_message.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the action for the command (now checks global and common bindings too)
|
// Get the action for the command (now checks global and common bindings too)
|
||||||
@@ -91,41 +96,50 @@ async fn process_command(
|
|||||||
match action {
|
match action {
|
||||||
"force_quit" | "save_and_quit" | "quit" => {
|
"force_quit" | "save_and_quit" | "quit" => {
|
||||||
let (should_exit, message) = command_handler
|
let (should_exit, message) = command_handler
|
||||||
.handle_command(action, terminal)
|
.handle_command(
|
||||||
|
action,
|
||||||
|
terminal,
|
||||||
|
app_state,
|
||||||
|
form_state,
|
||||||
|
auth_state,
|
||||||
|
)
|
||||||
.await?;
|
.await?;
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
Ok((should_exit, message, true))
|
if should_exit {
|
||||||
|
Ok(EventOutcome::Exit(message))
|
||||||
|
} else {
|
||||||
|
Ok(EventOutcome::Ok(message))
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"save" => {
|
"save" => {
|
||||||
let message = common::save(
|
let outcome = save(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
&mut command_handler.is_saved,
|
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await?;
|
).await?;
|
||||||
|
let message = match outcome {
|
||||||
|
SaveOutcome::CreatedNew(_) => "New entry created".to_string(),
|
||||||
|
SaveOutcome::UpdatedExisting => "Entry updated".to_string(),
|
||||||
|
SaveOutcome::NoChange => "No changes to save".to_string(),
|
||||||
|
};
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
return Ok((false, message, true));
|
Ok(EventOutcome::DataSaved(outcome, message))
|
||||||
},
|
},
|
||||||
"revert" => {
|
"revert" => {
|
||||||
let message = common::revert(
|
let message = revert(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await?;
|
).await?;
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
return Ok((false, message, true));
|
Ok(EventOutcome::Ok(message))
|
||||||
},
|
|
||||||
"unknown" => {
|
|
||||||
let message = format!("Unknown command: {}", command);
|
|
||||||
command_input.clear();
|
|
||||||
return Ok((false, message, true));
|
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
let message = format!("Unhandled action: {}", action);
|
let message = format!("Unhandled action: {}", action);
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
return Ok((false, message, true));
|
Ok(EventOutcome::Ok(message))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,26 @@
|
|||||||
// src/tui/controls/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::pages::{form::FormState, auth::AuthState};
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
pub struct CommandHandler {
|
pub struct CommandHandler;
|
||||||
pub is_saved: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandHandler {
|
impl CommandHandler {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { is_saved: false }
|
Self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_command(
|
pub async fn handle_command(
|
||||||
&mut self,
|
&mut self,
|
||||||
action: &str,
|
action: &str,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
|
app_state: &AppState,
|
||||||
|
form_state: &FormState,
|
||||||
|
auth_state: &AuthState,
|
||||||
) -> 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).await,
|
"quit" => self.handle_quit(terminal, app_state, form_state, auth_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))),
|
||||||
@@ -26,8 +30,18 @@ impl CommandHandler {
|
|||||||
async fn handle_quit(
|
async fn handle_quit(
|
||||||
&self,
|
&self,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
|
app_state: &AppState,
|
||||||
|
form_state: &FormState,
|
||||||
|
auth_state: &AuthState,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||||
if self.is_saved {
|
// Use actual unsaved changes state instead of is_saved flag
|
||||||
|
let has_unsaved = if app_state.ui.show_login {
|
||||||
|
auth_state.has_unsaved_changes()
|
||||||
|
} else {
|
||||||
|
form_state.has_unsaved_changes
|
||||||
|
};
|
||||||
|
|
||||||
|
if !has_unsaved {
|
||||||
terminal.cleanup()?;
|
terminal.cleanup()?;
|
||||||
Ok((true, "Exiting.".into()))
|
Ok((true, "Exiting.".into()))
|
||||||
} else {
|
} else {
|
||||||
@@ -47,7 +61,6 @@ impl CommandHandler {
|
|||||||
&mut self,
|
&mut self,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||||
self.is_saved = true;
|
|
||||||
terminal.cleanup()?;
|
terminal.cleanup()?;
|
||||||
Ok((true, "State saved. Exiting.".into()))
|
Ok((true, "State saved. Exiting.".into()))
|
||||||
}
|
}
|
||||||
@@ -3,70 +3,89 @@
|
|||||||
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::state::AppState;
|
||||||
use crate::ui::handlers::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use crate::ui::handlers::context::UiContext;
|
||||||
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
|
||||||
pub async fn handle_navigation_event(
|
pub async fn handle_navigation_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
command_mode: &mut bool,
|
command_mode: &mut bool,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||||
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);
|
move_up(app_state, auth_state);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
}
|
||||||
"move_down" => {
|
"move_down" => {
|
||||||
let item_count = if app_state.ui.show_intro {
|
move_down(app_state);
|
||||||
2 // Intro options count
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
} else {
|
|
||||||
app_state.profile_tree.profiles.len() // Admin panel items
|
|
||||||
};
|
|
||||||
move_down(app_state, item_count);
|
|
||||||
return Ok((false, String::new()));
|
|
||||||
}
|
}
|
||||||
"next_option" => {
|
"next_option" => {
|
||||||
next_option(app_state, 2); // Intro has 2 options
|
next_option(app_state);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
}
|
||||||
"previous_option" => {
|
"previous_option" => {
|
||||||
previous_option(app_state);
|
previous_option(app_state);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
|
||||||
"select" => {
|
|
||||||
select(app_state);
|
|
||||||
return Ok((false, "Selected".to_string()));
|
|
||||||
}
|
}
|
||||||
"toggle_sidebar" => {
|
"toggle_sidebar" => {
|
||||||
toggle_sidebar(app_state);
|
toggle_sidebar(app_state);
|
||||||
return Ok((false, format!("Sidebar {}",
|
return Ok(EventOutcome::Ok(format!("Sidebar {}",
|
||||||
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
|
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
"next_field" => {
|
"next_field" => {
|
||||||
next_field(form_state);
|
next_field(form_state);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
}
|
||||||
"prev_field" => {
|
"prev_field" => {
|
||||||
prev_field(form_state);
|
prev_field(form_state);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
}
|
||||||
"enter_command_mode" => {
|
"enter_command_mode" => {
|
||||||
handle_enter_command_mode(command_mode, command_input, command_message);
|
handle_enter_command_mode(command_mode, command_input, command_message);
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
|
}
|
||||||
|
"select" => {
|
||||||
|
let (context, index) = if app_state.ui.show_intro {
|
||||||
|
(UiContext::Intro, app_state.ui.intro_state.selected_option)
|
||||||
|
} else if app_state.ui.show_login && app_state.ui.focus_outside_canvas {
|
||||||
|
(UiContext::Login, app_state.general.selected_item)
|
||||||
|
} else if app_state.ui.show_admin {
|
||||||
|
(UiContext::Admin, app_state.general.selected_item)
|
||||||
|
} else if app_state.ui.dialog.dialog_show {
|
||||||
|
(UiContext::Dialog, app_state.ui.dialog.dialog_active_button_index)
|
||||||
|
} else {
|
||||||
|
// Handle cases where select is pressed but no button context applies
|
||||||
|
return Ok(EventOutcome::Ok("Select (No Action)".to_string()));
|
||||||
|
};
|
||||||
|
return Ok(EventOutcome::ButtonSelected { context, index });
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok((false, String::new()))
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn move_up(app_state: &mut AppState) {
|
pub fn move_up(app_state: &mut AppState, auth_state: &mut AuthState) {
|
||||||
if app_state.ui.show_intro {
|
if app_state.ui.focus_outside_canvas && app_state.ui.show_login {
|
||||||
|
if app_state.general.selected_item == 0 {
|
||||||
|
app_state.ui.focus_outside_canvas = false;
|
||||||
|
let last_field_index = auth_state.fields().len().saturating_sub(1);
|
||||||
|
auth_state.set_current_field(last_field_index);
|
||||||
|
} else {
|
||||||
|
app_state.general.selected_item = app_state.general.selected_item.saturating_sub(1);
|
||||||
|
}
|
||||||
|
} else if app_state.ui.show_intro {
|
||||||
app_state.ui.intro_state.previous_option();
|
app_state.ui.intro_state.previous_option();
|
||||||
} else if app_state.ui.show_admin {
|
} else if app_state.ui.show_admin {
|
||||||
// Assuming profile_tree.profiles is the list we're navigating
|
// Assuming profile_tree.profiles is the list we're navigating
|
||||||
@@ -84,8 +103,13 @@ pub fn move_up(app_state: &mut AppState) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn move_down(app_state: &mut AppState, item_count: usize) {
|
pub fn move_down(app_state: &mut AppState) {
|
||||||
if app_state.ui.show_intro {
|
if app_state.ui.focus_outside_canvas && app_state.ui.show_login {
|
||||||
|
let num_general_elements = 2;
|
||||||
|
if app_state.general.selected_item < num_general_elements - 1 {
|
||||||
|
app_state.general.selected_item += 1;
|
||||||
|
}
|
||||||
|
} else if app_state.ui.show_intro {
|
||||||
app_state.ui.intro_state.next_option();
|
app_state.ui.intro_state.next_option();
|
||||||
} else if app_state.ui.show_admin {
|
} else if app_state.ui.show_admin {
|
||||||
// Assuming profile_tree.profiles is the list we're navigating
|
// Assuming profile_tree.profiles is the list we're navigating
|
||||||
@@ -98,11 +122,12 @@ pub fn move_down(app_state: &mut AppState, item_count: usize) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn next_option(app_state: &mut AppState, option_count: usize) {
|
pub fn next_option(app_state: &mut AppState) { // Remove option_count parameter
|
||||||
if app_state.ui.show_intro {
|
if app_state.ui.show_intro {
|
||||||
app_state.ui.intro_state.next_option();
|
app_state.ui.intro_state.next_option();
|
||||||
} else {
|
} else {
|
||||||
// For other screens that might have options
|
// Get option count from state instead of parameter
|
||||||
|
let option_count = app_state.profile_tree.profiles.len();
|
||||||
app_state.general.current_option = (app_state.general.current_option + 1) % option_count;
|
app_state.general.current_option = (app_state.general.current_option + 1) % option_count;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -111,36 +136,12 @@ pub fn previous_option(app_state: &mut AppState) {
|
|||||||
if app_state.ui.show_intro {
|
if app_state.ui.show_intro {
|
||||||
app_state.ui.intro_state.previous_option();
|
app_state.ui.intro_state.previous_option();
|
||||||
} else {
|
} else {
|
||||||
// For other screens that might have options
|
let option_count = app_state.profile_tree.profiles.len();
|
||||||
if app_state.general.current_option == 0 {
|
app_state.general.current_option = if app_state.general.current_option == 0 {
|
||||||
// We'd need the option count here, but since it's not passed we can't wrap around correctly
|
option_count.saturating_sub(1) // Wrap to last option
|
||||||
// For now, just stay at 0
|
|
||||||
} else {
|
} else {
|
||||||
app_state.general.current_option -= 1;
|
app_state.general.current_option - 1
|
||||||
}
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn select(app_state: &mut AppState) {
|
|
||||||
if app_state.ui.show_intro {
|
|
||||||
// Handle selection in intro screen
|
|
||||||
if app_state.ui.intro_state.selected_option == 0 {
|
|
||||||
// First option selected - show form
|
|
||||||
app_state.ui.show_form = true;
|
|
||||||
app_state.ui.show_admin = false;
|
|
||||||
} else {
|
|
||||||
// Second option selected - show admin
|
|
||||||
app_state.ui.show_form = false;
|
|
||||||
app_state.ui.show_admin = true;
|
|
||||||
}
|
|
||||||
app_state.ui.show_intro = false;
|
|
||||||
} else if app_state.ui.show_admin {
|
|
||||||
// Handle selection in admin panel
|
|
||||||
let profiles = &app_state.profile_tree.profiles;
|
|
||||||
if !profiles.is_empty() && app_state.general.selected_item < profiles.len() {
|
|
||||||
// Set the selected profile
|
|
||||||
app_state.selected_profile = Some(profiles[app_state.general.selected_item].name.clone());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,34 @@
|
|||||||
// src/modes/handlers/event.rs
|
// src/modes/handlers/event.rs
|
||||||
use crossterm::event::{Event, KeyEvent};
|
use crossterm::event::Event;
|
||||||
use crossterm::cursor::SetCursorStyle;
|
use crossterm::cursor::SetCursorStyle;
|
||||||
use crate::tui::terminal::{
|
use crate::tui::terminal::core::TerminalCore;
|
||||||
core::TerminalCore,
|
use crate::services::grpc_client::GrpcClient;
|
||||||
grpc_client::GrpcClient,
|
use crate::services::auth::AuthClient;
|
||||||
};
|
use crate::modes::common::commands::CommandHandler;
|
||||||
use crate::tui::controls::commands::CommandHandler;
|
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::ui::handlers::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
use crate::ui::handlers::rat_state::UiStateHandler;
|
use crate::ui::handlers::rat_state::UiStateHandler;
|
||||||
|
use crate::ui::handlers::context::UiContext;
|
||||||
|
use crate::tui::functions::{intro, admin};
|
||||||
|
use crate::tui::functions::common::login;
|
||||||
use crate::modes::{
|
use crate::modes::{
|
||||||
common::{command_mode},
|
common::command_mode,
|
||||||
canvas::{edit, read_only, common},
|
canvas::{edit, read_only, common_mode},
|
||||||
general::navigation,
|
general::navigation,
|
||||||
};
|
};
|
||||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
use crate::modes::handlers::mode_manager::{ModeManager, AppMode};
|
use crate::modes::handlers::mode_manager::{ModeManager, AppMode};
|
||||||
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum EventOutcome {
|
||||||
|
Ok(String),
|
||||||
|
Exit(String),
|
||||||
|
DataSaved(SaveOutcome, String),
|
||||||
|
ButtonSelected { context: UiContext, index: usize },
|
||||||
|
}
|
||||||
|
|
||||||
pub struct EventHandler {
|
pub struct EventHandler {
|
||||||
pub command_mode: bool,
|
pub command_mode: bool,
|
||||||
@@ -25,11 +38,12 @@ pub struct EventHandler {
|
|||||||
pub edit_mode_cooldown: bool,
|
pub edit_mode_cooldown: bool,
|
||||||
pub ideal_cursor_column: usize,
|
pub ideal_cursor_column: usize,
|
||||||
pub key_sequence_tracker: KeySequenceTracker,
|
pub key_sequence_tracker: KeySequenceTracker,
|
||||||
|
pub auth_client: AuthClient,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventHandler {
|
impl EventHandler {
|
||||||
pub fn new() -> Self {
|
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
EventHandler {
|
Ok(EventHandler {
|
||||||
command_mode: false,
|
command_mode: false,
|
||||||
command_input: String::new(),
|
command_input: String::new(),
|
||||||
command_message: String::new(),
|
command_message: String::new(),
|
||||||
@@ -37,7 +51,8 @@ impl EventHandler {
|
|||||||
edit_mode_cooldown: false,
|
edit_mode_cooldown: false,
|
||||||
ideal_cursor_column: 0,
|
ideal_cursor_column: 0,
|
||||||
key_sequence_tracker: KeySequenceTracker::new(800),
|
key_sequence_tracker: KeySequenceTracker::new(800),
|
||||||
}
|
auth_client: AuthClient::new().await?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_event(
|
pub async fn handle_event(
|
||||||
@@ -48,11 +63,11 @@ impl EventHandler {
|
|||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
command_handler: &mut CommandHandler,
|
command_handler: &mut CommandHandler,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
app_state: &mut crate::state::state::AppState,
|
app_state: &mut crate::state::state::AppState,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
||||||
// Determine current mode based on app state and event handler state
|
|
||||||
let current_mode = ModeManager::derive_mode(app_state, self);
|
let current_mode = ModeManager::derive_mode(app_state, self);
|
||||||
app_state.update_mode(current_mode);
|
app_state.update_mode(current_mode);
|
||||||
|
|
||||||
@@ -60,64 +75,111 @@ impl EventHandler {
|
|||||||
let key_code = key.code;
|
let key_code = key.code;
|
||||||
let modifiers = key.modifiers;
|
let modifiers = key.modifiers;
|
||||||
|
|
||||||
// Handle common actions across all modes
|
|
||||||
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) {
|
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) {
|
||||||
return Ok((false, format!("Sidebar {}",
|
let message = format!("Sidebar {}",
|
||||||
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
|
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
|
||||||
)));
|
);
|
||||||
|
return Ok(EventOutcome::Ok(message));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mode-specific handling
|
|
||||||
match current_mode {
|
match current_mode {
|
||||||
AppMode::General => {
|
AppMode::General => {
|
||||||
return 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,
|
||||||
&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 {
|
||||||
|
Ok(EventOutcome::ButtonSelected { context, index }) => {
|
||||||
|
let mut message = String::from("Selected"); // Default message
|
||||||
|
match context {
|
||||||
|
UiContext::Intro => {
|
||||||
|
intro::handle_intro_selection(app_state, index); // Pass index
|
||||||
|
message = format!("Intro Option {} selected", index);
|
||||||
|
}
|
||||||
|
UiContext::Login => {
|
||||||
|
message = match index {
|
||||||
|
0 => login::save(auth_state, &mut self.auth_client, app_state).await?,
|
||||||
|
1 => {
|
||||||
|
let msg = login::revert(auth_state, app_state).await;
|
||||||
|
// Optional: Add navigation logic here if revert should change screen
|
||||||
|
// app_state.ui.show_login = false;
|
||||||
|
// app_state.ui.show_intro = true;
|
||||||
|
msg
|
||||||
|
}
|
||||||
|
_ => "Invalid Login Option".to_string(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
UiContext::Admin => {
|
||||||
|
// Assuming handle_admin_selection uses app_state.general.selected_item
|
||||||
|
admin::handle_admin_selection(app_state);
|
||||||
|
message = format!("Admin Option {} selected", index);
|
||||||
|
}
|
||||||
|
UiContext::Dialog => {
|
||||||
|
// Add specific dialog handling logic here
|
||||||
|
message = format!("Dialog Button {} selected", index);
|
||||||
|
app_state.hide_dialog(); // Example action
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(EventOutcome::Ok(message)); // Return Ok with message
|
||||||
|
}
|
||||||
|
other => return other, // Pass through Ok, Err, DataSaved directly
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
AppMode::ReadOnly => {
|
AppMode::ReadOnly => {
|
||||||
// Check for mode transitions first
|
|
||||||
if config.is_enter_edit_mode_before(key_code, modifiers) &&
|
if config.is_enter_edit_mode_before(key_code, modifiers) &&
|
||||||
ModeManager::can_enter_edit_mode(current_mode) {
|
ModeManager::can_enter_edit_mode(current_mode) {
|
||||||
self.is_edit_mode = true;
|
self.is_edit_mode = true;
|
||||||
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((false, self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.is_enter_edit_mode_after(key_code, modifiers) &&
|
if config.is_enter_edit_mode_after(key_code, modifiers) &&
|
||||||
ModeManager::can_enter_edit_mode(current_mode) {
|
ModeManager::can_enter_edit_mode(current_mode) {
|
||||||
let current_input = form_state.get_current_input();
|
let current_input = if app_state.ui.show_login {
|
||||||
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
|
auth_state.get_current_input()
|
||||||
form_state.current_cursor_pos += 1;
|
} else {
|
||||||
self.ideal_cursor_column = form_state.current_cursor_pos;
|
form_state.get_current_input()
|
||||||
|
};
|
||||||
|
let current_cursor_pos = if app_state.ui.show_login {
|
||||||
|
auth_state.current_cursor_pos()
|
||||||
|
} else {
|
||||||
|
form_state.current_cursor_pos()
|
||||||
|
};
|
||||||
|
|
||||||
|
if !current_input.is_empty() && current_cursor_pos < current_input.len() {
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
auth_state.set_current_cursor_pos(current_cursor_pos + 1);
|
||||||
|
self.ideal_cursor_column = auth_state.current_cursor_pos();
|
||||||
|
} else {
|
||||||
|
form_state.set_current_cursor_pos(current_cursor_pos + 1);
|
||||||
|
self.ideal_cursor_column = form_state.current_cursor_pos();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
self.is_edit_mode = true;
|
self.is_edit_mode = true;
|
||||||
self.edit_mode_cooldown = true;
|
self.edit_mode_cooldown = true;
|
||||||
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((false, 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) {
|
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
|
||||||
if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) {
|
if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) {
|
||||||
self.command_mode = true;
|
self.command_mode = true;
|
||||||
self.command_input.clear();
|
self.command_input.clear();
|
||||||
self.command_message.clear();
|
self.command_message.clear();
|
||||||
return Ok((false, String::new()));
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for core application actions (save, quit, etc.)
|
|
||||||
// ONLY handle a limited subset of core actions here
|
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(
|
if let Some(action) = config.get_action_for_key_in_mode(
|
||||||
&config.keybindings.common,
|
&config.keybindings.common,
|
||||||
key_code,
|
key_code,
|
||||||
@@ -125,26 +187,28 @@ impl EventHandler {
|
|||||||
) {
|
) {
|
||||||
match action {
|
match action {
|
||||||
"save" | "force_quit" | "save_and_quit" | "revert" => {
|
"save" | "force_quit" | "save_and_quit" | "revert" => {
|
||||||
return common::handle_core_action(
|
return common_mode::handle_core_action(
|
||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
|
auth_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
command_handler,
|
&mut self.auth_client,
|
||||||
terminal,
|
terminal,
|
||||||
app_state,
|
app_state,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await;
|
).await;
|
||||||
},
|
},
|
||||||
_ => {} // For other actions, let the mode-specific handler take care of it
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let read_only mode handle its own actions (including navigation from common bindings)
|
let (_should_exit, message) = read_only::handle_read_only_event(
|
||||||
return read_only::handle_read_only_event(
|
app_state,
|
||||||
key,
|
key,
|
||||||
config,
|
config,
|
||||||
form_state,
|
form_state,
|
||||||
|
auth_state,
|
||||||
&mut self.key_sequence_tracker,
|
&mut self.key_sequence_tracker,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
@@ -152,31 +216,53 @@ impl EventHandler {
|
|||||||
&mut self.command_message,
|
&mut self.command_message,
|
||||||
&mut self.edit_mode_cooldown,
|
&mut self.edit_mode_cooldown,
|
||||||
&mut self.ideal_cursor_column,
|
&mut self.ideal_cursor_column,
|
||||||
).await;
|
).await?;
|
||||||
|
return Ok(EventOutcome::Ok(message));
|
||||||
},
|
},
|
||||||
|
|
||||||
AppMode::Edit => {
|
AppMode::Edit => {
|
||||||
// Check for exiting edit mode
|
|
||||||
if config.is_exit_edit_mode(key_code, modifiers) {
|
if config.is_exit_edit_mode(key_code, modifiers) {
|
||||||
if form_state.has_unsaved_changes {
|
|
||||||
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
|
|
||||||
return Ok((false, self.command_message.clone()));
|
|
||||||
}
|
|
||||||
self.is_edit_mode = false;
|
self.is_edit_mode = false;
|
||||||
self.edit_mode_cooldown = true;
|
self.edit_mode_cooldown = true;
|
||||||
self.command_message = "Read-only mode".to_string();
|
|
||||||
|
let has_changes = if app_state.ui.show_login {
|
||||||
|
auth_state.has_unsaved_changes()
|
||||||
|
} else {
|
||||||
|
form_state.has_unsaved_changes()
|
||||||
|
};
|
||||||
|
|
||||||
|
self.command_message = if has_changes {
|
||||||
|
"Exited edit mode (unsaved changes remain)".to_string()
|
||||||
|
} else {
|
||||||
|
"Read-only mode".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
|
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
|
||||||
|
|
||||||
let current_input = form_state.get_current_input();
|
let current_input = if app_state.ui.show_login {
|
||||||
if !current_input.is_empty() && form_state.current_cursor_pos >= current_input.len() {
|
auth_state.get_current_input()
|
||||||
form_state.current_cursor_pos = current_input.len() - 1;
|
} else {
|
||||||
self.ideal_cursor_column = form_state.current_cursor_pos;
|
form_state.get_current_input()
|
||||||
|
};
|
||||||
|
let current_cursor_pos = if app_state.ui.show_login {
|
||||||
|
auth_state.current_cursor_pos()
|
||||||
|
} else {
|
||||||
|
form_state.current_cursor_pos()
|
||||||
|
};
|
||||||
|
|
||||||
|
if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
|
||||||
|
let new_pos = current_input.len() - 1;
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
auth_state.set_current_cursor_pos(new_pos);
|
||||||
|
self.ideal_cursor_column = auth_state.current_cursor_pos();
|
||||||
|
} else {
|
||||||
|
form_state.set_current_cursor_pos(new_pos);
|
||||||
|
self.ideal_cursor_column = form_state.current_cursor_pos();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return Ok((false, self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for core application actions (save, quit, etc.)
|
|
||||||
// ONLY handle a limited subset of core actions here
|
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(
|
if let Some(action) = config.get_action_for_key_in_mode(
|
||||||
&config.keybindings.common,
|
&config.keybindings.common,
|
||||||
key_code,
|
key_code,
|
||||||
@@ -184,42 +270,45 @@ impl EventHandler {
|
|||||||
) {
|
) {
|
||||||
match action {
|
match action {
|
||||||
"save" | "force_quit" | "save_and_quit" | "revert" => {
|
"save" | "force_quit" | "save_and_quit" | "revert" => {
|
||||||
return common::handle_core_action(
|
return common_mode::handle_core_action(
|
||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
|
auth_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
command_handler,
|
&mut self.auth_client,
|
||||||
terminal,
|
terminal,
|
||||||
app_state,
|
app_state,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await;
|
).await;
|
||||||
},
|
},
|
||||||
_ => {} // For other actions, let the mode-specific handler take care of it
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let edit mode handle its own actions (including navigation from common bindings)
|
let message = edit::handle_edit_event(
|
||||||
let result = edit::handle_edit_event_internal(
|
app_state.ui.show_login,
|
||||||
key,
|
key,
|
||||||
config,
|
config,
|
||||||
form_state,
|
form_state,
|
||||||
|
auth_state,
|
||||||
&mut self.ideal_cursor_column,
|
&mut self.ideal_cursor_column,
|
||||||
&mut self.command_message,
|
&mut self.command_message,
|
||||||
&mut app_state.ui.is_saved,
|
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
self.key_sequence_tracker.reset();
|
self.key_sequence_tracker.reset();
|
||||||
return Ok((false, result));
|
return Ok(EventOutcome::Ok(message));
|
||||||
},
|
},
|
||||||
|
|
||||||
AppMode::Command => {
|
AppMode::Command => {
|
||||||
let (should_exit, message, exit_command_mode) = command_mode::handle_command_event(
|
let outcome = command_mode::handle_command_event(
|
||||||
key,
|
key,
|
||||||
config,
|
config,
|
||||||
|
app_state,
|
||||||
|
auth_state,
|
||||||
form_state,
|
form_state,
|
||||||
&mut self.command_input,
|
&mut self.command_input,
|
||||||
&mut self.command_message,
|
&mut self.command_message,
|
||||||
@@ -230,19 +319,17 @@ impl EventHandler {
|
|||||||
total_count,
|
total_count,
|
||||||
).await?;
|
).await?;
|
||||||
|
|
||||||
if exit_command_mode {
|
if let EventOutcome::Ok(msg) = &outcome {
|
||||||
self.command_mode = false;
|
if msg == "Exited command mode" {
|
||||||
|
self.command_mode = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return Ok(outcome);
|
||||||
return Ok((should_exit, message));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Non-key events or if no specific handler was matched
|
|
||||||
self.edit_mode_cooldown = false;
|
self.edit_mode_cooldown = false;
|
||||||
Ok((false, self.command_message.clone()))
|
Ok(EventOutcome::Ok(self.command_message.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,14 +15,20 @@ pub struct ModeManager;
|
|||||||
impl ModeManager {
|
impl ModeManager {
|
||||||
// Determine current mode based on app state
|
// Determine current mode based on app state
|
||||||
pub fn derive_mode(app_state: &AppState, event_handler: &EventHandler) -> AppMode {
|
pub fn derive_mode(app_state: &AppState, event_handler: &EventHandler) -> AppMode {
|
||||||
// Command mode takes precedence if active
|
|
||||||
if event_handler.command_mode {
|
if event_handler.command_mode {
|
||||||
return AppMode::Command;
|
return AppMode::Command;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check UI state flags
|
if app_state.ui.focus_outside_canvas {
|
||||||
if app_state.ui.show_intro || app_state.ui.show_admin {
|
return AppMode::General;
|
||||||
AppMode::General
|
}
|
||||||
|
|
||||||
|
if app_state.ui.show_login {
|
||||||
|
if event_handler.is_edit_mode {
|
||||||
|
AppMode::Edit
|
||||||
|
} else {
|
||||||
|
AppMode::ReadOnly
|
||||||
|
}
|
||||||
} else if app_state.ui.show_form {
|
} else if app_state.ui.show_form {
|
||||||
if event_handler.is_edit_mode {
|
if event_handler.is_edit_mode {
|
||||||
AppMode::Edit
|
AppMode::Edit
|
||||||
@@ -30,7 +36,6 @@ impl ModeManager {
|
|||||||
AppMode::ReadOnly
|
AppMode::ReadOnly
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Fallback
|
|
||||||
AppMode::General
|
AppMode::General
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
23
client/src/services/auth.rs
Normal file
23
client/src/services/auth.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// src/services/auth.rs
|
||||||
|
use tonic::transport::Channel;
|
||||||
|
use common::proto::multieko2::auth::{
|
||||||
|
auth_service_client::AuthServiceClient,
|
||||||
|
LoginRequest, LoginResponse
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct AuthClient {
|
||||||
|
client: AuthServiceClient<Channel>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthClient {
|
||||||
|
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
|
let client = AuthServiceClient::connect("http://[::1]:50051").await?;
|
||||||
|
Ok(Self { client })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
|
||||||
|
let request = tonic::Request::new(LoginRequest { identifier, password });
|
||||||
|
let response = self.client.login(request).await?.into_inner();
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// src/tui/terminal/grpc_client.rs
|
// src/services/grpc_client.rs
|
||||||
|
|
||||||
use tonic::transport::Channel;
|
use tonic::transport::Channel;
|
||||||
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
|
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
|
||||||
@@ -11,6 +11,7 @@ use common::proto::multieko2::table_definition::{
|
|||||||
ProfileTreeResponse
|
ProfileTreeResponse
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct GrpcClient {
|
pub struct GrpcClient {
|
||||||
adresar_client: AdresarClient<Channel>,
|
adresar_client: AdresarClient<Channel>,
|
||||||
table_structure_client: TableStructureServiceClient<Channel>,
|
table_structure_client: TableStructureServiceClient<Channel>,
|
||||||
9
client/src/services/mod.rs
Normal file
9
client/src/services/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// services/mod.rs
|
||||||
|
|
||||||
|
pub mod grpc_client;
|
||||||
|
pub mod auth;
|
||||||
|
pub mod ui_service;
|
||||||
|
|
||||||
|
pub use grpc_client::*;
|
||||||
|
pub use ui_service::*;
|
||||||
|
pub use auth::*;
|
||||||
112
client/src/services/ui_service.rs
Normal file
112
client/src/services/ui_service.rs
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
// src/services/ui_service.rs
|
||||||
|
|
||||||
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use crate::state::state::AppState;
|
||||||
|
|
||||||
|
pub struct UiService;
|
||||||
|
|
||||||
|
impl UiService {
|
||||||
|
pub async fn initialize_app_state(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
||||||
|
// Fetch profile tree
|
||||||
|
let profile_tree = grpc_client.get_profile_tree().await?;
|
||||||
|
app_state.profile_tree = profile_tree;
|
||||||
|
|
||||||
|
// Fetch table structure
|
||||||
|
let table_structure = grpc_client.get_table_structure().await?;
|
||||||
|
|
||||||
|
// Extract the column names from the response
|
||||||
|
let column_names: Vec<String> = table_structure
|
||||||
|
.columns
|
||||||
|
.iter()
|
||||||
|
.map(|col| col.name.clone())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(column_names)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn initialize_adresar_count(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let total_count = grpc_client.get_adresar_count().await?;
|
||||||
|
app_state.update_total_count(total_count);
|
||||||
|
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_adresar_count(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let total_count = grpc_client.get_adresar_count().await?;
|
||||||
|
app_state.update_total_count(total_count);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn load_adresar_by_position(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
form_state: &mut FormState,
|
||||||
|
position: u64,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
match grpc_client.get_adresar_by_position(position).await {
|
||||||
|
Ok(response) => {
|
||||||
|
// Set the ID properly
|
||||||
|
form_state.id = response.id;
|
||||||
|
|
||||||
|
// Update form values dynamically
|
||||||
|
form_state.values = vec![
|
||||||
|
response.firma,
|
||||||
|
response.kz,
|
||||||
|
response.drc,
|
||||||
|
response.ulica,
|
||||||
|
response.psc,
|
||||||
|
response.mesto,
|
||||||
|
response.stat,
|
||||||
|
response.banka,
|
||||||
|
response.ucet,
|
||||||
|
response.skladm,
|
||||||
|
response.ico,
|
||||||
|
response.kontakt,
|
||||||
|
response.telefon,
|
||||||
|
response.skladu,
|
||||||
|
response.fax,
|
||||||
|
];
|
||||||
|
|
||||||
|
form_state.has_unsaved_changes = false;
|
||||||
|
Ok(format!("Loaded entry {}", position))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
Ok(format!("Error loading entry: {}", e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles the consequences of a save operation, like updating counts.
|
||||||
|
pub async fn handle_save_outcome(
|
||||||
|
save_outcome: SaveOutcome,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
form_state: &mut FormState, // Needed to potentially update position/ID
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
match save_outcome {
|
||||||
|
SaveOutcome::CreatedNew(new_id) => {
|
||||||
|
// A new record was created, update the count!
|
||||||
|
UiService::update_adresar_count(grpc_client, app_state).await?;
|
||||||
|
// Navigate to the new record (now that count is updated)
|
||||||
|
app_state.update_current_position(app_state.total_count);
|
||||||
|
form_state.id = new_id; // Ensure ID is set (might be redundant if save already did it)
|
||||||
|
}
|
||||||
|
SaveOutcome::UpdatedExisting | SaveOutcome::NoChange => {
|
||||||
|
// No count update needed for these outcomes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
16
client/src/state/canvas_state.rs
Normal file
16
client/src/state/canvas_state.rs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// src/state/canvas_state.rs
|
||||||
|
|
||||||
|
|
||||||
|
pub trait CanvasState {
|
||||||
|
fn current_field(&self) -> usize;
|
||||||
|
fn current_cursor_pos(&self) -> usize;
|
||||||
|
fn has_unsaved_changes(&self) -> bool;
|
||||||
|
fn inputs(&self) -> Vec<&String>;
|
||||||
|
fn get_current_input(&self) -> &str;
|
||||||
|
fn get_current_input_mut(&mut self) -> &mut String;
|
||||||
|
fn fields(&self) -> Vec<&str>;
|
||||||
|
|
||||||
|
fn set_current_field(&mut self, index: usize);
|
||||||
|
fn set_current_cursor_pos(&mut self, pos: usize);
|
||||||
|
fn set_has_unsaved_changes(&mut self, changed: bool);
|
||||||
|
}
|
||||||
@@ -1,2 +1,4 @@
|
|||||||
// src/state/mod.rs
|
// src/state/mod.rs
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
pub mod pages;
|
||||||
|
pub mod canvas_state;
|
||||||
|
|||||||
4
client/src/state/pages.rs
Normal file
4
client/src/state/pages.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
// src/state/pages.rs
|
||||||
|
|
||||||
|
pub mod form;
|
||||||
|
pub mod auth;
|
||||||
104
client/src/state/pages/auth.rs
Normal file
104
client/src/state/pages/auth.rs
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
// src/state/pages/auth.rs
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct AuthState {
|
||||||
|
pub return_selected: bool,
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
pub error_message: Option<String>,
|
||||||
|
pub current_field: 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
return_selected: false,
|
||||||
|
username: String::new(),
|
||||||
|
password: String::new(),
|
||||||
|
error_message: None,
|
||||||
|
current_field: 0,
|
||||||
|
current_cursor_pos: 0,
|
||||||
|
auth_token: None,
|
||||||
|
user_id: None,
|
||||||
|
role: None,
|
||||||
|
has_unsaved_changes: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasState for AuthState {
|
||||||
|
fn current_field(&self) -> usize {
|
||||||
|
self.current_field
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_cursor_pos(&self) -> usize {
|
||||||
|
let len = match self.current_field {
|
||||||
|
0 => self.username.len(),
|
||||||
|
1 => self.password.len(),
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
self.current_cursor_pos.min(len)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_unsaved_changes(&self) -> bool {
|
||||||
|
self.has_unsaved_changes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inputs(&self) -> Vec<&String> {
|
||||||
|
vec![&self.username, &self.password]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_current_input(&self) -> &str {
|
||||||
|
match self.current_field {
|
||||||
|
0 => &self.username,
|
||||||
|
1 => &self.password,
|
||||||
|
_ => "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_current_input_mut(&mut self) -> &mut String {
|
||||||
|
match self.current_field {
|
||||||
|
0 => &mut self.username,
|
||||||
|
1 => &mut self.password,
|
||||||
|
_ => panic!("Invalid current_field index in AuthState"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fields(&self) -> Vec<&str> {
|
||||||
|
vec!["Username/Email", "Password"]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_current_field(&mut self, index: usize) {
|
||||||
|
if index < 2 { // AuthState only has 2 fields
|
||||||
|
self.current_field = index;
|
||||||
|
// IMPORTANT: Clamp cursor position to the length of the NEW field
|
||||||
|
let len = match self.current_field {
|
||||||
|
0 => self.username.len(),
|
||||||
|
1 => self.password.len(),
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
self.current_cursor_pos = self.current_cursor_pos.min(len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_current_cursor_pos(&mut self, pos: usize) {
|
||||||
|
let len = match self.current_field {
|
||||||
|
0 => self.username.len(),
|
||||||
|
1 => self.password.len(),
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
// Ensure stored position is always valid
|
||||||
|
self.current_cursor_pos = pos.min(len);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
||||||
|
// Allow the generic handler to signal changes
|
||||||
|
self.has_unsaved_changes = changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
// src/client/ui/handlers/form.rs
|
// src/state/pages/form.rs
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use ratatui::layout::Rect;
|
use ratatui::layout::Rect;
|
||||||
use ratatui::Frame;
|
use ratatui::Frame;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
pub struct FormState {
|
pub struct FormState {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
@@ -70,4 +71,66 @@ impl FormState {
|
|||||||
.get_mut(self.current_field)
|
.get_mut(self.current_field)
|
||||||
.expect("Invalid current_field index")
|
.expect("Invalid current_field index")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn update_from_response(&mut self, response: common::proto::multieko2::adresar::AdresarResponse) {
|
||||||
|
self.id = response.id;
|
||||||
|
self.values = vec![
|
||||||
|
response.firma, response.kz, response.drc,
|
||||||
|
response.ulica, response.psc, response.mesto,
|
||||||
|
response.stat, response.banka, response.ucet,
|
||||||
|
response.skladm, response.ico, response.kontakt,
|
||||||
|
response.telefon, response.skladu, response.fax,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasState for FormState {
|
||||||
|
fn current_field(&self) -> usize {
|
||||||
|
self.current_field
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_cursor_pos(&self) -> usize {
|
||||||
|
self.current_cursor_pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_unsaved_changes(&self) -> bool {
|
||||||
|
self.has_unsaved_changes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inputs(&self) -> Vec<&String> {
|
||||||
|
self.values.iter().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_current_input(&self) -> &str {
|
||||||
|
self.values
|
||||||
|
.get(self.current_field)
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_current_input_mut(&mut self) -> &mut String {
|
||||||
|
self.values
|
||||||
|
.get_mut(self.current_field)
|
||||||
|
.expect("Invalid current_field index")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fields(&self) -> Vec<&str> {
|
||||||
|
self.fields.iter().map(|s| s.as_str()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Implement the setter methods ---
|
||||||
|
fn set_current_field(&mut self, index: usize) {
|
||||||
|
if index < self.fields.len() { // Basic bounds check
|
||||||
|
self.current_field = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_current_cursor_pos(&mut self, pos: usize) {
|
||||||
|
// Optional: Add validation based on current input length if needed
|
||||||
|
self.current_cursor_pos = pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
||||||
|
self.has_unsaved_changes = changed;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,13 +5,23 @@ use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
|||||||
use crate::components::IntroState;
|
use crate::components::IntroState;
|
||||||
use crate::modes::handlers::mode_manager::AppMode;
|
use crate::modes::handlers::mode_manager::AppMode;
|
||||||
|
|
||||||
|
pub struct DialogState {
|
||||||
|
pub dialog_show: bool,
|
||||||
|
pub dialog_title: String,
|
||||||
|
pub dialog_message: String,
|
||||||
|
pub dialog_buttons: Vec<String>,
|
||||||
|
pub dialog_active_button_index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct UiState {
|
pub struct UiState {
|
||||||
pub show_sidebar: bool,
|
pub show_sidebar: bool,
|
||||||
pub is_saved: bool,
|
|
||||||
pub show_intro: bool,
|
pub show_intro: bool,
|
||||||
pub show_admin: bool,
|
pub show_admin: bool,
|
||||||
pub show_form: bool,
|
pub show_form: bool,
|
||||||
|
pub show_login: bool,
|
||||||
pub intro_state: IntroState,
|
pub intro_state: IntroState,
|
||||||
|
pub focus_outside_canvas: bool,
|
||||||
|
pub dialog: DialogState, // Add dialog state here
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct GeneralState {
|
pub struct GeneralState {
|
||||||
@@ -65,17 +75,84 @@ impl AppState {
|
|||||||
pub fn update_mode(&mut self, mode: AppMode) {
|
pub fn update_mode(&mut self, mode: AppMode) {
|
||||||
self.current_mode = mode;
|
self.current_mode = mode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add dialog helper methods
|
||||||
|
/// Shows a dialog with the given title, message, and buttons.
|
||||||
|
/// The first button (index 0) is active by default.
|
||||||
|
pub fn show_dialog(
|
||||||
|
&mut self,
|
||||||
|
title: &str,
|
||||||
|
message: &str,
|
||||||
|
buttons: Vec<String>,
|
||||||
|
) {
|
||||||
|
self.ui.dialog.dialog_title = title.to_string();
|
||||||
|
self.ui.dialog.dialog_message = message.to_string();
|
||||||
|
self.ui.dialog.dialog_buttons = buttons;
|
||||||
|
self.ui.dialog.dialog_active_button_index = 0; // Default to first button
|
||||||
|
self.ui.dialog.dialog_show = true; // Use new name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the dialog and clears its content.
|
||||||
|
pub fn hide_dialog(&mut self) {
|
||||||
|
self.ui.dialog.dialog_show = false; // Use new name
|
||||||
|
self.ui.dialog.dialog_title.clear();
|
||||||
|
self.ui.dialog.dialog_message.clear();
|
||||||
|
self.ui.dialog.dialog_buttons.clear();
|
||||||
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the active button index, wrapping around if necessary.
|
||||||
|
pub fn next_dialog_button(&mut self) {
|
||||||
|
if !self.ui.dialog.dialog_buttons.is_empty() {
|
||||||
|
let next_index = (self.ui.dialog.dialog_active_button_index + 1)
|
||||||
|
% self.ui.dialog.dialog_buttons.len();
|
||||||
|
self.ui.dialog.dialog_active_button_index = next_index; // Use new name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the active button index, wrapping around if necessary.
|
||||||
|
pub fn previous_dialog_button(&mut self) {
|
||||||
|
if !self.ui.dialog.dialog_buttons.is_empty() {
|
||||||
|
let len = self.ui.dialog.dialog_buttons.len();
|
||||||
|
let prev_index =
|
||||||
|
(self.ui.dialog.dialog_active_button_index + len - 1) % len;
|
||||||
|
self.ui.dialog.dialog_active_button_index = prev_index; // Use new name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the label of the currently active button, if any.
|
||||||
|
pub fn get_active_dialog_button_label(&self) -> Option<&str> {
|
||||||
|
self.ui.dialog
|
||||||
|
.dialog_buttons // Use new name
|
||||||
|
.get(self.ui.dialog.dialog_active_button_index) // Use new name
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for UiState {
|
impl Default for UiState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
show_sidebar: true,
|
show_sidebar: true,
|
||||||
is_saved: false,
|
|
||||||
show_intro: true,
|
show_intro: true,
|
||||||
show_admin: false,
|
show_admin: false,
|
||||||
show_form: false,
|
show_form: false,
|
||||||
|
show_login: false,
|
||||||
intro_state: IntroState::new(),
|
intro_state: IntroState::new(),
|
||||||
|
focus_outside_canvas: false,
|
||||||
|
dialog: DialogState::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the Default implementation for DialogState itself
|
||||||
|
impl Default for DialogState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
dialog_show: false, // Use new name
|
||||||
|
dialog_title: String::new(), // Use new name
|
||||||
|
dialog_message: String::new(), // Use new name
|
||||||
|
dialog_buttons: Vec::new(), // Use new name
|
||||||
|
dialog_active_button_index: 0, // Use new name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
// src/tui/controls.rs
|
|
||||||
|
|
||||||
pub mod commands;
|
|
||||||
|
|
||||||
pub use commands::*;
|
|
||||||
11
client/src/tui/functions.rs
Normal file
11
client/src/tui/functions.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// src/tui/functions.rs
|
||||||
|
|
||||||
|
pub mod admin;
|
||||||
|
pub mod intro;
|
||||||
|
pub mod login;
|
||||||
|
pub mod form;
|
||||||
|
pub mod common;
|
||||||
|
|
||||||
|
pub use admin::*;
|
||||||
|
pub use intro::*;
|
||||||
|
pub use form::*;
|
||||||
8
client/src/tui/functions/admin.rs
Normal file
8
client/src/tui/functions/admin.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
use crate::state::state::AppState;
|
||||||
|
|
||||||
|
pub fn handle_admin_selection(app_state: &mut AppState) {
|
||||||
|
let profiles = &app_state.profile_tree.profiles;
|
||||||
|
if !profiles.is_empty() && app_state.general.selected_item < profiles.len() {
|
||||||
|
app_state.selected_profile = Some(profiles[app_state.general.selected_item].name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
5
client/src/tui/functions/common.rs
Normal file
5
client/src/tui/functions/common.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
// src/tui/functions/common.rs
|
||||||
|
|
||||||
|
pub mod form;
|
||||||
|
pub mod login;
|
||||||
|
|
||||||
@@ -1,94 +1,29 @@
|
|||||||
// src/modes/canvas/common.rs
|
// src/tui/functions/common/form.rs
|
||||||
|
|
||||||
use crossterm::event::{KeyEvent};
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::config::binds::config::Config;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::tui::terminal::grpc_client::GrpcClient;
|
|
||||||
use crate::tui::terminal::core::TerminalCore;
|
|
||||||
use crate::tui::controls::commands::CommandHandler;
|
|
||||||
use crate::ui::handlers::form::FormState;
|
|
||||||
use crate::state::state::AppState;
|
|
||||||
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
||||||
|
|
||||||
/// Main handler for common core actions
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub async fn handle_core_action(
|
pub enum SaveOutcome {
|
||||||
action: &str,
|
NoChange, // Nothing needed saving
|
||||||
form_state: &mut FormState,
|
UpdatedExisting, // An existing record was updated
|
||||||
grpc_client: &mut GrpcClient,
|
CreatedNew(i64), // A new record was created (include its new ID)
|
||||||
command_handler: &mut CommandHandler,
|
|
||||||
terminal: &mut TerminalCore,
|
|
||||||
app_state: &mut AppState,
|
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
|
||||||
"save" => {
|
|
||||||
let message = save(
|
|
||||||
form_state,
|
|
||||||
grpc_client,
|
|
||||||
&mut app_state.ui.is_saved,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
|
||||||
Ok((false, message))
|
|
||||||
},
|
|
||||||
"force_quit" => {
|
|
||||||
terminal.cleanup()?;
|
|
||||||
Ok((true, "Force exiting without saving.".to_string()))
|
|
||||||
},
|
|
||||||
"save_and_quit" => {
|
|
||||||
let message = save(
|
|
||||||
form_state,
|
|
||||||
grpc_client,
|
|
||||||
&mut app_state.ui.is_saved,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
|
||||||
terminal.cleanup()?;
|
|
||||||
Ok((true, format!("{}. Exiting application.", message)))
|
|
||||||
},
|
|
||||||
"revert" => {
|
|
||||||
let message = revert(
|
|
||||||
form_state,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
|
||||||
Ok((false, message))
|
|
||||||
},
|
|
||||||
// We should never hit this case with proper filtering
|
|
||||||
_ => Ok((false, format!("Core action not handled: {}", action))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function to check if a key event should trigger a core action
|
|
||||||
pub fn is_core_action(config: &Config, key_code: crossterm::event::KeyCode, modifiers: crossterm::event::KeyModifiers) -> Option<String> {
|
|
||||||
// Check for core application actions (save, quit, etc.)
|
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(
|
|
||||||
&config.keybindings.common,
|
|
||||||
key_code,
|
|
||||||
modifiers
|
|
||||||
) {
|
|
||||||
match action {
|
|
||||||
"save" | "force_quit" | "save_and_quit" | "revert" => {
|
|
||||||
return Some(action.to_string())
|
|
||||||
},
|
|
||||||
_ => {} // Other actions are handled by their respective mode handlers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared logic for saving the current form state
|
/// Shared logic for saving the current form state
|
||||||
pub async fn save(
|
pub async fn save(
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
is_saved: &mut bool,
|
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<SaveOutcome, Box<dyn std::error::Error>> { // <-- Return SaveOutcome
|
||||||
|
if !form_state.has_unsaved_changes {
|
||||||
|
return Ok(SaveOutcome::NoChange); // Early exit if no changes
|
||||||
|
}
|
||||||
let is_new = *current_position == total_count + 1;
|
let is_new = *current_position == total_count + 1;
|
||||||
|
|
||||||
let message = if is_new {
|
let outcome = if is_new {
|
||||||
let post_request = PostAdresarRequest {
|
let post_request = PostAdresarRequest {
|
||||||
firma: form_state.values[0].clone(),
|
firma: form_state.values[0].clone(),
|
||||||
kz: form_state.values[1].clone(),
|
kz: form_state.values[1].clone(),
|
||||||
@@ -107,10 +42,9 @@ pub async fn save(
|
|||||||
fax: form_state.values[14].clone(),
|
fax: form_state.values[14].clone(),
|
||||||
};
|
};
|
||||||
let response = grpc_client.post_adresar(post_request).await?;
|
let response = grpc_client.post_adresar(post_request).await?;
|
||||||
let new_total = grpc_client.get_adresar_count().await?;
|
let new_id = response.into_inner().id;
|
||||||
*current_position = new_total;
|
form_state.id = new_id;
|
||||||
form_state.id = response.into_inner().id;
|
SaveOutcome::CreatedNew(new_id) // <-- Return CreatedNew with ID
|
||||||
"New entry created".to_string()
|
|
||||||
} else {
|
} else {
|
||||||
let put_request = PutAdresarRequest {
|
let put_request = PutAdresarRequest {
|
||||||
id: form_state.id,
|
id: form_state.id,
|
||||||
@@ -131,12 +65,11 @@ pub async fn save(
|
|||||||
fax: form_state.values[14].clone(),
|
fax: form_state.values[14].clone(),
|
||||||
};
|
};
|
||||||
let _ = grpc_client.put_adresar(put_request).await?;
|
let _ = grpc_client.put_adresar(put_request).await?;
|
||||||
"Entry updated".to_string()
|
SaveOutcome::UpdatedExisting
|
||||||
};
|
};
|
||||||
|
|
||||||
*is_saved = true;
|
|
||||||
form_state.has_unsaved_changes = false;
|
form_state.has_unsaved_changes = false;
|
||||||
Ok(message)
|
Ok(outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Discard changes since last save
|
/// Discard changes since last save
|
||||||
100
client/src/tui/functions/common/login.rs
Normal file
100
client/src/tui/functions/common/login.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
// src/tui/functions/common/login.rs
|
||||||
|
use crate::services::auth::AuthClient;
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
|
use crate::state::state::AppState;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
// Remove unused import if CanvasState is not directly used here
|
||||||
|
// use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
|
/// Attempts to log the user in using the provided credentials via gRPC.
|
||||||
|
/// Updates AuthState and AppState on success or failure.
|
||||||
|
pub async fn save(
|
||||||
|
auth_state: &mut AuthState,
|
||||||
|
auth_client: &mut AuthClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
let identifier = auth_state.username.clone();
|
||||||
|
let password = auth_state.password.clone();
|
||||||
|
|
||||||
|
// Clear previous error/dialog state before attempting
|
||||||
|
auth_state.error_message = None;
|
||||||
|
// Use the helper to ensure dialog is hidden and cleared properly
|
||||||
|
app_state.hide_dialog();
|
||||||
|
|
||||||
|
// Call the gRPC login method
|
||||||
|
match auth_client.login(identifier, password).await {
|
||||||
|
Ok(response) => {
|
||||||
|
// Store authentication details on success
|
||||||
|
auth_state.auth_token = Some(response.access_token.clone());
|
||||||
|
auth_state.user_id = Some(response.user_id.clone());
|
||||||
|
auth_state.role = Some(response.role.clone());
|
||||||
|
auth_state.set_has_unsaved_changes(false);
|
||||||
|
|
||||||
|
let success_message = format!(
|
||||||
|
"Login Successful!\n\n\
|
||||||
|
Access Token: {}\n\
|
||||||
|
Token Type: {}\n\
|
||||||
|
Expires In: {}\n\
|
||||||
|
User ID: {}\n\
|
||||||
|
Role: {}",
|
||||||
|
response.access_token,
|
||||||
|
response.token_type,
|
||||||
|
response.expires_in,
|
||||||
|
response.user_id,
|
||||||
|
response.role
|
||||||
|
);
|
||||||
|
|
||||||
|
// Use the helper method to configure and show the dialog
|
||||||
|
// TODO Implement logic for pressing menu or exit buttons, not imeplementing it now,
|
||||||
|
// need to do other more important stuff now"
|
||||||
|
app_state.show_dialog(
|
||||||
|
"Login Success",
|
||||||
|
&success_message,
|
||||||
|
vec!["Menu".to_string(), "Exit".to_string()],
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok("Login successful, details shown in dialog.".to_string())
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let error_message = format!("{}", e);
|
||||||
|
|
||||||
|
// Use the helper method to configure and show the dialog
|
||||||
|
app_state.show_dialog(
|
||||||
|
"Login Failed",
|
||||||
|
&error_message,
|
||||||
|
vec!["OK".to_string()], // Pass buttons here
|
||||||
|
);
|
||||||
|
// REMOVE these lines:
|
||||||
|
// app_state.ui.dialog.dialog_title = "Login Failed".to_string();
|
||||||
|
// app_state.ui.dialog.dialog_message = error_message.clone();
|
||||||
|
// app_state.ui.dialog.dialog_show = true;
|
||||||
|
// app_state.ui.dialog.dialog_button_active = true;
|
||||||
|
|
||||||
|
auth_state.set_has_unsaved_changes(true);
|
||||||
|
|
||||||
|
Ok(format!("Login failed: {}", error_message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
|
||||||
|
pub async fn revert(
|
||||||
|
auth_state: &mut AuthState,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
) -> String {
|
||||||
|
// Clear the input fields
|
||||||
|
auth_state.username.clear();
|
||||||
|
auth_state.password.clear();
|
||||||
|
auth_state.error_message = None;
|
||||||
|
auth_state.set_has_unsaved_changes(false);
|
||||||
|
|
||||||
|
// Ensure dialog is hidden if revert is called
|
||||||
|
// _app_state.hide_dialog(); // Uncomment if needed
|
||||||
|
|
||||||
|
// Navigation logic (currently disabled in original code)
|
||||||
|
// _app_state.ui.show_login = false;
|
||||||
|
// _app_state.ui.show_intro = true;
|
||||||
|
|
||||||
|
"Login reverted".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
89
client/src/tui/functions/form.rs
Normal file
89
client/src/tui/functions/form.rs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// src/tui/functions/form.rs
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
|
||||||
|
pub async fn handle_action(
|
||||||
|
action: &str,
|
||||||
|
form_state: &mut FormState,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
current_position: &mut u64,
|
||||||
|
total_count: u64,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
// TODO store unsaved changes without deleting form state values
|
||||||
|
// First check for unsaved changes in both cases
|
||||||
|
if form_state.has_unsaved_changes() {
|
||||||
|
return Ok(
|
||||||
|
"Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
match action {
|
||||||
|
"previous_entry" => {
|
||||||
|
let new_position = current_position.saturating_sub(1);
|
||||||
|
if new_position >= 1 {
|
||||||
|
*current_position = new_position;
|
||||||
|
let response = grpc_client.get_adresar_by_position(*current_position).await?;
|
||||||
|
|
||||||
|
// Direct field assignments
|
||||||
|
form_state.id = response.id;
|
||||||
|
form_state.values = vec![
|
||||||
|
response.firma, response.kz, response.drc,
|
||||||
|
response.ulica, response.psc, response.mesto,
|
||||||
|
response.stat, response.banka, response.ucet,
|
||||||
|
response.skladm, response.ico, response.kontakt,
|
||||||
|
response.telefon, response.skladu, response.fax,
|
||||||
|
];
|
||||||
|
|
||||||
|
let current_input = form_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
|
current_input.len() - 1
|
||||||
|
} else { 0 };
|
||||||
|
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
||||||
|
form_state.has_unsaved_changes = false;
|
||||||
|
|
||||||
|
Ok(format!("Loaded form entry {}", *current_position))
|
||||||
|
} else {
|
||||||
|
Ok("Already at first form entry".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"next_entry" => {
|
||||||
|
if *current_position <= total_count {
|
||||||
|
*current_position += 1;
|
||||||
|
if *current_position <= total_count {
|
||||||
|
let response = grpc_client.get_adresar_by_position(*current_position).await?;
|
||||||
|
|
||||||
|
// Direct field assignments
|
||||||
|
form_state.id = response.id;
|
||||||
|
form_state.values = vec![
|
||||||
|
response.firma, response.kz, response.drc,
|
||||||
|
response.ulica, response.psc, response.mesto,
|
||||||
|
response.stat, response.banka, response.ucet,
|
||||||
|
response.skladm, response.ico, response.kontakt,
|
||||||
|
response.telefon, response.skladu, response.fax,
|
||||||
|
];
|
||||||
|
|
||||||
|
let current_input = form_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
|
current_input.len() - 1
|
||||||
|
} else { 0 };
|
||||||
|
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
||||||
|
form_state.has_unsaved_changes = false;
|
||||||
|
|
||||||
|
Ok(format!("Loaded form entry {}", *current_position))
|
||||||
|
} else {
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
form_state.current_field = 0;
|
||||||
|
form_state.current_cursor_pos = 0;
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("New form entry mode".into())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok("Already at last entry".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Err("Unknown form action".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
24
client/src/tui/functions/intro.rs
Normal file
24
client/src/tui/functions/intro.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
use crate::state::state::AppState;
|
||||||
|
|
||||||
|
pub fn handle_intro_selection(app_state: &mut AppState, index: usize) { // Add index parameter
|
||||||
|
match index { // Use index directly
|
||||||
|
0 => { // Continue
|
||||||
|
app_state.ui.show_form = true;
|
||||||
|
app_state.ui.show_admin = false;
|
||||||
|
app_state.ui.show_login = false;
|
||||||
|
}
|
||||||
|
1 => { // Admin
|
||||||
|
app_state.ui.show_form = false;
|
||||||
|
app_state.ui.show_admin = true;
|
||||||
|
app_state.ui.show_login = false;
|
||||||
|
}
|
||||||
|
2 => { // Login
|
||||||
|
app_state.ui.show_form = false;
|
||||||
|
app_state.ui.show_admin = false;
|
||||||
|
app_state.ui.show_login = true;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
app_state.ui.show_intro = false;
|
||||||
|
}
|
||||||
|
|
||||||
18
client/src/tui/functions/login.rs
Normal file
18
client/src/tui/functions/login.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// src/tui/functions/login.rs
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
|
|
||||||
|
pub async fn handle_action(
|
||||||
|
action: &str,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
match action {
|
||||||
|
"previous_entry" => {
|
||||||
|
Ok("Previous entry at tui/functions/login.rs not implemented".into())
|
||||||
|
}
|
||||||
|
"next_entry" => {
|
||||||
|
Ok("Next entry at tui/functions/login.rs not implemented".into())
|
||||||
|
}
|
||||||
|
_ => Err("Unknown login action".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
// src/tui/mod.rs
|
// src/tui/mod.rs
|
||||||
pub mod terminal;
|
pub mod terminal;
|
||||||
pub mod controls;
|
pub mod functions;
|
||||||
|
|
||||||
|
pub use functions::*;
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
// src/tui/terminal.rs
|
// src/tui/terminal.rs
|
||||||
|
|
||||||
pub mod core;
|
pub mod core;
|
||||||
pub mod grpc_client;
|
|
||||||
pub mod event_reader;
|
pub mod event_reader;
|
||||||
|
|
||||||
pub use core::TerminalCore;
|
pub use core::TerminalCore;
|
||||||
pub use grpc_client::GrpcClient;
|
|
||||||
pub use event_reader::EventReader;
|
pub use event_reader::EventReader;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
use crossterm::{
|
use crossterm::{
|
||||||
execute,
|
execute,
|
||||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||||
cursor::{SetCursorStyle, EnableBlinking, Show, MoveTo},
|
cursor::{SetCursorStyle, EnableBlinking, Show, Hide, MoveTo},
|
||||||
};
|
};
|
||||||
use ratatui::{backend::CrosstermBackend, Terminal};
|
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||||
use std::io::{self, stdout, Write};
|
use std::io::{self, stdout, Write};
|
||||||
@@ -64,6 +64,22 @@ impl TerminalCore {
|
|||||||
)?;
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn show_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
execute!(
|
||||||
|
self.terminal.backend_mut(),
|
||||||
|
Show
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hide_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
execute!(
|
||||||
|
self.terminal.backend_mut(),
|
||||||
|
Hide
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for TerminalCore {
|
impl Drop for TerminalCore {
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
// src/client/ui/handlers.rs
|
// src/client/ui/handlers.rs
|
||||||
|
|
||||||
pub mod ui;
|
pub mod ui;
|
||||||
pub mod form;
|
|
||||||
pub mod render;
|
pub mod render;
|
||||||
pub mod rat_state;
|
pub mod rat_state;
|
||||||
|
pub mod context;
|
||||||
|
|
||||||
pub use ui::run_ui;
|
pub use ui::run_ui;
|
||||||
pub use rat_state::*;
|
pub use rat_state::*;
|
||||||
|
pub use context::*;
|
||||||
|
|||||||
8
client/src/ui/handlers/context.rs
Normal file
8
client/src/ui/handlers/context.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum UiContext {
|
||||||
|
Intro,
|
||||||
|
Login,
|
||||||
|
Admin,
|
||||||
|
Dialog,
|
||||||
|
}
|
||||||
|
|
||||||
@@ -6,18 +6,20 @@ use crate::components::{
|
|||||||
render_status_line,
|
render_status_line,
|
||||||
handlers::sidebar::{self, calculate_sidebar_layout},
|
handlers::sidebar::{self, calculate_sidebar_layout},
|
||||||
form::form::render_form,
|
form::form::render_form,
|
||||||
intro::{intro},
|
|
||||||
admin::{admin_panel::AdminPanelState},
|
admin::{admin_panel::AdminPanelState},
|
||||||
|
auth::login::render_login,
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use ratatui::layout::{Constraint, Direction, Layout};
|
use ratatui::layout::{Constraint, Direction, Layout};
|
||||||
use ratatui::Frame;
|
use ratatui::Frame;
|
||||||
use super::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
use crate::state::state::AppState;
|
use crate::state::state::AppState;
|
||||||
|
|
||||||
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,
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
@@ -44,6 +46,15 @@ pub fn render_ui(
|
|||||||
if app_state.ui.show_intro {
|
if app_state.ui.show_intro {
|
||||||
// Use app_state's intro_state directly
|
// Use app_state's intro_state directly
|
||||||
app_state.ui.intro_state.render(f, main_content_area, theme);
|
app_state.ui.intro_state.render(f, main_content_area, theme);
|
||||||
|
}else if app_state.ui.show_login {
|
||||||
|
render_login(
|
||||||
|
f,
|
||||||
|
main_content_area,
|
||||||
|
theme,
|
||||||
|
auth_state,
|
||||||
|
app_state, // Add AppState reference here
|
||||||
|
auth_state.current_field < 2
|
||||||
|
);
|
||||||
} else if app_state.ui.show_admin {
|
} else if app_state.ui.show_admin {
|
||||||
// Create temporary AdminPanelState for rendering
|
// Create temporary AdminPanelState for rendering
|
||||||
let mut admin_state = AdminPanelState::new(
|
let mut admin_state = AdminPanelState::new(
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
// src/ui/handlers/ui.rs
|
// src/ui/handlers/ui.rs
|
||||||
|
|
||||||
use crate::tui::terminal::TerminalCore;
|
|
||||||
use crate::tui::terminal::GrpcClient;
|
|
||||||
use crate::tui::controls::CommandHandler;
|
|
||||||
use crate::tui::terminal::EventReader;
|
|
||||||
use crate::config::colors::themes::Theme;
|
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::ui::handlers::{form::FormState, render::render_ui};
|
use crate::config::colors::themes::Theme;
|
||||||
use crate::modes::handlers::event::EventHandler;
|
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::ui_service::UiService;
|
||||||
|
use crate::state::canvas_state::CanvasState;
|
||||||
|
use crate::state::pages::auth::AuthState;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
use crate::state::state::AppState;
|
use crate::state::state::AppState;
|
||||||
use crate::components::admin::{admin_panel::AdminPanelState};
|
use crate::tui::functions::common::form::SaveOutcome; // Import SaveOutcome
|
||||||
use crate::components::intro::{intro::IntroState};
|
use crate::tui::terminal::{EventReader, TerminalCore};
|
||||||
|
use crate::ui::handlers::render::render_ui;
|
||||||
|
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()?;
|
||||||
@@ -18,55 +22,39 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let mut grpc_client = GrpcClient::new().await?;
|
let mut grpc_client = GrpcClient::new().await?;
|
||||||
let mut command_handler = CommandHandler::new();
|
let mut command_handler = CommandHandler::new();
|
||||||
let theme = Theme::from_str(&config.colors.theme);
|
let theme = Theme::from_str(&config.colors.theme);
|
||||||
let mut intro_state = IntroState::new();
|
let mut auth_state = AuthState::default(); // The single source of truth for AuthState
|
||||||
|
|
||||||
// Initialize app_state first
|
// Initialize app_state first
|
||||||
let mut app_state = AppState::new()?;
|
let mut app_state = AppState::new()?;
|
||||||
|
|
||||||
// Fetch profile tree and table structure
|
// Initialize app state with profile tree and table structure
|
||||||
let profile_tree = grpc_client.get_profile_tree().await?;
|
let column_names =
|
||||||
app_state.profile_tree = profile_tree;
|
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
||||||
|
.await?;
|
||||||
// Now create admin panel with profiles from app_state
|
|
||||||
if intro_state.selected_option == 1 {
|
|
||||||
app_state.ui.show_admin = true;
|
|
||||||
app_state.general.selected_item = 0;
|
|
||||||
app_state.general.current_option = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch table structure at startup (one-time)
|
|
||||||
let table_structure = grpc_client.get_table_structure().await?;
|
|
||||||
|
|
||||||
// Extract the column names from the response
|
|
||||||
let column_names: Vec<String> = table_structure
|
|
||||||
.columns
|
|
||||||
.iter()
|
|
||||||
.map(|col| col.name.clone())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Initialize FormState with dynamic fields
|
// Initialize FormState with dynamic fields
|
||||||
let mut form_state = FormState::new(column_names);
|
let mut form_state = FormState::new(column_names);
|
||||||
|
|
||||||
// The rest of your UI initialization remains the same
|
// Initialize EventHandler (which now contains AuthClient)
|
||||||
let mut event_handler = EventHandler::new();
|
let mut event_handler = EventHandler::new().await?;
|
||||||
let event_reader = EventReader::new();
|
let event_reader = EventReader::new();
|
||||||
|
|
||||||
// Fetch the total count of Adresar entries
|
// Fetch the total count of Adresar entries
|
||||||
let total_count = grpc_client.get_adresar_count().await?;
|
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state)
|
||||||
app_state.update_total_count(total_count);
|
.await?;
|
||||||
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
|
||||||
form_state.reset_to_empty();
|
form_state.reset_to_empty();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let total_count = grpc_client.get_adresar_count().await?;
|
// Determine edit mode based on EventHandler state
|
||||||
app_state.update_total_count(total_count);
|
let is_edit_mode = event_handler.is_edit_mode;
|
||||||
|
|
||||||
terminal.draw(|f| {
|
terminal.draw(|f| {
|
||||||
render_ui(
|
render_ui(
|
||||||
f,
|
f,
|
||||||
&mut form_state,
|
&mut form_state,
|
||||||
|
&mut auth_state, // Pass the single AuthState instance
|
||||||
&theme,
|
&theme,
|
||||||
event_handler.is_edit_mode,
|
is_edit_mode, // Use determined edit mode
|
||||||
app_state.total_count,
|
app_state.total_count,
|
||||||
app_state.current_position,
|
app_state.current_position,
|
||||||
&app_state.current_dir,
|
&app_state.current_dir,
|
||||||
@@ -77,91 +65,199 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
);
|
);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let total_count = app_state.total_count;
|
// --- Cursor Visibility Logic ---
|
||||||
|
let current_mode = ModeManager::derive_mode(&app_state, &event_handler);
|
||||||
|
match current_mode {
|
||||||
|
AppMode::Edit => {
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
}
|
||||||
|
AppMode::ReadOnly => {
|
||||||
|
if !app_state.ui.focus_outside_canvas {
|
||||||
|
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
|
||||||
|
} else {
|
||||||
|
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
||||||
|
}
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
}
|
||||||
|
AppMode::General => {
|
||||||
|
if app_state.ui.focus_outside_canvas {
|
||||||
|
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
} else {
|
||||||
|
terminal.hide_cursor()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AppMode::Command => {
|
||||||
|
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- End Cursor Visibility Logic ---
|
||||||
|
|
||||||
|
let total_count = app_state.total_count; // Keep track for save logic
|
||||||
let mut current_position = app_state.current_position;
|
let mut current_position = app_state.current_position;
|
||||||
|
let position_before_event = current_position;
|
||||||
|
|
||||||
let event = event_reader.read_event()?;
|
let event = event_reader.read_event()?;
|
||||||
let (should_exit, message) = event_handler.handle_event(
|
|
||||||
event,
|
|
||||||
&config,
|
|
||||||
&mut terminal,
|
|
||||||
&mut grpc_client,
|
|
||||||
&mut command_handler,
|
|
||||||
&mut form_state,
|
|
||||||
&mut app_state,
|
|
||||||
total_count,
|
|
||||||
&mut current_position,
|
|
||||||
).await?;
|
|
||||||
|
|
||||||
|
// Get the outcome from the event handler
|
||||||
|
let event_outcome_result = event_handler
|
||||||
|
.handle_event(
|
||||||
|
event,
|
||||||
|
&config,
|
||||||
|
&mut terminal, // Pass terminal mutably
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut command_handler,
|
||||||
|
&mut form_state,
|
||||||
|
&mut auth_state,
|
||||||
|
&mut app_state,
|
||||||
|
total_count, // Pass the count *before* potential save
|
||||||
|
&mut current_position,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Update position based on handler's modification
|
||||||
app_state.current_position = current_position;
|
app_state.current_position = current_position;
|
||||||
|
|
||||||
// Handle position changes and update form state
|
// --- Centralized Consequence Handling ---
|
||||||
if !event_handler.is_edit_mode {
|
let mut should_exit = false;
|
||||||
let current_input = form_state.get_current_input();
|
match event_outcome_result {
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
// Handle the Result first
|
||||||
current_input.len() - 1 // Limit to last character in readonly mode
|
Ok(outcome) => match outcome {
|
||||||
} else {
|
// Handle the Ok variant containing EventOutcome
|
||||||
0
|
EventOutcome::Ok(message) => {
|
||||||
};
|
if !message.is_empty() {
|
||||||
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
event_handler.command_message = message;
|
||||||
|
|
||||||
// Ensure position never exceeds total_count + 1
|
|
||||||
if app_state.current_position > total_count + 1 {
|
|
||||||
app_state.current_position = total_count + 1;
|
|
||||||
}
|
|
||||||
if app_state.current_position > total_count {
|
|
||||||
// New entry - reset form
|
|
||||||
form_state.reset_to_empty();
|
|
||||||
form_state.current_field = 0;
|
|
||||||
} else if app_state.current_position >= 1 && app_state.current_position <= total_count {
|
|
||||||
// Existing entry - load data
|
|
||||||
match grpc_client.get_adresar_by_position(app_state.current_position).await {
|
|
||||||
Ok(response) => {
|
|
||||||
// Set the ID properly
|
|
||||||
form_state.id = response.id;
|
|
||||||
|
|
||||||
// Update form values dynamically
|
|
||||||
form_state.values = vec![
|
|
||||||
response.firma,
|
|
||||||
response.kz,
|
|
||||||
response.drc,
|
|
||||||
response.ulica,
|
|
||||||
response.psc,
|
|
||||||
response.mesto,
|
|
||||||
response.stat,
|
|
||||||
response.banka,
|
|
||||||
response.ucet,
|
|
||||||
response.skladm,
|
|
||||||
response.ico,
|
|
||||||
response.kontakt,
|
|
||||||
response.telefon,
|
|
||||||
response.skladu,
|
|
||||||
response.fax,
|
|
||||||
];
|
|
||||||
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
|
|
||||||
current_input.len() - 1 // In readonly mode, limit to last character
|
|
||||||
} else {
|
|
||||||
current_input.len()
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
event_handler.command_message = format!("Loaded entry {}", app_state.current_position);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
event_handler.command_message = format!("Error loading entry: {}", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
EventOutcome::Exit(message) => {
|
||||||
// Invalid position - reset to first entry
|
event_handler.command_message = message;
|
||||||
app_state.current_position = 1;
|
should_exit = true;
|
||||||
|
}
|
||||||
|
EventOutcome::DataSaved(save_outcome, message) => {
|
||||||
|
event_handler.command_message = message; // Show save status
|
||||||
|
|
||||||
|
// *** Delegate outcome handling to UiService ***
|
||||||
|
if let Err(e) = UiService::handle_save_outcome(
|
||||||
|
save_outcome,
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut app_state,
|
||||||
|
&mut form_state,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
// Handle potential errors from the outcome handler itself
|
||||||
|
event_handler.command_message =
|
||||||
|
format!("Error handling save outcome: {}", e);
|
||||||
|
}
|
||||||
|
// No count update needed for UpdatedExisting or NoChange
|
||||||
|
}
|
||||||
|
EventOutcome::ButtonSelected { context, index } => {
|
||||||
|
event_handler.command_message = "Internal error: Unexpected button state".to_string();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
// Handle errors from handle_event, e.g., log or display
|
||||||
|
event_handler.command_message = format!("Error: {}", e);
|
||||||
|
// Decide if the error is fatal, maybe set should_exit = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
event_handler.command_message = message;
|
// --- Position Change Handling (after outcome processing) ---
|
||||||
|
let position_changed =
|
||||||
|
app_state.current_position != position_before_event; // Calculate after potential update
|
||||||
|
// Recalculate total_count *after* potential update
|
||||||
|
let current_total_count = app_state.total_count;
|
||||||
|
|
||||||
|
// Handle position changes and update form state (Only when form is shown)
|
||||||
|
if app_state.ui.show_form {
|
||||||
|
if position_changed && !event_handler.is_edit_mode {
|
||||||
|
let current_input = form_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
|
current_input.len() - 1 // Limit to last character in readonly mode
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
form_state.current_cursor_pos =
|
||||||
|
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
|
|
||||||
|
// Ensure position never exceeds total_count + 1
|
||||||
|
if app_state.current_position > current_total_count + 1 {
|
||||||
|
app_state.current_position = current_total_count + 1;
|
||||||
|
}
|
||||||
|
if app_state.current_position > current_total_count {
|
||||||
|
// New entry - reset form
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
form_state.current_field = 0;
|
||||||
|
} else if app_state.current_position >= 1
|
||||||
|
&& app_state.current_position <= current_total_count
|
||||||
|
{
|
||||||
|
// Existing entry - load data
|
||||||
|
let current_position_to_load = app_state.current_position; // Use a copy
|
||||||
|
let load_message = UiService::load_adresar_by_position(
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut app_state, // Pass app_state mutably if needed by the service
|
||||||
|
&mut form_state,
|
||||||
|
current_position_to_load,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let current_input = form_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !event_handler.is_edit_mode
|
||||||
|
&& !current_input.is_empty()
|
||||||
|
{
|
||||||
|
current_input.len() - 1 // In readonly mode, limit to last character
|
||||||
|
} else {
|
||||||
|
current_input.len()
|
||||||
|
};
|
||||||
|
form_state.current_cursor_pos = event_handler
|
||||||
|
.ideal_cursor_column
|
||||||
|
.min(max_cursor_pos);
|
||||||
|
// Don't overwrite message from handle_event if load_message is simple success
|
||||||
|
if !load_message.starts_with("Loaded entry")
|
||||||
|
|| event_handler.command_message.is_empty()
|
||||||
|
{
|
||||||
|
event_handler.command_message = load_message;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Invalid position (e.g., 0) - reset to first entry or new entry mode
|
||||||
|
app_state.current_position =
|
||||||
|
1.min(current_total_count + 1); // Go to 1 or new entry if empty
|
||||||
|
if app_state.current_position > total_count {
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
form_state.current_field = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !position_changed && !event_handler.is_edit_mode {
|
||||||
|
// If position didn't change but we are in read-only, just adjust cursor
|
||||||
|
let current_input = form_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
|
current_input.len() - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
form_state.current_cursor_pos =
|
||||||
|
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
|
}
|
||||||
|
} else if app_state.ui.show_login {
|
||||||
|
// Handle cursor updates for AuthState if needed, similar to FormState
|
||||||
|
if !event_handler.is_edit_mode {
|
||||||
|
let current_input = auth_state.get_current_input();
|
||||||
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
|
current_input.len() - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
auth_state.current_cursor_pos =
|
||||||
|
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check exit condition *after* processing outcome
|
||||||
if should_exit {
|
if should_exit {
|
||||||
|
// terminal.cleanup()?; // Optional: Drop handles this
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import "common.proto";
|
|||||||
|
|
||||||
service AuthService {
|
service AuthService {
|
||||||
rpc Register(RegisterRequest) returns (AuthResponse);
|
rpc Register(RegisterRequest) returns (AuthResponse);
|
||||||
|
rpc Login(LoginRequest) returns (LoginResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
message RegisterRequest {
|
message RegisterRequest {
|
||||||
@@ -21,3 +22,16 @@ message AuthResponse {
|
|||||||
string email = 3; // Registered email (if provided)
|
string email = 3; // Registered email (if provided)
|
||||||
string role = 4; // Default role: 'accountant'
|
string role = 4; // Default role: 'accountant'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message LoginRequest {
|
||||||
|
string identifier = 1; // Can be username or email
|
||||||
|
string password = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message LoginResponse {
|
||||||
|
string access_token = 1; // JWT token
|
||||||
|
string token_type = 2; // Usually "Bearer"
|
||||||
|
int32 expires_in = 3; // Expiration in seconds (86400 for 24 hours)
|
||||||
|
string user_id = 4; // User's UUID in string format
|
||||||
|
string role = 5; // User's role
|
||||||
|
}
|
||||||
|
|||||||
Binary file not shown.
@@ -25,6 +25,32 @@ pub struct AuthResponse {
|
|||||||
#[prost(string, tag = "4")]
|
#[prost(string, tag = "4")]
|
||||||
pub role: ::prost::alloc::string::String,
|
pub role: ::prost::alloc::string::String,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
pub struct LoginRequest {
|
||||||
|
/// Can be username or email
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub identifier: ::prost::alloc::string::String,
|
||||||
|
#[prost(string, tag = "2")]
|
||||||
|
pub password: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
pub struct LoginResponse {
|
||||||
|
/// JWT token
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub access_token: ::prost::alloc::string::String,
|
||||||
|
/// Usually "Bearer"
|
||||||
|
#[prost(string, tag = "2")]
|
||||||
|
pub token_type: ::prost::alloc::string::String,
|
||||||
|
/// Expiration in seconds (86400 for 24 hours)
|
||||||
|
#[prost(int32, tag = "3")]
|
||||||
|
pub expires_in: i32,
|
||||||
|
/// User's UUID in string format
|
||||||
|
#[prost(string, tag = "4")]
|
||||||
|
pub user_id: ::prost::alloc::string::String,
|
||||||
|
/// User's role
|
||||||
|
#[prost(string, tag = "5")]
|
||||||
|
pub role: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
/// Generated client implementations.
|
/// Generated client implementations.
|
||||||
pub mod auth_service_client {
|
pub mod auth_service_client {
|
||||||
#![allow(
|
#![allow(
|
||||||
@@ -137,6 +163,27 @@ pub mod auth_service_client {
|
|||||||
.insert(GrpcMethod::new("multieko2.auth.AuthService", "Register"));
|
.insert(GrpcMethod::new("multieko2.auth.AuthService", "Register"));
|
||||||
self.inner.unary(req, path, codec).await
|
self.inner.unary(req, path, codec).await
|
||||||
}
|
}
|
||||||
|
pub async fn login(
|
||||||
|
&mut self,
|
||||||
|
request: impl tonic::IntoRequest<super::LoginRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::LoginResponse>, tonic::Status> {
|
||||||
|
self.inner
|
||||||
|
.ready()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tonic::Status::unknown(
|
||||||
|
format!("Service was not ready: {}", e.into()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let path = http::uri::PathAndQuery::from_static(
|
||||||
|
"/multieko2.auth.AuthService/Login",
|
||||||
|
);
|
||||||
|
let mut req = request.into_request();
|
||||||
|
req.extensions_mut()
|
||||||
|
.insert(GrpcMethod::new("multieko2.auth.AuthService", "Login"));
|
||||||
|
self.inner.unary(req, path, codec).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Generated server implementations.
|
/// Generated server implementations.
|
||||||
@@ -156,6 +203,10 @@ pub mod auth_service_server {
|
|||||||
&self,
|
&self,
|
||||||
request: tonic::Request<super::RegisterRequest>,
|
request: tonic::Request<super::RegisterRequest>,
|
||||||
) -> std::result::Result<tonic::Response<super::AuthResponse>, tonic::Status>;
|
) -> std::result::Result<tonic::Response<super::AuthResponse>, tonic::Status>;
|
||||||
|
async fn login(
|
||||||
|
&self,
|
||||||
|
request: tonic::Request<super::LoginRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::LoginResponse>, tonic::Status>;
|
||||||
}
|
}
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct AuthServiceServer<T> {
|
pub struct AuthServiceServer<T> {
|
||||||
@@ -278,6 +329,49 @@ pub mod auth_service_server {
|
|||||||
};
|
};
|
||||||
Box::pin(fut)
|
Box::pin(fut)
|
||||||
}
|
}
|
||||||
|
"/multieko2.auth.AuthService/Login" => {
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
struct LoginSvc<T: AuthService>(pub Arc<T>);
|
||||||
|
impl<T: AuthService> tonic::server::UnaryService<super::LoginRequest>
|
||||||
|
for LoginSvc<T> {
|
||||||
|
type Response = super::LoginResponse;
|
||||||
|
type Future = BoxFuture<
|
||||||
|
tonic::Response<Self::Response>,
|
||||||
|
tonic::Status,
|
||||||
|
>;
|
||||||
|
fn call(
|
||||||
|
&mut self,
|
||||||
|
request: tonic::Request<super::LoginRequest>,
|
||||||
|
) -> Self::Future {
|
||||||
|
let inner = Arc::clone(&self.0);
|
||||||
|
let fut = async move {
|
||||||
|
<T as AuthService>::login(&inner, request).await
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let accept_compression_encodings = self.accept_compression_encodings;
|
||||||
|
let send_compression_encodings = self.send_compression_encodings;
|
||||||
|
let max_decoding_message_size = self.max_decoding_message_size;
|
||||||
|
let max_encoding_message_size = self.max_encoding_message_size;
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
let fut = async move {
|
||||||
|
let method = LoginSvc(inner);
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let mut grpc = tonic::server::Grpc::new(codec)
|
||||||
|
.apply_compression_config(
|
||||||
|
accept_compression_encodings,
|
||||||
|
send_compression_encodings,
|
||||||
|
)
|
||||||
|
.apply_max_message_size_config(
|
||||||
|
max_decoding_message_size,
|
||||||
|
max_encoding_message_size,
|
||||||
|
);
|
||||||
|
let res = grpc.unary(method, req).await;
|
||||||
|
Ok(res)
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let mut response = http::Response::new(empty_body());
|
let mut response = http::Response::new(empty_body());
|
||||||
|
|||||||
22
server/.sqlx/query-468bb5bb4fdaefcb4b280761d7880a556d40c172568ad3a1ed13156fbef72776.json
generated
Normal file
22
server/.sqlx/query-468bb5bb4fdaefcb4b280761d7880a556d40c172568ad3a1ed13156fbef72776.json
generated
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "SELECT ltd.table_name\n FROM table_definition_links tdl\n JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id\n WHERE tdl.source_table_id = $1",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "table_name",
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Int8"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "468bb5bb4fdaefcb4b280761d7880a556d40c172568ad3a1ed13156fbef72776"
|
||||||
|
}
|
||||||
42
server/.sqlx/query-48d0a6d393dac121bfa4230830a105aede2179b07395f97750ab2fa1970afacd.json
generated
Normal file
42
server/.sqlx/query-48d0a6d393dac121bfa4230830a105aede2179b07395f97750ab2fa1970afacd.json
generated
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n INSERT INTO users (username, email, password_hash, role)\n VALUES ($1, $2, $3, 'accountant')\n RETURNING id, username, email, role\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "username",
|
||||||
|
"type_info": "Varchar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "email",
|
||||||
|
"type_info": "Varchar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 3,
|
||||||
|
"name": "role",
|
||||||
|
"type_info": "Varchar"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Varchar",
|
||||||
|
"Varchar",
|
||||||
|
"Varchar"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "48d0a6d393dac121bfa4230830a105aede2179b07395f97750ab2fa1970afacd"
|
||||||
|
}
|
||||||
34
server/.sqlx/query-6be0bb23ad1ba85add309f6e4f55495a5d248901fb0d23fea908815747a0bd50.json
generated
Normal file
34
server/.sqlx/query-6be0bb23ad1ba85add309f6e4f55495a5d248901fb0d23fea908815747a0bd50.json
generated
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n SELECT id, password_hash, role\n FROM users\n WHERE username = $1 OR email = $1\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "password_hash",
|
||||||
|
"type_info": "Varchar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "role",
|
||||||
|
"type_info": "Varchar"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Text"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "6be0bb23ad1ba85add309f6e4f55495a5d248901fb0d23fea908815747a0bd50"
|
||||||
|
}
|
||||||
23
server/.sqlx/query-80f0f7f9ab12a8fe07ea71b548d27bcd6253b598ac4486b72b3d960f03df47f3.json
generated
Normal file
23
server/.sqlx/query-80f0f7f9ab12a8fe07ea71b548d27bcd6253b598ac4486b72b3d960f03df47f3.json
generated
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "SELECT table_name FROM table_definitions\n WHERE profile_id = $1 AND table_name LIKE $2",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "table_name",
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Int8",
|
||||||
|
"Text"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "80f0f7f9ab12a8fe07ea71b548d27bcd6253b598ac4486b72b3d960f03df47f3"
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"db_name": "PostgreSQL",
|
|
||||||
"query": "SELECT ltd.table_name \n FROM table_definition_links tdl\n JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id\n WHERE tdl.source_table_id = $1 AND tdl.is_required = true",
|
|
||||||
"describe": {
|
|
||||||
"columns": [
|
|
||||||
{
|
|
||||||
"ordinal": 0,
|
|
||||||
"name": "table_name",
|
|
||||||
"type_info": "Text"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"parameters": {
|
|
||||||
"Left": [
|
|
||||||
"Int8"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"nullable": [
|
|
||||||
false
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"hash": "b097f30f98490b979939759d85327a20ca7ade4866052a5cfdb0451fb76fbf15"
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "PostgreSQL",
|
"db_name": "PostgreSQL",
|
||||||
"query": "INSERT INTO table_scripts\n (table_definitions_id, target_column, target_column_type, script, description)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id",
|
"query": "INSERT INTO table_scripts\n (table_definitions_id, target_table, target_column,\n target_column_type, script, description, profile_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id",
|
||||||
"describe": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -15,12 +15,14 @@
|
|||||||
"Text",
|
"Text",
|
||||||
"Text",
|
"Text",
|
||||||
"Text",
|
"Text",
|
||||||
"Text"
|
"Text",
|
||||||
|
"Text",
|
||||||
|
"Int8"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"nullable": [
|
"nullable": [
|
||||||
false
|
false
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "4cd5de4d3332ca35a9975ffb32728041978435e14f97c559e2ffec4a82d567ae"
|
"hash": "c07a8511e5f32bf230240b28cb292d40f862b6ec58883f21ee8e1937860585d6"
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,8 @@ lazy_static = "1.5.0"
|
|||||||
regex = "1.11.1"
|
regex = "1.11.1"
|
||||||
bcrypt = "0.17.0"
|
bcrypt = "0.17.0"
|
||||||
validator = { version = "0.20.0", features = ["derive"] }
|
validator = { version = "0.20.0", features = ["derive"] }
|
||||||
uuid = { version = "1.16.0", features = ["v4"] }
|
uuid = { version = "1.16.0", features = ["serde", "v4"] }
|
||||||
|
jsonwebtoken = "9.3.1"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "server"
|
name = "server"
|
||||||
|
|||||||
51
server/src/auth/docs/reg_log.txt
Normal file
51
server/src/auth/docs/reg_log.txt
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
❯ grpcurl -plaintext -d '{
|
||||||
|
"username": "testuser3",
|
||||||
|
"email": "test3@example.com",
|
||||||
|
"password": "your_password",
|
||||||
|
"password_confirmation": "your_password"
|
||||||
|
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||||
|
{
|
||||||
|
"id": "96d2fd35-b39d-4c05-916a-66134453d34c",
|
||||||
|
"username": "testuser3",
|
||||||
|
"email": "test3@example.com",
|
||||||
|
"role": "accountant"
|
||||||
|
}
|
||||||
|
❯ grpcurl -plaintext -d '{
|
||||||
|
"identifier": "testuser3"
|
||||||
|
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||||
|
ERROR:
|
||||||
|
Code: Unauthenticated
|
||||||
|
Message: Invalid credentials
|
||||||
|
❯ grpcurl -plaintext -d '{
|
||||||
|
"identifier": "testuser3",
|
||||||
|
"password": "your_password"
|
||||||
|
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||||
|
{
|
||||||
|
"accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI5NmQyZmQzNS1iMzlkLTRjMDUtOTE2YS02NjEzNDQ1M2QzNGMiLCJleHAiOjE3NDI5ODE2MTAsInJvbGUiOiJhY2NvdW50YW50In0.78VIR3X4QZohzeI5x3xmkmqcICTusOC6PELPohMV-k8",
|
||||||
|
"tokenType": "Bearer",
|
||||||
|
"expiresIn": 86400,
|
||||||
|
"userId": "96d2fd35-b39d-4c05-916a-66134453d34c",
|
||||||
|
"role": "accountant"
|
||||||
|
}
|
||||||
|
❯ grpcurl -plaintext -d '{
|
||||||
|
"username": "testuser4",
|
||||||
|
"email": "test4@example.com"
|
||||||
|
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||||
|
{
|
||||||
|
"id": "413d7ecc-f231-48af-8c5a-566b1dc2bf0b",
|
||||||
|
"username": "testuser4",
|
||||||
|
"email": "test4@example.com",
|
||||||
|
"role": "accountant"
|
||||||
|
}
|
||||||
|
❯ grpcurl -plaintext -d '{
|
||||||
|
"identifier": "test4@example.com"
|
||||||
|
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||||
|
{
|
||||||
|
"accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MTNkN2VjYy1mMjMxLTQ4YWYtOGM1YS01NjZiMWRjMmJmMGIiLCJleHAiOjE3NDI5ODE3MDEsInJvbGUiOiJhY2NvdW50YW50In0.4Hzu3tTZRNGHnBSgeCbGy2tFTl8EzpPdXBhcW8kuIc8",
|
||||||
|
"tokenType": "Bearer",
|
||||||
|
"expiresIn": 86400,
|
||||||
|
"userId": "413d7ecc-f231-48af-8c5a-566b1dc2bf0b",
|
||||||
|
"role": "accountant"
|
||||||
|
}
|
||||||
|
╭─ ~/Doc/pr/multieko2/server auth ······ ✔
|
||||||
|
╰─
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
// src/auth/handlers.rs
|
// src/auth/handlers.rs
|
||||||
|
|
||||||
pub mod register;
|
pub mod register;
|
||||||
|
pub mod login;
|
||||||
|
|
||||||
pub use register::*;
|
pub use register::*;
|
||||||
|
pub use login::*;
|
||||||
|
|||||||
46
server/src/auth/handlers/login.rs
Normal file
46
server/src/auth/handlers/login.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
// src/auth/handlers/login.rs
|
||||||
|
use bcrypt::verify;
|
||||||
|
use tonic::{Request, Response, Status};
|
||||||
|
use crate::db::PgPool;
|
||||||
|
use crate::auth::{models::AuthError, logic::jwt}; // Fixed import path
|
||||||
|
use common::proto::multieko2::auth::{LoginRequest, LoginResponse};
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
pool: &PgPool,
|
||||||
|
request: LoginRequest,
|
||||||
|
) -> Result<Response<LoginResponse>, Status> {
|
||||||
|
let user = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
SELECT id, password_hash, role
|
||||||
|
FROM users
|
||||||
|
WHERE username = $1 OR email = $1
|
||||||
|
"#,
|
||||||
|
request.identifier
|
||||||
|
)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Status::internal(e.to_string()))?
|
||||||
|
.ok_or_else(|| Status::unauthenticated("Invalid credentials"))?;
|
||||||
|
|
||||||
|
// Handle the optional password_hash
|
||||||
|
let password_hash = user.password_hash
|
||||||
|
.ok_or_else(|| Status::internal("User account has no password set"))?;
|
||||||
|
|
||||||
|
// Verify the password
|
||||||
|
if !verify(&request.password, &password_hash)
|
||||||
|
.map_err(|e| Status::internal(e.to_string()))?
|
||||||
|
{
|
||||||
|
return Err(Status::unauthenticated("Invalid credentials"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let token = jwt::generate_token(user.id, &user.role)
|
||||||
|
.map_err(|e| Status::internal(e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(Response::new(LoginResponse {
|
||||||
|
access_token: token,
|
||||||
|
token_type: "Bearer".to_string(),
|
||||||
|
expires_in: 86400, // 24 hours
|
||||||
|
user_id: user.id.to_string(),
|
||||||
|
role: user.role,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -1,64 +1,48 @@
|
|||||||
// src/auth/handlers/register.rs
|
// src/auth/handlers/register.rs
|
||||||
|
|
||||||
use bcrypt::{hash, DEFAULT_COST};
|
use bcrypt::{hash, DEFAULT_COST};
|
||||||
use tonic::{Request, Response, Status};
|
use tonic::{Response, Status};
|
||||||
use common::proto::multieko2::auth::{auth_service_server, RegisterRequest, AuthResponse};
|
use common::proto::multieko2::auth::{RegisterRequest, AuthResponse};
|
||||||
use crate::db::PgPool;
|
use crate::db::PgPool;
|
||||||
use crate::auth::models::AuthError;
|
use crate::auth::models::AuthError;
|
||||||
|
|
||||||
pub struct AuthService {
|
pub async fn register(
|
||||||
pool: PgPool,
|
pool: &PgPool,
|
||||||
}
|
payload: RegisterRequest,
|
||||||
|
) -> Result<Response<AuthResponse>, Status> {
|
||||||
impl AuthService {
|
// Validate passwords match
|
||||||
pub fn new(pool: PgPool) -> Self {
|
if payload.password != payload.password_confirmation {
|
||||||
Self { pool }
|
return Err(Status::invalid_argument(AuthError::PasswordMismatch.to_string()));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[tonic::async_trait]
|
// Hash password
|
||||||
impl auth_service_server::AuthService for AuthService {
|
let password_hash = hash(payload.password, DEFAULT_COST)
|
||||||
async fn register(
|
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
|
||||||
&self,
|
|
||||||
request: Request<RegisterRequest>,
|
|
||||||
) -> Result<Response<AuthResponse>, Status> {
|
|
||||||
let payload = request.into_inner();
|
|
||||||
|
|
||||||
// Validate passwords match
|
// Insert user
|
||||||
if payload.password != payload.password_confirmation {
|
let user = sqlx::query!(
|
||||||
return Err(Status::invalid_argument(AuthError::PasswordMismatch.to_string()));
|
r#"
|
||||||
|
INSERT INTO users (username, email, password_hash, role)
|
||||||
|
VALUES ($1, $2, $3, 'accountant')
|
||||||
|
RETURNING id, username, email, role
|
||||||
|
"#,
|
||||||
|
payload.username,
|
||||||
|
payload.email,
|
||||||
|
password_hash
|
||||||
|
)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
if e.to_string().contains("duplicate key") {
|
||||||
|
Status::already_exists(AuthError::UserExists.to_string())
|
||||||
|
} else {
|
||||||
|
Status::internal(AuthError::DatabaseError(e.to_string()).to_string())
|
||||||
}
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
// Hash password
|
Ok(Response::new(AuthResponse {
|
||||||
let password_hash = hash(payload.password, DEFAULT_COST)
|
id: user.id.to_string(),
|
||||||
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
|
username: user.username,
|
||||||
|
email: user.email.unwrap_or_default(),
|
||||||
// Insert user
|
role: user.role,
|
||||||
let user = sqlx::query!(
|
}))
|
||||||
r#"
|
|
||||||
INSERT INTO users (username, email, password_hash, role)
|
|
||||||
VALUES ($1, $2, $3, 'accountant')
|
|
||||||
RETURNING id, username, email, role
|
|
||||||
"#,
|
|
||||||
payload.username,
|
|
||||||
payload.email,
|
|
||||||
password_hash
|
|
||||||
)
|
|
||||||
.fetch_one(&self.pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| {
|
|
||||||
if e.to_string().contains("duplicate key") {
|
|
||||||
Status::already_exists(AuthError::UserExists.to_string())
|
|
||||||
} else {
|
|
||||||
Status::internal(AuthError::DatabaseError(e.to_string()).to_string())
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(Response::new(AuthResponse {
|
|
||||||
id: user.id.to_string(),
|
|
||||||
username: user.username,
|
|
||||||
email: user.email.unwrap_or_default(),
|
|
||||||
role: user.role,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
9
server/src/auth/logic.rs
Normal file
9
server/src/auth/logic.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// src/auth/logic.rs
|
||||||
|
|
||||||
|
pub mod jwt;
|
||||||
|
pub mod middleware;
|
||||||
|
// TODO implement RBAC on all of the endpoints
|
||||||
|
// pub mod rbac;
|
||||||
|
|
||||||
|
pub use jwt::*;
|
||||||
|
pub use middleware::*;
|
||||||
55
server/src/auth/logic/jwt.rs
Normal file
55
server/src/auth/logic/jwt.rs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
// src/auth/jwt.rs
|
||||||
|
use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use time::{Duration, OffsetDateTime};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
use crate::auth::models::AuthError;
|
||||||
|
|
||||||
|
static KEYS: OnceLock<Keys> = OnceLock::new();
|
||||||
|
|
||||||
|
struct Keys {
|
||||||
|
encoding: EncodingKey,
|
||||||
|
decoding: DecodingKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
pub struct Claims {
|
||||||
|
pub sub: Uuid, // User ID
|
||||||
|
pub exp: i64, // Expiration time
|
||||||
|
pub role: String, // User role
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init_jwt() -> Result<(), AuthError> {
|
||||||
|
let secret = std::env::var("JWT_SECRET")
|
||||||
|
.map_err(|_| AuthError::ConfigError("JWT_SECRET must be set".to_string()))?;
|
||||||
|
|
||||||
|
KEYS.set(Keys {
|
||||||
|
encoding: EncodingKey::from_secret(secret.as_bytes()),
|
||||||
|
decoding: DecodingKey::from_secret(secret.as_bytes()),
|
||||||
|
}).map_err(|_| AuthError::ConfigError("Failed to initialize JWT keys".to_string()))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_token(user_id: Uuid, role: &str) -> Result<String, AuthError> {
|
||||||
|
let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?;
|
||||||
|
|
||||||
|
let exp = OffsetDateTime::now_utc() + Duration::days(365000);
|
||||||
|
let claims = Claims {
|
||||||
|
sub: user_id,
|
||||||
|
exp: exp.unix_timestamp(),
|
||||||
|
role: role.to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
encode(&Header::default(), &claims, &keys.encoding)
|
||||||
|
.map_err(|e| AuthError::JwtError(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_token(token: &str) -> Result<Claims, AuthError> {
|
||||||
|
let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?;
|
||||||
|
|
||||||
|
decode::<Claims>(token, &keys.decoding, &Validation::default())
|
||||||
|
.map(|data| data.claims)
|
||||||
|
.map_err(|e| AuthError::JwtError(e.to_string()))
|
||||||
|
}
|
||||||
22
server/src/auth/logic/middleware.rs
Normal file
22
server/src/auth/logic/middleware.rs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
// src/auth/middleware.rs
|
||||||
|
use tonic::{metadata::MetadataValue, service::Interceptor, Status};
|
||||||
|
use crate::auth::{logic::jwt, models::AuthError};
|
||||||
|
|
||||||
|
pub struct AuthInterceptor;
|
||||||
|
|
||||||
|
impl Interceptor for AuthInterceptor {
|
||||||
|
fn call(&mut self, mut request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
|
||||||
|
let metadata = request.metadata();
|
||||||
|
let token = metadata.get("authorization")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|s| s.strip_prefix("Bearer "))
|
||||||
|
.ok_or(Status::unauthenticated("Missing authorization header"))?;
|
||||||
|
|
||||||
|
let claims = jwt::validate_token(token)
|
||||||
|
.map_err(|e| Status::unauthenticated(e.to_string()))?;
|
||||||
|
|
||||||
|
// Store claims in request extensions
|
||||||
|
request.extensions_mut().insert(claims);
|
||||||
|
Ok(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
36
server/src/auth/logic/rbac.rs
Normal file
36
server/src/auth/logic/rbac.rs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
// src/auth/logic/rbac.rs
|
||||||
|
|
||||||
|
use tower::ServiceBuilder;
|
||||||
|
use crate::auth::logic::rbac;
|
||||||
|
|
||||||
|
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// ... existing setup code ...
|
||||||
|
|
||||||
|
// Create service layers
|
||||||
|
let adresar_layer = ServiceBuilder::new()
|
||||||
|
.layer(rbac::create_adresar_layer())
|
||||||
|
.into_inner();
|
||||||
|
|
||||||
|
let uctovnictvo_layer = ServiceBuilder::new()
|
||||||
|
.layer(rbac::create_uctovnictvo_layer())
|
||||||
|
.into_inner();
|
||||||
|
|
||||||
|
// Create services with layers
|
||||||
|
let adresar_service = AdresarServer::new(AdresarService { db_pool: db_pool.clone() })
|
||||||
|
.layer(adresar_layer);
|
||||||
|
|
||||||
|
let uctovnictvo_service = UctovnictvoServer::new(UctovnictvoService { db_pool: db_pool.clone() })
|
||||||
|
.layer(uctovnictvo_layer);
|
||||||
|
|
||||||
|
// ... repeat for other services ...
|
||||||
|
|
||||||
|
Server::builder()
|
||||||
|
.add_service(auth_server)
|
||||||
|
.add_service(adresar_service)
|
||||||
|
.add_service(uctovnictvo_service)
|
||||||
|
// ... other services ...
|
||||||
|
.serve(addr)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
// src/auth/mod.rs
|
// src/auth/mod.rs
|
||||||
|
|
||||||
pub mod models;
|
pub mod models;
|
||||||
|
pub mod logic;
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ pub struct RegisterRequest {
|
|||||||
pub password_confirmation: String,
|
pub password_confirmation: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Validate, Deserialize)]
|
||||||
|
pub struct LoginRequest {
|
||||||
|
#[validate(length(min = 1))]
|
||||||
|
pub identifier: String,
|
||||||
|
#[validate(length(min = 1))]
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum AuthError {
|
pub enum AuthError {
|
||||||
#[error("Passwords do not match")]
|
#[error("Passwords do not match")]
|
||||||
@@ -24,4 +32,10 @@ pub enum AuthError {
|
|||||||
DatabaseError(String),
|
DatabaseError(String),
|
||||||
#[error("Hashing error: {0}")]
|
#[error("Hashing error: {0}")]
|
||||||
HashingError(String),
|
HashingError(String),
|
||||||
|
#[error("Invalid credentials")]
|
||||||
|
InvalidCredentials,
|
||||||
|
#[error("JWT error: {0}")]
|
||||||
|
JwtError(String),
|
||||||
|
#[error("Configuration error: {0}")]
|
||||||
|
ConfigError(String),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use crate::server::services::{
|
|||||||
TableDefinitionService,
|
TableDefinitionService,
|
||||||
TablesDataService,
|
TablesDataService,
|
||||||
TableScriptService,
|
TableScriptService,
|
||||||
|
AuthServiceImpl
|
||||||
};
|
};
|
||||||
use common::proto::multieko2::{
|
use common::proto::multieko2::{
|
||||||
adresar::adresar_server::AdresarServer,
|
adresar::adresar_server::AdresarServer,
|
||||||
@@ -18,11 +19,13 @@ use common::proto::multieko2::{
|
|||||||
table_definition::table_definition_server::TableDefinitionServer,
|
table_definition::table_definition_server::TableDefinitionServer,
|
||||||
tables_data::tables_data_server::TablesDataServer,
|
tables_data::tables_data_server::TablesDataServer,
|
||||||
table_script::table_script_server::TableScriptServer,
|
table_script::table_script_server::TableScriptServer,
|
||||||
auth::auth_service_server::AuthServiceServer // Add this import
|
auth::auth_service_server::AuthServiceServer
|
||||||
};
|
};
|
||||||
use crate::auth::handlers::AuthService; // Add this import
|
|
||||||
|
|
||||||
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// Initialize JWT for authentication
|
||||||
|
crate::auth::logic::jwt::init_jwt()?;
|
||||||
|
|
||||||
let addr = "[::1]:50051".parse()?;
|
let addr = "[::1]:50051".parse()?;
|
||||||
|
|
||||||
let reflection_service = ReflectionBuilder::configure()
|
let reflection_service = ReflectionBuilder::configure()
|
||||||
@@ -33,7 +36,7 @@ pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error:
|
|||||||
let table_definition_service = TableDefinitionService { db_pool: db_pool.clone() };
|
let table_definition_service = TableDefinitionService { db_pool: db_pool.clone() };
|
||||||
let tables_data_service = TablesDataService { db_pool: db_pool.clone() };
|
let tables_data_service = TablesDataService { db_pool: db_pool.clone() };
|
||||||
let table_script_service = TableScriptService { db_pool: db_pool.clone() };
|
let table_script_service = TableScriptService { db_pool: db_pool.clone() };
|
||||||
let auth_service = AuthService::new(db_pool.clone()); // Add this line
|
let auth_service = AuthServiceImpl { db_pool: db_pool.clone() };
|
||||||
|
|
||||||
Server::builder()
|
Server::builder()
|
||||||
.add_service(AdresarServer::new(AdresarService { db_pool: db_pool.clone() }))
|
.add_service(AdresarServer::new(AdresarService { db_pool: db_pool.clone() }))
|
||||||
|
|||||||
36
server/src/server/services/auth_service.rs
Normal file
36
server/src/server/services/auth_service.rs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
// src/server/services/auth_service.rs
|
||||||
|
use tonic::{Request, Response, Status};
|
||||||
|
use common::proto::multieko2::auth::{
|
||||||
|
auth_service_server::AuthService,
|
||||||
|
RegisterRequest, AuthResponse,
|
||||||
|
LoginRequest, LoginResponse
|
||||||
|
};
|
||||||
|
use crate::auth::handlers::{
|
||||||
|
login::login,
|
||||||
|
register::register
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct AuthServiceImpl {
|
||||||
|
pub db_pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl AuthService for AuthServiceImpl {
|
||||||
|
async fn register(
|
||||||
|
&self,
|
||||||
|
request: Request<RegisterRequest>,
|
||||||
|
) -> Result<Response<AuthResponse>, Status> {
|
||||||
|
let response = register(&self.db_pool, request.into_inner()).await?;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(
|
||||||
|
&self,
|
||||||
|
request: Request<LoginRequest>,
|
||||||
|
) -> Result<Response<LoginResponse>, Status> {
|
||||||
|
let response = login(&self.db_pool, request.into_inner()).await?;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ pub mod uctovnictvo_service;
|
|||||||
pub mod table_definition_service;
|
pub mod table_definition_service;
|
||||||
pub mod tables_data_service;
|
pub mod tables_data_service;
|
||||||
pub mod table_script_service;
|
pub mod table_script_service;
|
||||||
|
pub mod auth_service;
|
||||||
|
|
||||||
pub use adresar_service::AdresarService;
|
pub use adresar_service::AdresarService;
|
||||||
pub use table_structure_service::TableStructureHandler;
|
pub use table_structure_service::TableStructureHandler;
|
||||||
@@ -13,3 +14,4 @@ pub use uctovnictvo_service::UctovnictvoService;
|
|||||||
pub use table_definition_service::TableDefinitionService;
|
pub use table_definition_service::TableDefinitionService;
|
||||||
pub use tables_data_service::TablesDataService;
|
pub use tables_data_service::TablesDataService;
|
||||||
pub use table_script_service::TableScriptService;
|
pub use table_script_service::TableScriptService;
|
||||||
|
pub use auth_service::AuthServiceImpl;
|
||||||
|
|||||||
Reference in New Issue
Block a user