Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e101bef14 | ||
|
|
149949ad99 | ||
|
|
741cc952fa | ||
|
|
d2bb7a0bf4 | ||
|
|
d4d5bcec9e | ||
|
|
b4053a7b94 | ||
|
|
7b27d00972 | ||
|
|
f4d234089f | ||
|
|
50a329fc0d | ||
|
|
6d6df7ca5c | ||
|
|
6b16068706 | ||
|
|
024a0de4af | ||
|
|
e145d63ba6 | ||
|
|
e7e8b0b3f6 | ||
|
|
a7389db674 | ||
|
|
cf1aa4fd2a | ||
|
|
0fd2a589eb |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -428,6 +428,7 @@ dependencies = [
|
||||
"crossterm",
|
||||
"dirs 6.0.0",
|
||||
"dotenvy",
|
||||
"lazy_static",
|
||||
"prost",
|
||||
"ratatui",
|
||||
"serde",
|
||||
@@ -435,6 +436,7 @@ dependencies = [
|
||||
"toml",
|
||||
"tonic",
|
||||
"tracing",
|
||||
"unicode-width 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -11,6 +11,7 @@ common = { path = "../common" }
|
||||
crossterm = "0.28.1"
|
||||
dirs = "6.0.0"
|
||||
dotenvy = "0.15.7"
|
||||
lazy_static = "1.5.0"
|
||||
prost = "0.13.5"
|
||||
ratatui = "0.29.0"
|
||||
serde = { version = "1.0.218", features = ["derive"] }
|
||||
@@ -18,3 +19,4 @@ tokio = { version = "1.43.0", features = ["full", "macros"] }
|
||||
toml = "0.8.20"
|
||||
tonic = "0.12.3"
|
||||
tracing = "0.1.41"
|
||||
unicode-width = "0.2.0"
|
||||
|
||||
@@ -50,10 +50,14 @@ move_last_line = ["x"]
|
||||
exit_edit_mode = ["esc","ctrl+e"]
|
||||
delete_char_forward = ["delete"]
|
||||
delete_char_backward = ["backspace"]
|
||||
next_field = ["tab", "enter"]
|
||||
prev_field = ["shift+tab", "backtab"]
|
||||
next_field = ["enter"]
|
||||
prev_field = ["shift+enter"]
|
||||
move_left = ["left"]
|
||||
move_right = ["right"]
|
||||
suggestion_down = ["ctrl+n", "tab"]
|
||||
suggestion_up = ["ctrl+p", "shift+tab"]
|
||||
select_suggestion = ["enter"]
|
||||
exit_suggestion_mode = ["esc"]
|
||||
|
||||
[keybindings.command]
|
||||
exit_command_mode = ["ctrl+g", "esc"]
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
use crate::{
|
||||
config::colors::themes::Theme,
|
||||
state::pages::auth::RegisterState, // Use RegisterState
|
||||
components::common::dialog,
|
||||
components::common::{dialog, autocomplete},
|
||||
state::state::AppState,
|
||||
state::canvas_state::CanvasState,
|
||||
modes::handlers::mode_manager::AppMode,
|
||||
};
|
||||
use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
|
||||
style::{Style, Modifier, Color},
|
||||
widgets::{Block, BorderType, Borders, Paragraph},
|
||||
widgets::{Block, BorderType, Borders, Paragraph, Wrap},
|
||||
Frame,
|
||||
};
|
||||
|
||||
@@ -39,32 +41,29 @@ pub fn render_register(
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(6), // Form (4 fields + padding)
|
||||
Constraint::Length(7), // Form (5 fields + padding)
|
||||
Constraint::Length(1), // Error message
|
||||
Constraint::Length(3), // Buttons
|
||||
])
|
||||
.split(inner_area);
|
||||
|
||||
// --- FORM RENDERING ---
|
||||
crate::components::handlers::canvas::render_canvas(
|
||||
// --- FORM RENDERING (Using render_canvas) ---
|
||||
let active_field_rect = crate::components::handlers::canvas::render_canvas(
|
||||
f,
|
||||
chunks[0],
|
||||
state, // Pass RegisterState
|
||||
&[ // Update field labels
|
||||
chunks[0], // Area for the canvas
|
||||
state, // The state object (RegisterState)
|
||||
&[ // Field labels
|
||||
"Username",
|
||||
"Email (Optional)",
|
||||
"Password (Optional)",
|
||||
"Confirm Password",
|
||||
"Role (Optional)",
|
||||
],
|
||||
&state.current_field,
|
||||
&[ // Update values from RegisterState
|
||||
&state.username,
|
||||
&state.email,
|
||||
&state.password,
|
||||
&state.password_confirmation,
|
||||
],
|
||||
&state.current_field(), // Pass current field index
|
||||
&state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(), // Pass inputs directly
|
||||
theme,
|
||||
is_edit_mode,
|
||||
// No need to pass suggestion state here, render_canvas uses the trait
|
||||
);
|
||||
|
||||
// --- ERROR MESSAGE ---
|
||||
@@ -137,6 +136,18 @@ pub fn render_register(
|
||||
button_chunks[1],
|
||||
);
|
||||
|
||||
// --- Render Autocomplete Dropdown (Draw AFTER buttons) ---
|
||||
if app_state.current_mode == AppMode::Edit {
|
||||
if let Some(suggestions) = state.get_suggestions() {
|
||||
let selected = state.get_selected_suggestion_index();
|
||||
if !suggestions.is_empty() {
|
||||
if let Some(input_rect) = active_field_rect {
|
||||
autocomplete::render_autocomplete_dropdown(f, input_rect, f.size(), theme, suggestions, selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- DIALOG --- (Keep dialog logic)
|
||||
if app_state.ui.dialog.dialog_show {
|
||||
dialog::render_dialog(
|
||||
@@ -150,4 +161,3 @@ pub fn render_register(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,10 @@ pub mod command_line;
|
||||
pub mod status_line;
|
||||
pub mod background;
|
||||
pub mod dialog;
|
||||
pub mod autocomplete;
|
||||
|
||||
pub use command_line::*;
|
||||
pub use status_line::*;
|
||||
pub use background::*;
|
||||
pub use dialog::*;
|
||||
pub use autocomplete::*;
|
||||
|
||||
90
client/src/components/common/autocomplete.rs
Normal file
90
client/src/components/common/autocomplete.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
// src/components/common/autocomplete.rs
|
||||
|
||||
use crate::config::colors::themes::Theme;
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Color, Modifier, Style},
|
||||
widgets::{Block, List, ListItem, ListState},
|
||||
Frame,
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Renders an opaque dropdown list for autocomplete suggestions.
|
||||
pub fn render_autocomplete_dropdown(
|
||||
f: &mut Frame,
|
||||
input_rect: Rect,
|
||||
frame_area: Rect,
|
||||
theme: &Theme,
|
||||
suggestions: &[String],
|
||||
selected_index: Option<usize>,
|
||||
) {
|
||||
if suggestions.is_empty() {
|
||||
return;
|
||||
}
|
||||
// --- Calculate Dropdown Size & Position ---
|
||||
let max_suggestion_width = suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
|
||||
let horizontal_padding: u16 = 2;
|
||||
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
|
||||
let dropdown_height = (suggestions.len() as u16).min(5);
|
||||
|
||||
let mut dropdown_area = Rect {
|
||||
x: input_rect.x, // Align horizontally with input
|
||||
y: input_rect.y + 1, // Position directly below input
|
||||
width: dropdown_width,
|
||||
height: dropdown_height,
|
||||
};
|
||||
|
||||
// --- Clamping Logic (prevent rendering off-screen) ---
|
||||
// Clamp vertically (if it goes below the frame)
|
||||
if dropdown_area.bottom() > frame_area.height {
|
||||
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height); // Try rendering above
|
||||
}
|
||||
// Clamp horizontally (if it goes past the right edge)
|
||||
if dropdown_area.right() > frame_area.width {
|
||||
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
|
||||
}
|
||||
// Ensure x is not negative (if clamping pushes it left)
|
||||
dropdown_area.x = dropdown_area.x.max(0);
|
||||
// Ensure y is not negative (if clamping pushes it up)
|
||||
dropdown_area.y = dropdown_area.y.max(0);
|
||||
// --- End Clamping ---
|
||||
|
||||
// Render a solid background block first to ensure opacity
|
||||
let background_block = Block::default().style(Style::default().bg(Color::DarkGray));
|
||||
f.render_widget(background_block, dropdown_area);
|
||||
|
||||
// Create list items, ensuring each has a defined background
|
||||
let items: Vec<ListItem> = suggestions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| {
|
||||
let is_selected = selected_index == Some(i);
|
||||
let s_width = s.width() as u16;
|
||||
let padding_needed = dropdown_width.saturating_sub(s_width);
|
||||
let padded_s = format!("{}{}", s, " ".repeat(padding_needed as usize));
|
||||
|
||||
ListItem::new(padded_s).style(if is_selected {
|
||||
Style::default()
|
||||
.fg(theme.bg) // Text color on highlight
|
||||
.bg(theme.highlight) // Highlight background
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
// Style for non-selected items (matching background block)
|
||||
Style::default()
|
||||
.fg(theme.fg) // Text color on gray
|
||||
.bg(Color::DarkGray) // Explicit gray background
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Create the list widget (without its own block)
|
||||
let list = List::new(items);
|
||||
|
||||
// State for managing selection highlight (still needed for logic)
|
||||
let mut list_state = ListState::default();
|
||||
list_state.select(selected_index);
|
||||
|
||||
// Render the list statefully *over* the background block
|
||||
f.render_stateful_widget(list, dropdown_area, &mut list_state);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ use ratatui::{
|
||||
};
|
||||
use crate::config::colors::themes::Theme;
|
||||
use crate::state::canvas_state::CanvasState;
|
||||
use crate::components::common::autocomplete;
|
||||
use crate::components::render_autocomplete_dropdown;
|
||||
|
||||
pub fn render_canvas(
|
||||
f: &mut Frame,
|
||||
@@ -19,7 +21,7 @@ pub fn render_canvas(
|
||||
inputs: &[&String],
|
||||
theme: &Theme,
|
||||
is_edit_mode: bool,
|
||||
) {
|
||||
) -> Option<Rect> {
|
||||
// Split area into columns
|
||||
let columns = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
@@ -56,6 +58,8 @@ pub fn render_canvas(
|
||||
.constraints(vec![Constraint::Length(1); fields.len()])
|
||||
.split(input_area);
|
||||
|
||||
let mut active_field_input_rect = None;
|
||||
|
||||
// Render labels
|
||||
for (i, field) in fields.iter().enumerate() {
|
||||
let label = Paragraph::new(Line::from(Span::styled(
|
||||
@@ -84,9 +88,12 @@ pub fn render_canvas(
|
||||
f.render_widget(input_display, input_rows[i]);
|
||||
|
||||
if is_active {
|
||||
active_field_input_rect = Some(input_rows[i]);
|
||||
let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16;
|
||||
let cursor_y = input_rows[i].y;
|
||||
f.set_cursor_position((cursor_x, cursor_y));
|
||||
}
|
||||
}
|
||||
|
||||
active_field_input_rect
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::state::canvas_state::CanvasState;
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::state::pages::auth::RegisterState;
|
||||
use crate::tui::functions::common::form::{revert, save};
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use std::any::Any;
|
||||
@@ -56,7 +57,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute_edit_action<S: CanvasState>(
|
||||
pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
||||
action: &str,
|
||||
key: KeyEvent,
|
||||
state: &mut S,
|
||||
@@ -297,6 +298,60 @@ pub async fn execute_edit_action<S: CanvasState>(
|
||||
Ok("Moved to previous word end".to_string())
|
||||
}
|
||||
|
||||
// --- Autocomplete Actions ---
|
||||
"suggestion_down" | "suggestion_up" | "select_suggestion" | "exit_suggestion_mode" => {
|
||||
// Attempt to downcast to RegisterState
|
||||
if let Some(register_state) = (state as &mut dyn Any).downcast_mut::<RegisterState>() {
|
||||
// Only handle if it's the role field (index 4) and suggestions are shown (except for hide)
|
||||
if register_state.current_field() == 4 {
|
||||
match action {
|
||||
"suggestion_down" if register_state.in_suggestion_mode => {
|
||||
let max_index = register_state.role_suggestions.len().saturating_sub(1);
|
||||
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
|
||||
register_state.selected_suggestion_index = Some(if current_index >= max_index { 0 } else { current_index + 1 });
|
||||
Ok("Suggestion changed down".to_string())
|
||||
}
|
||||
"suggestion_up" if register_state.in_suggestion_mode => {
|
||||
let max_index = register_state.role_suggestions.len().saturating_sub(1);
|
||||
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
|
||||
register_state.selected_suggestion_index = Some(if current_index == 0 { max_index } else { current_index.saturating_sub(1) });
|
||||
Ok("Suggestion changed up".to_string())
|
||||
}
|
||||
"select_suggestion" if register_state.in_suggestion_mode => {
|
||||
if let Some(index) = register_state.selected_suggestion_index {
|
||||
let selected_role = register_state.role_suggestions[index].clone();
|
||||
register_state.role = selected_role.clone(); // Update the role field
|
||||
register_state.in_suggestion_mode = false; // Exit suggestion mode
|
||||
register_state.show_role_suggestions = false; // Hide suggestions
|
||||
register_state.selected_suggestion_index = None; // Clear selection
|
||||
Ok(format!("Selected role: {}", selected_role)) // Return success message
|
||||
} else {
|
||||
Ok("No suggestion selected".to_string())
|
||||
|
||||
}
|
||||
}
|
||||
"exit_suggestion_mode" => { // Handle Esc
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
register_state.in_suggestion_mode = false;
|
||||
Ok("Suggestions hidden".to_string())
|
||||
}
|
||||
"suggestion_down" | "suggestion_up" | "select_suggestion" => {
|
||||
Ok("Suggestion action ignored: Not in suggestion mode.".to_string())
|
||||
}
|
||||
_ => Ok("".to_string())
|
||||
}
|
||||
} else {
|
||||
Ok("".to_string())
|
||||
}
|
||||
} else {
|
||||
// Downcast failed - this action is only for RegisterState
|
||||
Ok(format!("Action '{}' not applicable for this form type.", action))
|
||||
}
|
||||
}
|
||||
// --- End Autocomplete Actions ---
|
||||
|
||||
|
||||
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::state::pages::{auth::{AuthState, RegisterState}};
|
||||
use crate::state::canvas_state::CanvasState;
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::functions::modes::edit::{auth_e, form_e};
|
||||
use crate::modes::handlers::event::EventOutcome;
|
||||
use crate::state::state::AppState;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
pub async fn handle_edit_event(
|
||||
key: KeyEvent,
|
||||
@@ -79,6 +80,21 @@ pub async fn handle_edit_event(
|
||||
|
||||
// Edit-specific actions
|
||||
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
|
||||
// --- Special Handling for Tab/Shift+Tab in Role Field ---
|
||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||
if !register_state.in_suggestion_mode && key.code == KeyCode::Tab && key.modifiers == KeyModifiers::NONE {
|
||||
register_state.update_role_suggestions();
|
||||
if !register_state.role_suggestions.is_empty() {
|
||||
register_state.in_suggestion_mode = true;
|
||||
register_state.selected_suggestion_index = Some(0); // Select first suggestion
|
||||
return Ok("Suggestions shown".to_string());
|
||||
} else {
|
||||
return Ok("No suggestions available".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
// --- End Special Handling ---
|
||||
|
||||
return if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
action,
|
||||
@@ -114,6 +130,15 @@ pub async fn handle_edit_event(
|
||||
|
||||
// Character insertion
|
||||
if let KeyCode::Char(_) = key.code {
|
||||
// If in suggestion mode, exit it before inserting char
|
||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||
register_state.in_suggestion_mode = false;
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
}
|
||||
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
|
||||
// --- End Autocomplete Trigger ---
|
||||
|
||||
return if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
@@ -147,5 +172,35 @@ pub async fn handle_edit_event(
|
||||
};
|
||||
}
|
||||
|
||||
// Handle Backspace/Delete for Autocomplete Trigger
|
||||
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
|
||||
// If in suggestion mode, exit it before deleting char
|
||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||
register_state.in_suggestion_mode = false;
|
||||
register_state.show_role_suggestions = false;
|
||||
register_state.selected_suggestion_index = None;
|
||||
}
|
||||
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
|
||||
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
|
||||
|
||||
// Execute the action first
|
||||
let result = if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
action_str,
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count
|
||||
).await
|
||||
} else {
|
||||
// Handle for login/form if needed, assuming auth_e covers RegisterState
|
||||
Ok("Action not applicable here".to_string()) // Placeholder
|
||||
}?;
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ pub async fn handle_navigation_event(
|
||||
}
|
||||
|
||||
pub fn move_up(app_state: &mut AppState, auth_state: &mut AuthState) {
|
||||
if app_state.ui.focus_outside_canvas && app_state.ui.show_login {
|
||||
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register{
|
||||
if app_state.general.selected_item == 0 {
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
let last_field_index = auth_state.fields().len().saturating_sub(1);
|
||||
@@ -106,7 +106,7 @@ pub fn move_up(app_state: &mut AppState, auth_state: &mut AuthState) {
|
||||
}
|
||||
|
||||
pub fn move_down(app_state: &mut AppState) {
|
||||
if app_state.ui.focus_outside_canvas && app_state.ui.show_login {
|
||||
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register {
|
||||
let num_general_elements = 2;
|
||||
if app_state.general.selected_item < num_general_elements - 1 {
|
||||
app_state.general.selected_item += 1;
|
||||
|
||||
@@ -28,14 +28,16 @@ impl AuthClient {
|
||||
&mut self,
|
||||
username: String,
|
||||
email: String,
|
||||
password: Option<String>, // Use Option for optional fields
|
||||
password_confirmation: Option<String>, // Use Option for optional fields
|
||||
password: Option<String>,
|
||||
password_confirmation: Option<String>,
|
||||
role: Option<String>,
|
||||
) -> Result<AuthResponse, Box<dyn std::error::Error>> {
|
||||
let request = tonic::Request::new(RegisterRequest {
|
||||
username,
|
||||
email,
|
||||
password: password.unwrap_or_default(), // Send empty string if None
|
||||
password_confirmation: password_confirmation.unwrap_or_default(), // Send empty string if None
|
||||
password: password.unwrap_or_default(),
|
||||
password_confirmation: password_confirmation.unwrap_or_default(),
|
||||
role: role.unwrap_or_default(),
|
||||
});
|
||||
let response = self.client.register(request).await?.into_inner();
|
||||
Ok(response)
|
||||
|
||||
@@ -13,4 +13,8 @@ pub trait CanvasState {
|
||||
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);
|
||||
|
||||
// --- Autocomplete Support ---
|
||||
fn get_suggestions(&self) -> Option<&[String]>;
|
||||
fn get_selected_suggestion_index(&self) -> Option<usize>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
// src/state/pages/auth.rs
|
||||
use crate::state::canvas_state::CanvasState;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref AVAILABLE_ROLES: Vec<String> = vec![
|
||||
"admin".to_string(),
|
||||
"moderator".to_string(),
|
||||
"accountant".to_string(),
|
||||
"viewer".to_string(),
|
||||
];
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AuthState {
|
||||
@@ -21,10 +31,15 @@ pub struct RegisterState {
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
pub password_confirmation: String,
|
||||
pub role: String,
|
||||
pub error_message: Option<String>,
|
||||
pub current_field: usize,
|
||||
pub current_cursor_pos: usize,
|
||||
pub has_unsaved_changes: bool,
|
||||
pub show_role_suggestions: bool,
|
||||
pub role_suggestions: Vec<String>,
|
||||
pub selected_suggestion_index: Option<usize>,
|
||||
pub in_suggestion_mode: bool,
|
||||
}
|
||||
|
||||
impl AuthState {
|
||||
@@ -51,12 +66,28 @@ impl RegisterState {
|
||||
email: String::new(),
|
||||
password: String::new(),
|
||||
password_confirmation: String::new(),
|
||||
role: String::new(),
|
||||
error_message: None,
|
||||
current_field: 0,
|
||||
current_cursor_pos: 0,
|
||||
has_unsaved_changes: false,
|
||||
show_role_suggestions: false,
|
||||
role_suggestions: Vec::new(),
|
||||
selected_suggestion_index: None,
|
||||
in_suggestion_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates role suggestions based on current input.
|
||||
pub fn update_role_suggestions(&mut self) {
|
||||
let current_input = self.role.to_lowercase();
|
||||
self.role_suggestions = AVAILABLE_ROLES
|
||||
.iter()
|
||||
.filter(|role| role.to_lowercase().contains(¤t_input))
|
||||
.cloned()
|
||||
.collect();
|
||||
self.show_role_suggestions = !self.role_suggestions.is_empty();
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasState for AuthState {
|
||||
@@ -128,6 +159,15 @@ impl CanvasState for AuthState {
|
||||
// Allow the generic handler to signal changes
|
||||
self.has_unsaved_changes = changed;
|
||||
}
|
||||
|
||||
// --- Autocomplete Support (Not Used for AuthState) ---
|
||||
fn get_suggestions(&self) -> Option<&[String]> {
|
||||
None // AuthState doesn't provide suggestions
|
||||
}
|
||||
|
||||
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
||||
None // AuthState doesn't have selected suggestions
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasState for RegisterState {
|
||||
@@ -141,6 +181,7 @@ impl CanvasState for RegisterState {
|
||||
1 => self.email.len(),
|
||||
2 => self.password.len(),
|
||||
3 => self.password_confirmation.len(),
|
||||
4 => self.role.len(),
|
||||
_ => 0,
|
||||
};
|
||||
self.current_cursor_pos.min(len)
|
||||
@@ -156,6 +197,7 @@ impl CanvasState for RegisterState {
|
||||
&self.email,
|
||||
&self.password,
|
||||
&self.password_confirmation,
|
||||
&self.role,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -165,6 +207,7 @@ impl CanvasState for RegisterState {
|
||||
1 => &self.email,
|
||||
2 => &self.password,
|
||||
3 => &self.password_confirmation,
|
||||
4 => &self.role,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
@@ -175,6 +218,7 @@ impl CanvasState for RegisterState {
|
||||
1 => &mut self.email,
|
||||
2 => &mut self.password,
|
||||
3 => &mut self.password_confirmation,
|
||||
4 => &mut self.role,
|
||||
_ => panic!("Invalid current_field index in RegisterState"),
|
||||
}
|
||||
}
|
||||
@@ -185,17 +229,19 @@ impl CanvasState for RegisterState {
|
||||
"Email (Optional)",
|
||||
"Password (Optional)",
|
||||
"Confirm Password",
|
||||
"Role (Oprional)"
|
||||
]
|
||||
}
|
||||
|
||||
fn set_current_field(&mut self, index: usize) {
|
||||
if index < 4 { // RegisterState has 4 fields
|
||||
if index < 5 { // RegisterState has 5 fields
|
||||
self.current_field = index;
|
||||
let len = match self.current_field {
|
||||
0 => self.username.len(),
|
||||
1 => self.email.len(),
|
||||
2 => self.password.len(),
|
||||
3 => self.password_confirmation.len(),
|
||||
4 => self.role.len(),
|
||||
_ => 0,
|
||||
};
|
||||
self.current_cursor_pos = self.current_cursor_pos.min(len);
|
||||
@@ -208,6 +254,7 @@ impl CanvasState for RegisterState {
|
||||
1 => self.email.len(),
|
||||
2 => self.password.len(),
|
||||
3 => self.password_confirmation.len(),
|
||||
4 => self.role.len(),
|
||||
_ => 0,
|
||||
};
|
||||
self.current_cursor_pos = pos.min(len);
|
||||
@@ -216,4 +263,21 @@ impl CanvasState for RegisterState {
|
||||
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
||||
self.has_unsaved_changes = changed;
|
||||
}
|
||||
|
||||
fn get_suggestions(&self) -> Option<&[String]> {
|
||||
// Only show suggestions for the role field (index 4) when requested
|
||||
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
|
||||
Some(&self.role_suggestions)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
||||
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
|
||||
self.selected_suggestion_index
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,4 +133,13 @@ impl CanvasState for FormState {
|
||||
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
||||
self.has_unsaved_changes = changed;
|
||||
}
|
||||
|
||||
// --- Autocomplete Support (Not Used for FormState) ---
|
||||
fn get_suggestions(&self) -> Option<&[String]> {
|
||||
None // FormState doesn't provide suggestions
|
||||
}
|
||||
|
||||
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
||||
None // FormState doesn't have selected suggestions
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,11 @@ pub async fn save(
|
||||
} else {
|
||||
Some(register_state.password_confirmation.clone())
|
||||
};
|
||||
let role = if register_state.role.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(register_state.role.clone())
|
||||
};
|
||||
|
||||
// Basic client-side validation (example)
|
||||
if username.is_empty() {
|
||||
@@ -59,7 +64,7 @@ pub async fn save(
|
||||
app_state.hide_dialog();
|
||||
|
||||
// Call the gRPC register method
|
||||
match auth_client.register(username, email, password, password_confirmation).await {
|
||||
match auth_client.register(username, email, password, password_confirmation, role).await {
|
||||
Ok(response) => {
|
||||
// Clear fields on success? Optional, maybe wait for dialog confirmation.
|
||||
// register_state.username.clear();
|
||||
@@ -117,6 +122,7 @@ pub async fn revert(
|
||||
register_state.email.clear();
|
||||
register_state.password.clear();
|
||||
register_state.password_confirmation.clear();
|
||||
register_state.role.clear();
|
||||
register_state.error_message = None;
|
||||
register_state.set_has_unsaved_changes(false);
|
||||
register_state.current_field = 0; // Reset focus to first field
|
||||
|
||||
@@ -14,6 +14,7 @@ message RegisterRequest {
|
||||
string email = 2;
|
||||
string password = 3;
|
||||
string password_confirmation = 4;
|
||||
string role = 5;
|
||||
}
|
||||
|
||||
message AuthResponse {
|
||||
|
||||
Binary file not shown.
@@ -9,6 +9,8 @@ pub struct RegisterRequest {
|
||||
pub password: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "4")]
|
||||
pub password_confirmation: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "5")]
|
||||
pub role: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct AuthResponse {
|
||||
|
||||
37
server/src/auth/docs/role_added.txt
Normal file
37
server/src/auth/docs/role_added.txt
Normal file
@@ -0,0 +1,37 @@
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser_default_role",
|
||||
"email": "default@example.com",
|
||||
"password": "password",
|
||||
"password_confirmation": "password"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
{
|
||||
"id": "73017288-af41-49d8-b4cb-2ac2109b38a1",
|
||||
"username": "testuser_default_role",
|
||||
"email": "default@example.com",
|
||||
"role": "accountant"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser_admin_role",
|
||||
"email": "admin@example.com",
|
||||
"password": "password",
|
||||
"password_confirmation": "password",
|
||||
"role": "admin"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
{
|
||||
"id": "9437e318-818b-4c34-822d-c2d6601b835e",
|
||||
"username": "testuser_admin_role",
|
||||
"email": "admin@example.com",
|
||||
"role": "admin"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser_invalid_role",
|
||||
"email": "invalid@example.com",
|
||||
"password": "password",
|
||||
"password_confirmation": "password",
|
||||
"role": "invalid_role_name"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
ERROR:
|
||||
Code: InvalidArgument
|
||||
Message: Invalid role specified: 'invalid_role_name'
|
||||
╭─ ~/Doc/pr/multieko2/server main +3 !1
|
||||
╰─
|
||||
@@ -5,6 +5,8 @@ use common::proto::multieko2::auth::{RegisterRequest, AuthResponse};
|
||||
use crate::db::PgPool;
|
||||
use crate::auth::models::AuthError;
|
||||
|
||||
const DEFAULT_ROLE: &str = "accountant";
|
||||
|
||||
pub async fn register(
|
||||
pool: &PgPool,
|
||||
payload: RegisterRequest,
|
||||
@@ -18,20 +20,28 @@ pub async fn register(
|
||||
let password_hash = hash(payload.password, DEFAULT_COST)
|
||||
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
|
||||
|
||||
let role_to_insert = if payload.role.is_empty() { DEFAULT_ROLE } else { &payload.role };
|
||||
|
||||
// Insert user
|
||||
let user = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (username, email, password_hash, role)
|
||||
VALUES ($1, $2, $3, 'accountant')
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, email, role
|
||||
"#,
|
||||
payload.username,
|
||||
payload.email,
|
||||
password_hash
|
||||
password_hash,
|
||||
role_to_insert
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if let Some(db_err) = e.as_database_error() {
|
||||
if db_err.constraint() == Some("valid_roles") {
|
||||
return Status::invalid_argument(format!("Invalid role specified: '{}'", role_to_insert));
|
||||
}
|
||||
}
|
||||
if e.to_string().contains("duplicate key") {
|
||||
Status::already_exists(AuthError::UserExists.to_string())
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user