Compare commits

..

11 Commits

Author SHA1 Message Date
filipriec
8fcd28832d better answer parsing 2025-06-16 11:14:04 +02:00
filipriec
cccf029464 autocomplete is now perfectc 2025-06-16 10:52:28 +02:00
filipriec
512e7fb9e7 suggestions in the dropdown menu now works amazingly well 2025-06-15 23:11:27 +02:00
filipriec
0e69df8282 empty search is now allowed 2025-06-15 18:36:01 +02:00
filipriec
eb5532c200 finally works as i wanted it to 2025-06-15 14:23:19 +02:00
filipriec
49ed1dfe33 trash 2025-06-15 13:52:43 +02:00
filipriec
62d1c3f7f5 suggestion works, but not exactly, needs more stuff 2025-06-15 13:35:45 +02:00
filipriec
b49dce3334 dropdown is being triggered 2025-06-15 12:15:25 +02:00
filipriec
8ace9bc4d1 links are now in the get method of the backend 2025-06-14 18:09:30 +02:00
filipriec
ce490007ed fixing server responses, now push data links fixed 2025-06-14 17:39:59 +02:00
filipriec
eb96c64e26 links to the other tables 2025-06-14 12:47:59 +02:00
14 changed files with 1110 additions and 446 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target /target
.env .env
/tantivy_indexes /tantivy_indexes
server/tantivy_indexes

View File

@@ -70,10 +70,11 @@ prev_field = ["shift+enter"]
exit = ["esc", "ctrl+e"] exit = ["esc", "ctrl+e"]
delete_char_forward = ["delete"] delete_char_forward = ["delete"]
delete_char_backward = ["backspace"] delete_char_backward = ["backspace"]
move_left = ["left"] move_left = [""]
move_right = ["right"] move_right = ["right"]
suggestion_down = ["ctrl+n", "tab"] suggestion_down = ["ctrl+n", "tab"]
suggestion_up = ["ctrl+p", "shift+tab"] suggestion_up = ["ctrl+p", "shift+tab"]
trigger_autocomplete = ["left"]
[keybindings.command] [keybindings.command]
exit_command_mode = ["ctrl+g", "esc"] exit_command_mode = ["ctrl+g", "esc"]

View File

@@ -1,5 +1,6 @@
// src/components/common/autocomplete.rs // src/components/common/autocomplete.rs
use common::proto::multieko2::search::search_response::Hit;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use ratatui::{ use ratatui::{
layout::Rect, layout::Rect,
@@ -7,9 +8,23 @@ use ratatui::{
widgets::{Block, List, ListItem, ListState}, widgets::{Block, List, ListItem, ListState},
Frame, Frame,
}; };
use std::collections::HashMap;
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
/// Renders an opaque dropdown list for autocomplete suggestions. /// Converts a serde_json::Value into a displayable String.
/// Handles String, Number, and Bool variants. Returns an empty string for Null and others.
fn json_value_to_string(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::Bool(b) => b.to_string(),
// Return an empty string for Null, Array, or Object so we can filter them out.
_ => String::new(),
}
}
/// Renders an opaque dropdown list for simple string-based suggestions.
/// This function remains unchanged.
pub fn render_autocomplete_dropdown( pub fn render_autocomplete_dropdown(
f: &mut Frame, f: &mut Frame,
input_rect: Rect, input_rect: Rect,
@@ -21,39 +36,32 @@ pub fn render_autocomplete_dropdown(
if suggestions.is_empty() { if suggestions.is_empty() {
return; return;
} }
// --- Calculate Dropdown Size & Position --- let max_suggestion_width =
let max_suggestion_width = suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16; suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
let horizontal_padding: u16 = 2; let horizontal_padding: u16 = 2;
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10); let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
let dropdown_height = (suggestions.len() as u16).min(5); let dropdown_height = (suggestions.len() as u16).min(5);
let mut dropdown_area = Rect { let mut dropdown_area = Rect {
x: input_rect.x, // Align horizontally with input x: input_rect.x,
y: input_rect.y + 1, // Position directly below input y: input_rect.y + 1,
width: dropdown_width, width: dropdown_width,
height: dropdown_height, height: dropdown_height,
}; };
// --- Clamping Logic (prevent rendering off-screen) ---
// Clamp vertically (if it goes below the frame)
if dropdown_area.bottom() > frame_area.height { if dropdown_area.bottom() > frame_area.height {
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height); // Try rendering above dropdown_area.y = input_rect.y.saturating_sub(dropdown_height);
} }
// Clamp horizontally (if it goes past the right edge)
if dropdown_area.right() > frame_area.width { if dropdown_area.right() > frame_area.width {
dropdown_area.x = frame_area.width.saturating_sub(dropdown_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); 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); dropdown_area.y = dropdown_area.y.max(0);
// --- End Clamping ---
// Render a solid background block first to ensure opacity let background_block =
let background_block = Block::default().style(Style::default().bg(Color::DarkGray)); Block::default().style(Style::default().bg(Color::DarkGray));
f.render_widget(background_block, dropdown_area); f.render_widget(background_block, dropdown_area);
// Create list items, ensuring each has a defined background
let items: Vec<ListItem> = suggestions let items: Vec<ListItem> = suggestions
.iter() .iter()
.enumerate() .enumerate()
@@ -61,30 +69,140 @@ pub fn render_autocomplete_dropdown(
let is_selected = selected_index == Some(i); let is_selected = selected_index == Some(i);
let s_width = s.width() as u16; let s_width = s.width() as u16;
let padding_needed = dropdown_width.saturating_sub(s_width); let padding_needed = dropdown_width.saturating_sub(s_width);
let padded_s = format!("{}{}", s, " ".repeat(padding_needed as usize)); let padded_s =
format!("{}{}", s, " ".repeat(padding_needed as usize));
ListItem::new(padded_s).style(if is_selected { ListItem::new(padded_s).style(if is_selected {
Style::default() Style::default()
.fg(theme.bg) // Text color on highlight .fg(theme.bg)
.bg(theme.highlight) // Highlight background .bg(theme.highlight)
.add_modifier(Modifier::BOLD) .add_modifier(Modifier::BOLD)
} else { } else {
// Style for non-selected items (matching background block) Style::default().fg(theme.fg).bg(Color::DarkGray)
Style::default()
.fg(theme.fg) // Text color on gray
.bg(Color::DarkGray) // Explicit gray background
}) })
}) })
.collect(); .collect();
// Create the list widget (without its own block)
let list = List::new(items); let list = List::new(items);
// State for managing selection highlight (still needed for logic)
let mut profile_list_state = ListState::default(); let mut profile_list_state = ListState::default();
profile_list_state.select(selected_index); profile_list_state.select(selected_index);
// Render the list statefully *over* the background block
f.render_stateful_widget(list, dropdown_area, &mut profile_list_state); f.render_stateful_widget(list, dropdown_area, &mut profile_list_state);
} }
// --- MODIFIED FUNCTION FOR RICH SUGGESTIONS ---
/// Renders an opaque dropdown list for rich `Hit`-based suggestions.
/// Displays the value of the first meaningful column, followed by the Hit ID.
pub fn render_rich_autocomplete_dropdown(
f: &mut Frame,
input_rect: Rect,
frame_area: Rect,
theme: &Theme,
suggestions: &[Hit],
selected_index: Option<usize>,
) {
if suggestions.is_empty() {
return;
}
let display_names: Vec<String> = suggestions
.iter()
.map(|hit| {
// Use serde_json::Value to handle mixed types (string, null, etc.)
if let Ok(content_map) =
serde_json::from_str::<HashMap<String, serde_json::Value>>(
&hit.content_json,
)
{
// Define keys to ignore for a cleaner display
const IGNORED_KEYS: &[&str] = &["id", "deleted", "created_at"];
// Get keys, filter out ignored ones, and sort for consistency
let mut keys: Vec<_> = content_map
.keys()
.filter(|k| !IGNORED_KEYS.contains(&k.as_str()))
.cloned()
.collect();
keys.sort();
// Get only the first non-empty value from the sorted keys
let values: Vec<_> = keys
.iter()
.map(|key| {
content_map
.get(key)
.map(json_value_to_string)
.unwrap_or_default()
})
.filter(|s| !s.is_empty()) // Filter out null/empty values
.take(1) // Changed from take(2) to take(1)
.collect();
let display_part = values.first().cloned().unwrap_or_default(); // Get the first value
if display_part.is_empty() {
format!("ID: {}", hit.id)
} else {
format!("{} | ID: {}", display_part, hit.id) // ID at the end
}
} else {
format!("ID: {} (parse error)", hit.id)
}
})
.collect();
// --- Calculate Dropdown Size & Position ---
let max_suggestion_width =
display_names.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,
y: input_rect.y + 1,
width: dropdown_width,
height: dropdown_height,
};
// --- Clamping Logic ---
if dropdown_area.bottom() > frame_area.height {
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height);
}
if dropdown_area.right() > frame_area.width {
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
}
dropdown_area.x = dropdown_area.x.max(0);
dropdown_area.y = dropdown_area.y.max(0);
// --- Rendering Logic ---
let background_block =
Block::default().style(Style::default().bg(Color::DarkGray));
f.render_widget(background_block, dropdown_area);
let items: Vec<ListItem> = display_names
.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)
.bg(theme.highlight)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.fg).bg(Color::DarkGray)
})
})
.collect();
let list = List::new(items);
let mut list_state = ListState::default();
list_state.select(selected_index);
f.render_stateful_widget(list, dropdown_area, &mut list_state);
}

View File

@@ -1,36 +1,37 @@
// src/components/form/form.rs // src/components/form/form.rs
use crate::components::common::autocomplete; // <--- ADD THIS IMPORT
use crate::components::handlers::canvas::render_canvas;
use crate::config::colors::themes::Theme;
use crate::state::app::highlight::HighlightState;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState; // <--- CHANGE THIS IMPORT
use ratatui::{ use ratatui::{
widgets::{Paragraph, Block, Borders}, layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
layout::{Layout, Constraint, Direction, Rect, Margin, Alignment},
style::Style, style::Style,
widgets::{Block, Borders, Paragraph},
Frame, Frame,
}; };
use crate::config::colors::themes::Theme;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::app::highlight::HighlightState;
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_param: &impl CanvasState, form_state: &FormState, // <--- CHANGE THIS to the concrete type
fields: &[&str], fields: &[&str],
current_field_idx: &usize, current_field_idx: &usize,
inputs: &[&String], inputs: &[&String],
table_name: &str, // This parameter receives the correct table name table_name: &str,
theme: &Theme, theme: &Theme,
is_edit_mode: bool, is_edit_mode: bool,
highlight_state: &HighlightState, highlight_state: &HighlightState,
total_count: u64, total_count: u64,
current_position: u64, current_position: u64,
) { ) {
// Use the dynamic `table_name` parameter for the title instead of a hardcoded string.
let card_title = format!(" {} ", table_name); let card_title = format!(" {} ", table_name);
let adresar_card = Block::default() let adresar_card = Block::default()
.borders(Borders::ALL) .borders(Borders::ALL)
.border_style(Style::default().fg(theme.border)) .border_style(Style::default().fg(theme.border))
.title(card_title) // Use the dynamic title .title(card_title)
.style(Style::default().bg(theme.bg).fg(theme.fg)); .style(Style::default().bg(theme.bg).fg(theme.fg));
f.render_widget(adresar_card, area); f.render_widget(adresar_card, area);
@@ -42,10 +43,7 @@ pub fn render_form(
let main_layout = Layout::default() let main_layout = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([ .constraints([Constraint::Length(1), Constraint::Min(1)])
Constraint::Length(1),
Constraint::Min(1),
])
.split(inner_area); .split(inner_area);
let count_position_text = if total_count == 0 && current_position == 1 { let count_position_text = if total_count == 0 && current_position == 1 {
@@ -54,19 +52,22 @@ pub fn render_form(
format!("Total: {} | New Entry ({})", total_count, current_position) format!("Total: {} | New Entry ({})", total_count, current_position)
} else if total_count == 0 && current_position > 1 { } else if total_count == 0 && current_position > 1 {
format!("Total: 0 | New Entry ({})", current_position) format!("Total: 0 | New Entry ({})", current_position)
} } else {
else { format!(
format!("Total: {} | Position: {}/{}", total_count, current_position, total_count) "Total: {} | Position: {}/{}",
total_count, current_position, total_count
)
}; };
let count_para = Paragraph::new(count_position_text) let count_para = Paragraph::new(count_position_text)
.style(Style::default().fg(theme.fg)) .style(Style::default().fg(theme.fg))
.alignment(Alignment::Left); .alignment(Alignment::Left);
f.render_widget(count_para, main_layout[0]); f.render_widget(count_para, main_layout[0]);
render_canvas( // Get the active field's rect from render_canvas
let active_field_rect = render_canvas(
f, f,
main_layout[1], main_layout[1],
form_state_param, form_state,
fields, fields,
current_field_idx, current_field_idx,
inputs, inputs,
@@ -74,4 +75,40 @@ pub fn render_form(
is_edit_mode, is_edit_mode,
highlight_state, highlight_state,
); );
// --- NEW: RENDER AUTOCOMPLETE ---
if form_state.autocomplete_active {
// Use the Rect of the active field that render_canvas found for us.
if let Some(active_rect) = active_field_rect {
let selected_index = form_state.get_selected_suggestion_index();
// THE DECIDER LOGIC:
// 1. Check for rich suggestions first.
if let Some(rich_suggestions) = form_state.get_rich_suggestions() {
if !rich_suggestions.is_empty() {
autocomplete::render_rich_autocomplete_dropdown(
f,
active_rect,
f.area(), // Use f.area() for clamping, not f.size()
theme,
rich_suggestions,
selected_index,
);
}
}
// 2. Fallback to simple suggestions if rich ones aren't available.
else if let Some(simple_suggestions) = form_state.get_suggestions() {
if !simple_suggestions.is_empty() {
autocomplete::render_autocomplete_dropdown(
f,
active_rect,
f.area(),
theme,
simple_suggestions,
selected_index,
);
}
}
}
}
} }

View File

@@ -1,20 +1,22 @@
// src/modes/canvas/edit.rs // src/modes/canvas/edit.rs
use crate::config::binds::config::Config; use crate::config::binds::config::Config;
use crate::functions::modes::edit::{
add_logic_e, add_table_e, auth_e, form_e,
};
use crate::modes::handlers::event::EventHandler;
use crate::services::grpc_client::GrpcClient; use crate::services::grpc_client::GrpcClient;
use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
use crate::state::pages::{ use crate::state::pages::{
auth::{LoginState, RegisterState}, auth::{LoginState, RegisterState},
canvas_state::CanvasState, canvas_state::CanvasState,
form::FormState,
}; };
use crate::state::pages::form::FormState; // <<< ADD THIS LINE
// AddLogicState is already imported
// AddTableState is already imported
use crate::state::pages::admin::AdminState;
use crate::modes::handlers::event::EventOutcome;
use crate::functions::modes::edit::{add_logic_e, auth_e, form_e, add_table_e};
use crate::state::app::state::AppState;
use anyhow::Result; use anyhow::Result;
use crossterm::event::KeyEvent; // Removed KeyCode, KeyModifiers as they were unused use common::proto::multieko2::search::search_response::Hit;
use tracing::debug; use crossterm::event::{KeyCode, KeyEvent};
use tokio::sync::mpsc;
use tracing::{debug, info};
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditEventOutcome { pub enum EditEventOutcome {
@@ -22,231 +24,302 @@ pub enum EditEventOutcome {
ExitEditMode, ExitEditMode,
} }
/// Helper function to spawn a non-blocking search task for autocomplete.
async fn trigger_form_autocomplete_search(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
sender: mpsc::UnboundedSender<Vec<Hit>>,
) {
if let Some(field_def) = form_state.fields.get(form_state.current_field) {
if field_def.is_link {
if let Some(target_table) = &field_def.link_target_table {
// 1. Update state for immediate UI feedback
form_state.autocomplete_loading = true;
form_state.autocomplete_active = true;
form_state.autocomplete_suggestions.clear();
form_state.selected_suggestion_index = None;
// 2. Clone everything needed for the background task
let query = form_state.get_current_input().to_string();
let table_to_search = target_table.clone();
let mut grpc_client_clone = grpc_client.clone();
info!(
"[Autocomplete] Spawning search in '{}' for query: '{}'",
table_to_search, query
);
// 3. Spawn the non-blocking task
tokio::spawn(async move {
match grpc_client_clone
.search_table(table_to_search, query)
.await
{
Ok(response) => {
// Send results back through the channel
let _ = sender.send(response.hits);
}
Err(e) => {
tracing::error!(
"[Autocomplete] Search failed: {:?}",
e
);
// Send an empty vec on error so the UI can stop loading
let _ = sender.send(vec![]);
}
}
});
}
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_edit_event( pub async fn handle_edit_event(
key: KeyEvent, key: KeyEvent,
config: &Config, config: &Config,
form_state: &mut FormState, // Now FormState is in scope form_state: &mut FormState,
login_state: &mut LoginState, login_state: &mut LoginState,
register_state: &mut RegisterState, register_state: &mut RegisterState,
admin_state: &mut AdminState, admin_state: &mut AdminState,
ideal_cursor_column: &mut usize,
current_position: &mut u64, current_position: &mut u64,
total_count: u64, total_count: u64,
grpc_client: &mut GrpcClient, event_handler: &mut EventHandler,
app_state: &AppState, app_state: &AppState,
) -> Result<EditEventOutcome> { ) -> Result<EditEventOutcome> {
// --- Global command mode check --- // --- AUTOCOMPLETE-SPECIFIC KEY HANDLING ---
if let Some("enter_command_mode") = config.get_action_for_key_in_mode( if app_state.ui.show_form && form_state.autocomplete_active {
&config.keybindings.global, // Assuming command mode can be entered globally if let Some(action) =
key.code, config.get_edit_action_for_key(key.code, key.modifiers)
key.modifiers, {
) { match action {
// This check might be redundant if EventHandler already prevents entering Edit mode "suggestion_down" => {
// when command_mode is true. However, it's a safeguard. if !form_state.autocomplete_suggestions.is_empty() {
let current =
form_state.selected_suggestion_index.unwrap_or(0);
let next = (current + 1)
% form_state.autocomplete_suggestions.len();
form_state.selected_suggestion_index = Some(next);
}
return Ok(EditEventOutcome::Message(String::new()));
}
"suggestion_up" => {
if !form_state.autocomplete_suggestions.is_empty() {
let current =
form_state.selected_suggestion_index.unwrap_or(0);
let prev = if current == 0 {
form_state.autocomplete_suggestions.len() - 1
} else {
current - 1
};
form_state.selected_suggestion_index = Some(prev);
}
return Ok(EditEventOutcome::Message(String::new()));
}
"exit" => {
form_state.deactivate_autocomplete();
return Ok(EditEventOutcome::Message( return Ok(EditEventOutcome::Message(
"Cannot enter command mode from edit mode here.".to_string(), "Autocomplete cancelled".to_string(),
)); ));
} }
"enter_decider" => {
// --- Common actions (save, revert) --- if let Some(selected_idx) =
if let Some(action) = config.get_action_for_key_in_mode( form_state.selected_suggestion_index
&config.keybindings.common, {
key.code, if let Some(selection) = form_state
key.modifiers, .autocomplete_suggestions
).as_deref() { .get(selected_idx)
if matches!(action, "save" | "revert") { .cloned()
let message_string: String = if app_state.ui.show_login { {
auth_e::execute_common_action(action, login_state, grpc_client, current_position, total_count).await? let current_input =
} else if app_state.ui.show_register { form_state.get_current_input_mut();
auth_e::execute_common_action(action, register_state, grpc_client, current_position, total_count).await? *current_input = selection.id.to_string();
} else if app_state.ui.show_add_table { let new_cursor_pos = current_input.len();
// TODO: Implement common actions for AddTable if needed form_state.set_current_cursor_pos(new_cursor_pos);
format!("Action '{}' not implemented for Add Table in edit mode.", action) // FIX: Access ideal_cursor_column through event_handler
} else if app_state.ui.show_add_logic { event_handler.ideal_cursor_column = new_cursor_pos;
// TODO: Implement common actions for AddLogic if needed form_state.deactivate_autocomplete();
format!("Action '{}' not implemented for Add Logic in edit mode.", action) form_state.set_has_unsaved_changes(true);
} else { // Assuming Form view return Ok(EditEventOutcome::Message(
let outcome = form_e::execute_common_action(action, form_state, grpc_client).await?; "Selection made".to_string(),
match outcome { ));
EventOutcome::Ok(msg) | EventOutcome::DataSaved(_, msg) => msg,
_ => format!("Unexpected outcome from common action: {:?}", outcome),
} }
}
form_state.deactivate_autocomplete();
// Fall through to default 'enter' behavior
}
_ => {} // Let other keys fall through to the live search logic
}
}
}
// --- LIVE AUTOCOMPLETE TRIGGER LOGIC ---
let mut trigger_search = false;
if app_state.ui.show_form {
// Manual trigger
if let Some("trigger_autocomplete") =
config.get_edit_action_for_key(key.code, key.modifiers)
{
if !form_state.autocomplete_active {
trigger_search = true;
}
}
// Live search trigger while typing
else if form_state.autocomplete_active {
if let KeyCode::Char(_) | KeyCode::Backspace = key.code {
let action = if let KeyCode::Backspace = key.code {
"delete_char_backward"
} else {
"insert_char"
}; };
return Ok(EditEventOutcome::Message(message_string)); // FIX: Pass &mut event_handler.ideal_cursor_column
form_e::execute_edit_action(
action,
key,
form_state,
&mut event_handler.ideal_cursor_column,
)
.await?;
trigger_search = true;
}
} }
} }
// --- Edit-specific actions --- if trigger_search {
if let Some(action_str) = config.get_edit_action_for_key(key.code, key.modifiers).as_deref() { trigger_form_autocomplete_search(
// --- Handle "enter_decider" (Enter key) --- form_state,
&mut event_handler.grpc_client,
event_handler.autocomplete_result_sender.clone(),
)
.await;
return Ok(EditEventOutcome::Message("Searching...".to_string()));
}
// --- GENERAL EDIT MODE EVENT HANDLING (IF NOT AUTOCOMPLETE) ---
if let Some(action_str) =
config.get_edit_action_for_key(key.code, key.modifiers)
{
// Handle Enter key (next field)
if action_str == "enter_decider" { if action_str == "enter_decider" {
let effective_action = if app_state.ui.show_register // FIX: Pass &mut event_handler.ideal_cursor_column
&& register_state.in_suggestion_mode let msg = form_e::execute_edit_action(
&& register_state.current_field() == 4 { // Role field "next_field",
"select_suggestion" key,
} else if app_state.ui.show_add_logic form_state,
&& admin_state.add_logic_state.in_target_column_suggestion_mode &mut event_handler.ideal_cursor_column,
&& admin_state.add_logic_state.current_field() == 1 { // Target Column field )
"select_suggestion" .await?;
} else {
"next_field" // Default action for Enter
};
let msg = if app_state.ui.show_login {
auth_e::execute_edit_action(effective_action, key, login_state, ideal_cursor_column).await?
} else if app_state.ui.show_add_table {
add_table_e::execute_edit_action(effective_action, key, &mut admin_state.add_table_state, ideal_cursor_column).await?
} else if app_state.ui.show_add_logic {
add_logic_e::execute_edit_action(effective_action, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
} else if app_state.ui.show_register {
auth_e::execute_edit_action(effective_action, key, register_state, ideal_cursor_column).await?
} else { // Form view
form_e::execute_edit_action(effective_action, key, form_state, ideal_cursor_column).await?
};
return Ok(EditEventOutcome::Message(msg)); return Ok(EditEventOutcome::Message(msg));
} }
// --- Handle "exit" (Escape key) --- // Handle exiting edit mode
if action_str == "exit" { if action_str == "exit" {
if app_state.ui.show_register && register_state.in_suggestion_mode {
let msg = auth_e::execute_edit_action("exit_suggestion_mode", key, register_state, ideal_cursor_column).await?;
return Ok(EditEventOutcome::Message(msg));
} else if app_state.ui.show_add_logic && admin_state.add_logic_state.in_target_column_suggestion_mode {
admin_state.add_logic_state.in_target_column_suggestion_mode = false;
admin_state.add_logic_state.show_target_column_suggestions = false;
admin_state.add_logic_state.selected_target_column_suggestion_index = None;
return Ok(EditEventOutcome::Message("Exited column suggestions".to_string()));
} else {
return Ok(EditEventOutcome::ExitEditMode); return Ok(EditEventOutcome::ExitEditMode);
} }
}
// --- Autocomplete for AddLogicState Target Column --- // Handle all other edit actions
if app_state.ui.show_add_logic && admin_state.add_logic_state.current_field() == 1 { // Target Column field
if action_str == "suggestion_down" { // "Tab" is mapped to suggestion_down
if !admin_state.add_logic_state.in_target_column_suggestion_mode {
// Attempt to open suggestions
if let Some(profile_name) = admin_state.add_logic_state.profile_name.clone().into() {
if let Some(table_name) = admin_state.add_logic_state.selected_table_name.clone() {
debug!("Fetching table structure for autocomplete: Profile='{}', Table='{}'", profile_name, table_name);
match grpc_client.get_table_structure(profile_name, table_name).await {
Ok(ts_response) => {
admin_state.add_logic_state.table_columns_for_suggestions =
ts_response.columns.into_iter().map(|c| c.name).collect();
admin_state.add_logic_state.update_target_column_suggestions();
if !admin_state.add_logic_state.target_column_suggestions.is_empty() {
admin_state.add_logic_state.in_target_column_suggestion_mode = true;
// update_target_column_suggestions handles initial selection
return Ok(EditEventOutcome::Message("Column suggestions shown".to_string()));
} else {
return Ok(EditEventOutcome::Message("No column suggestions for current input".to_string()));
}
}
Err(e) => {
debug!("Error fetching table structure: {}", e);
admin_state.add_logic_state.table_columns_for_suggestions.clear(); // Clear old data on error
admin_state.add_logic_state.update_target_column_suggestions();
return Ok(EditEventOutcome::Message(format!("Error fetching columns: {}", e)));
}
}
} else {
return Ok(EditEventOutcome::Message("No table selected for column suggestions".to_string()));
}
} else { // Should not happen if AddLogic is properly initialized
return Ok(EditEventOutcome::Message("Profile name missing for column suggestions".to_string()));
}
} else { // Already in suggestion mode, navigate down
let msg = add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?;
return Ok(EditEventOutcome::Message(msg));
}
} else if admin_state.add_logic_state.in_target_column_suggestion_mode && action_str == "suggestion_up" {
let msg = add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?;
return Ok(EditEventOutcome::Message(msg));
}
}
// --- Autocomplete for RegisterState Role Field ---
if app_state.ui.show_register && register_state.current_field() == 4 { // Role field
if !register_state.in_suggestion_mode && action_str == "suggestion_down" { // Tab
register_state.update_role_suggestions();
if !register_state.role_suggestions.is_empty() {
register_state.in_suggestion_mode = true;
// update_role_suggestions should handle initial selection
return Ok(EditEventOutcome::Message("Role suggestions shown".to_string()));
} else {
// If Tab doesn't open suggestions, it might fall through to "next_field"
// or you might want specific behavior. For now, let it fall through.
}
}
if register_state.in_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up") {
let msg = auth_e::execute_edit_action(action_str, key, register_state, ideal_cursor_column).await?;
return Ok(EditEventOutcome::Message(msg));
}
}
// --- Dispatch other edit actions ---
let msg = if app_state.ui.show_login { let msg = if app_state.ui.show_login {
auth_e::execute_edit_action(action_str, key, login_state, ideal_cursor_column).await? // FIX: Pass &mut event_handler.ideal_cursor_column
auth_e::execute_edit_action(
action_str,
key,
login_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else if app_state.ui.show_add_table { } else if app_state.ui.show_add_table {
add_table_e::execute_edit_action(action_str, key, &mut admin_state.add_table_state, ideal_cursor_column).await? // FIX: Pass &mut event_handler.ideal_cursor_column
add_table_e::execute_edit_action(
action_str,
key,
&mut admin_state.add_table_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else if app_state.ui.show_add_logic { } else if app_state.ui.show_add_logic {
// If not a suggestion action handled above for AddLogic // FIX: Pass &mut event_handler.ideal_cursor_column
if !(admin_state.add_logic_state.in_target_column_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) { add_logic_e::execute_edit_action(
add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await? action_str,
} else { String::new() /* Already handled */ } key,
&mut admin_state.add_logic_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
if !(register_state.in_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) { // FIX: Pass &mut event_handler.ideal_cursor_column
auth_e::execute_edit_action(action_str, key, register_state, ideal_cursor_column).await? auth_e::execute_edit_action(
} else { String::new() /* Already handled */ } action_str,
} else { // Form view key,
form_e::execute_edit_action(action_str, key, form_state, ideal_cursor_column).await? register_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else {
// FIX: Pass &mut event_handler.ideal_cursor_column
form_e::execute_edit_action(
action_str,
key,
form_state,
&mut event_handler.ideal_cursor_column,
)
.await?
}; };
return Ok(EditEventOutcome::Message(msg)); return Ok(EditEventOutcome::Message(msg));
} }
// --- Character insertion --- // --- FALLBACK FOR CHARACTER INSERTION (IF NO OTHER BINDING MATCHED) ---
// If character insertion happens while in suggestion mode, exit suggestion mode first. if let KeyCode::Char(_) = key.code {
let mut exited_suggestion_mode_for_typing = false; let msg = if app_state.ui.show_login {
if app_state.ui.show_register && register_state.in_suggestion_mode { // FIX: Pass &mut event_handler.ideal_cursor_column
register_state.in_suggestion_mode = false; auth_e::execute_edit_action(
register_state.show_role_suggestions = false; "insert_char",
register_state.selected_suggestion_index = None; key,
exited_suggestion_mode_for_typing = true; login_state,
} &mut event_handler.ideal_cursor_column,
if app_state.ui.show_add_logic && admin_state.add_logic_state.in_target_column_suggestion_mode { )
admin_state.add_logic_state.in_target_column_suggestion_mode = false; .await?
admin_state.add_logic_state.show_target_column_suggestions = false;
admin_state.add_logic_state.selected_target_column_suggestion_index = None;
exited_suggestion_mode_for_typing = true;
}
let mut char_insert_msg = if app_state.ui.show_login {
auth_e::execute_edit_action("insert_char", key, login_state, ideal_cursor_column).await?
} else if app_state.ui.show_add_table { } else if app_state.ui.show_add_table {
add_table_e::execute_edit_action("insert_char", key, &mut admin_state.add_table_state, ideal_cursor_column).await? // FIX: Pass &mut event_handler.ideal_cursor_column
add_table_e::execute_edit_action(
"insert_char",
key,
&mut admin_state.add_table_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else if app_state.ui.show_add_logic { } else if app_state.ui.show_add_logic {
add_logic_e::execute_edit_action("insert_char", key, &mut admin_state.add_logic_state, ideal_cursor_column).await? // FIX: Pass &mut event_handler.ideal_cursor_column
add_logic_e::execute_edit_action(
"insert_char",
key,
&mut admin_state.add_logic_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else if app_state.ui.show_register { } else if app_state.ui.show_register {
auth_e::execute_edit_action("insert_char", key, register_state, ideal_cursor_column).await? // FIX: Pass &mut event_handler.ideal_cursor_column
} else { // Form view auth_e::execute_edit_action(
form_e::execute_edit_action("insert_char", key, form_state, ideal_cursor_column).await? "insert_char",
key,
register_state,
&mut event_handler.ideal_cursor_column,
)
.await?
} else {
// FIX: Pass &mut event_handler.ideal_cursor_column
form_e::execute_edit_action(
"insert_char",
key,
form_state,
&mut event_handler.ideal_cursor_column,
)
.await?
}; };
return Ok(EditEventOutcome::Message(msg));
// After character insertion, update suggestions if applicable
if app_state.ui.show_register && register_state.current_field() == 4 {
register_state.update_role_suggestions();
// If we just exited suggestion mode by typing, don't immediately show them again unless Tab is pressed.
// However, update_role_suggestions will set show_role_suggestions if matches are found.
// This is fine, as the render logic checks in_suggestion_mode.
}
if app_state.ui.show_add_logic && admin_state.add_logic_state.current_field() == 1 {
admin_state.add_logic_state.update_target_column_suggestions();
} }
if exited_suggestion_mode_for_typing && char_insert_msg.is_empty() { Ok(EditEventOutcome::Message(String::new())) // No action taken
char_insert_msg = "Suggestions hidden".to_string();
}
Ok(EditEventOutcome::Message(char_insert_msg))
} }

View File

@@ -47,7 +47,7 @@ use crossterm::cursor::SetCursorStyle;
use crossterm::event::{Event, KeyCode, KeyEvent}; use crossterm::event::{Event, KeyCode, KeyEvent};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio::sync::mpsc::unbounded_channel; use tokio::sync::mpsc::unbounded_channel;
use tracing::{info, error}; use tracing::{error, info};
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventOutcome { pub enum EventOutcome {
@@ -85,6 +85,9 @@ pub struct EventHandler {
pub navigation_state: NavigationState, pub navigation_state: NavigationState,
pub search_result_sender: mpsc::UnboundedSender<Vec<Hit>>, pub search_result_sender: mpsc::UnboundedSender<Vec<Hit>>,
pub search_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>, pub search_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>,
// --- ADDED FOR LIVE AUTOCOMPLETE ---
pub autocomplete_result_sender: mpsc::UnboundedSender<Vec<Hit>>,
pub autocomplete_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>,
} }
impl EventHandler { impl EventHandler {
@@ -96,6 +99,7 @@ impl EventHandler {
grpc_client: GrpcClient, grpc_client: GrpcClient,
) -> Result<Self> { ) -> Result<Self> {
let (search_tx, search_rx) = unbounded_channel(); let (search_tx, search_rx) = unbounded_channel();
let (autocomplete_tx, autocomplete_rx) = unbounded_channel(); // ADDED
Ok(EventHandler { Ok(EventHandler {
command_mode: false, command_mode: false,
command_input: String::new(), command_input: String::new(),
@@ -114,6 +118,9 @@ impl EventHandler {
navigation_state: NavigationState::new(), navigation_state: NavigationState::new(),
search_result_sender: search_tx, search_result_sender: search_tx,
search_result_receiver: search_rx, search_result_receiver: search_rx,
// --- ADDED ---
autocomplete_result_sender: autocomplete_tx,
autocomplete_result_receiver: autocomplete_rx,
}) })
} }
@@ -143,19 +150,28 @@ impl EventHandler {
outcome_message = "Search cancelled".to_string(); outcome_message = "Search cancelled".to_string();
} }
KeyCode::Enter => { KeyCode::Enter => {
if let Some(selected_hit) = search_state.results.get(search_state.selected_index) { if let Some(selected_hit) =
if let Ok(data) = serde_json::from_str::<std::collections::HashMap<String, String>>(&selected_hit.content_json) { search_state.results.get(search_state.selected_index)
{
if let Ok(data) = serde_json::from_str::<
std::collections::HashMap<String, String>,
>(&selected_hit.content_json)
{
let detached_pos = form_state.total_count + 2; let detached_pos = form_state.total_count + 2;
form_state.update_from_response(&data, detached_pos); form_state
.update_from_response(&data, detached_pos);
} }
should_close = true; should_close = true;
outcome_message = format!("Loaded record ID {}", selected_hit.id); outcome_message =
format!("Loaded record ID {}", selected_hit.id);
} }
} }
KeyCode::Up => search_state.previous_result(), KeyCode::Up => search_state.previous_result(),
KeyCode::Down => search_state.next_result(), KeyCode::Down => search_state.next_result(),
KeyCode::Char(c) => { KeyCode::Char(c) => {
search_state.input.insert(search_state.cursor_position, c); search_state
.input
.insert(search_state.cursor_position, c);
search_state.cursor_position += 1; search_state.cursor_position += 1;
trigger_search = true; trigger_search = true;
} }
@@ -167,10 +183,12 @@ impl EventHandler {
} }
} }
KeyCode::Left => { KeyCode::Left => {
search_state.cursor_position = search_state.cursor_position.saturating_sub(1); search_state.cursor_position =
search_state.cursor_position.saturating_sub(1);
} }
KeyCode::Right => { KeyCode::Right => {
if search_state.cursor_position < search_state.input.len() { if search_state.cursor_position < search_state.input.len()
{
search_state.cursor_position += 1; search_state.cursor_position += 1;
} }
} }
@@ -188,13 +206,19 @@ impl EventHandler {
let sender = self.search_result_sender.clone(); let sender = self.search_result_sender.clone();
let mut grpc_client = self.grpc_client.clone(); let mut grpc_client = self.grpc_client.clone();
info!("--- 1. Spawning search task for query: '{}' ---", query); info!(
"--- 1. Spawning search task for query: '{}' ---",
query
);
// We now move the grpc_client into the task, just like with login. // We now move the grpc_client into the task, just like with login.
tokio::spawn(async move { tokio::spawn(async move {
info!("--- 2. Background task started. ---"); info!("--- 2. Background task started. ---");
match grpc_client.search_table(table_name, query).await { match grpc_client.search_table(table_name, query).await {
Ok(response) => { Ok(response) => {
info!("--- 3a. gRPC call successful. Found {} hits. ---", response.hits.len()); info!(
"--- 3a. gRPC call successful. Found {} hits. ---",
response.hits.len()
);
let _ = sender.send(response.hits); let _ = sender.send(response.hits);
} }
Err(e) => { Err(e) => {
@@ -237,22 +261,33 @@ impl EventHandler {
if app_state.ui.show_search_palette { if app_state.ui.show_search_palette {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
// The call no longer passes grpc_client // The call no longer passes grpc_client
return self.handle_search_palette_event(key_event, form_state, app_state).await; return self
.handle_search_palette_event(
key_event,
form_state,
app_state,
)
.await;
} }
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
let mut current_mode = ModeManager::derive_mode(app_state, self, admin_state); let mut current_mode =
ModeManager::derive_mode(app_state, self, admin_state);
if current_mode == AppMode::General && self.navigation_state.active { if current_mode == AppMode::General && self.navigation_state.active {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
let outcome = let outcome = handle_command_navigation_event(
handle_command_navigation_event(&mut self.navigation_state, key_event, config) &mut self.navigation_state,
key_event,
config,
)
.await?; .await?;
if !self.navigation_state.active { if !self.navigation_state.active {
self.command_message = outcome.get_message_if_ok(); self.command_message = outcome.get_message_if_ok();
current_mode = ModeManager::derive_mode(app_state, self, admin_state); current_mode =
ModeManager::derive_mode(app_state, self, admin_state);
} }
app_state.update_mode(current_mode); app_state.update_mode(current_mode);
return Ok(outcome); return Ok(outcome);
@@ -265,23 +300,39 @@ impl EventHandler {
let current_view = { let current_view = {
let ui = &app_state.ui; let ui = &app_state.ui;
if ui.show_intro { AppView::Intro } if ui.show_intro {
else if ui.show_login { AppView::Login } AppView::Intro
else if ui.show_register { AppView::Register } } else if ui.show_login {
else if ui.show_admin { AppView::Admin } AppView::Login
else if ui.show_add_logic { AppView::AddLogic } } else if ui.show_register {
else if ui.show_add_table { AppView::AddTable } AppView::Register
else if ui.show_form { AppView::Form } } else if ui.show_admin {
else { AppView::Scratch } AppView::Admin
} else if ui.show_add_logic {
AppView::AddLogic
} else if ui.show_add_table {
AppView::AddTable
} else if ui.show_form {
AppView::Form
} else {
AppView::Scratch
}
}; };
buffer_state.update_history(current_view); buffer_state.update_history(current_view);
if app_state.ui.dialog.dialog_show { if app_state.ui.dialog.dialog_show {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
if let Some(dialog_result) = dialog::handle_dialog_event( if let Some(dialog_result) = dialog::handle_dialog_event(
&Event::Key(key_event), config, app_state, login_state, &Event::Key(key_event),
register_state, buffer_state, admin_state, config,
).await { app_state,
login_state,
register_state,
buffer_state,
admin_state,
)
.await
{
return dialog_result; return dialog_result;
} }
} else if let Event::Resize(_, _) = event { } else if let Event::Resize(_, _) = event {
@@ -293,45 +344,88 @@ impl EventHandler {
let key_code = key_event.code; let key_code = key_event.code;
let modifiers = key_event.modifiers; let modifiers = key_event.modifiers;
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) { if UiStateHandler::toggle_sidebar(
let message = format!("Sidebar {}", if app_state.ui.show_sidebar { "shown" } else { "hidden" }); &mut app_state.ui,
config,
key_code,
modifiers,
) {
let message = format!(
"Sidebar {}",
if app_state.ui.show_sidebar {
"shown"
} else {
"hidden"
}
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
if UiStateHandler::toggle_buffer_list(&mut app_state.ui, config, key_code, modifiers) { if UiStateHandler::toggle_buffer_list(
let message = format!("Buffer {}", if app_state.ui.show_buffer_list { "shown" } else { "hidden" }); &mut app_state.ui,
config,
key_code,
modifiers,
) {
let message = format!(
"Buffer {}",
if app_state.ui.show_buffer_list {
"shown"
} else {
"hidden"
}
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
if !matches!(current_mode, AppMode::Edit | AppMode::Command) { if !matches!(current_mode, AppMode::Edit | AppMode::Command) {
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.global, key_code, modifiers) { if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.global,
key_code,
modifiers,
) {
match action { match action {
"next_buffer" => { "next_buffer" => {
if buffer::switch_buffer(buffer_state, true) { if buffer::switch_buffer(buffer_state, true) {
return Ok(EventOutcome::Ok("Switched to next buffer".to_string())); return Ok(EventOutcome::Ok(
"Switched to next buffer".to_string(),
));
} }
} }
"previous_buffer" => { "previous_buffer" => {
if buffer::switch_buffer(buffer_state, false) { if buffer::switch_buffer(buffer_state, false) {
return Ok(EventOutcome::Ok("Switched to previous buffer".to_string())); return Ok(EventOutcome::Ok(
"Switched to previous buffer".to_string(),
));
} }
} }
"close_buffer" => { "close_buffer" => {
let current_table_name = app_state.current_view_table_name.as_deref(); let current_table_name =
let message = buffer_state.close_buffer_with_intro_fallback(current_table_name); app_state.current_view_table_name.as_deref();
let message = buffer_state
.close_buffer_with_intro_fallback(
current_table_name,
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
_ => {} _ => {}
} }
} }
if let Some(action) = config.get_general_action(key_code, modifiers) { if let Some(action) =
config.get_general_action(key_code, modifiers)
{
if action == "open_search" { if action == "open_search" {
if app_state.ui.show_form { if app_state.ui.show_form {
if let Some(table_name) = app_state.current_view_table_name.clone() { if let Some(table_name) =
app_state.current_view_table_name.clone()
{
app_state.ui.show_search_palette = true; app_state.ui.show_search_palette = true;
app_state.search_state = Some(SearchState::new(table_name)); app_state.search_state =
Some(SearchState::new(table_name));
app_state.ui.focus_outside_canvas = true; app_state.ui.focus_outside_canvas = true;
return Ok(EventOutcome::Ok("Search palette opened".to_string())); return Ok(EventOutcome::Ok(
"Search palette opened".to_string(),
));
} }
} }
} }
@@ -340,9 +434,20 @@ impl EventHandler {
match current_mode { match current_mode {
AppMode::General => { AppMode::General => {
if app_state.ui.show_admin && auth_state.role.as_deref() == Some("admin") { if app_state.ui.show_admin
if admin_nav::handle_admin_navigation(key_event, config, app_state, admin_state, buffer_state, &mut self.command_message) { && auth_state.role.as_deref() == Some("admin")
return Ok(EventOutcome::Ok(self.command_message.clone())); {
if admin_nav::handle_admin_navigation(
key_event,
config,
app_state,
admin_state,
buffer_state,
&mut self.command_message,
) {
return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -350,10 +455,19 @@ impl EventHandler {
let client_clone = self.grpc_client.clone(); let client_clone = self.grpc_client.clone();
let sender_clone = self.save_logic_result_sender.clone(); let sender_clone = self.save_logic_result_sender.clone();
if add_logic_nav::handle_add_logic_navigation( if add_logic_nav::handle_add_logic_navigation(
key_event, config, app_state, &mut admin_state.add_logic_state, key_event,
&mut self.is_edit_mode, buffer_state, client_clone, sender_clone, &mut self.command_message, config,
app_state,
&mut admin_state.add_logic_state,
&mut self.is_edit_mode,
buffer_state,
client_clone,
sender_clone,
&mut self.command_message,
) { ) {
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -361,44 +475,96 @@ impl EventHandler {
let client_clone = self.grpc_client.clone(); let client_clone = self.grpc_client.clone();
let sender_clone = self.save_table_result_sender.clone(); let sender_clone = self.save_table_result_sender.clone();
if add_table_nav::handle_add_table_navigation( if add_table_nav::handle_add_table_navigation(
key_event, config, app_state, &mut admin_state.add_table_state, key_event,
client_clone, sender_clone, &mut self.command_message, config,
app_state,
&mut admin_state.add_table_state,
client_clone,
sender_clone,
&mut self.command_message,
) { ) {
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
let nav_outcome = navigation::handle_navigation_event( let nav_outcome = navigation::handle_navigation_event(
key_event, config, form_state, app_state, login_state, register_state, key_event,
intro_state, admin_state, &mut self.command_mode, &mut self.command_input, config,
&mut self.command_message, &mut self.navigation_state, form_state,
).await; app_state,
login_state,
register_state,
intro_state,
admin_state,
&mut self.command_mode,
&mut self.command_input,
&mut self.command_message,
&mut self.navigation_state,
)
.await;
match nav_outcome { match nav_outcome {
Ok(EventOutcome::ButtonSelected { context, index }) => { Ok(EventOutcome::ButtonSelected { context, index }) => {
let message = match context { let message = match context {
UiContext::Intro => { UiContext::Intro => {
intro::handle_intro_selection(app_state, buffer_state, index); intro::handle_intro_selection(
if app_state.ui.show_admin && !app_state.profile_tree.profiles.is_empty() { app_state,
admin_state.profile_list_state.select(Some(0)); buffer_state,
index,
);
if app_state.ui.show_admin
&& !app_state
.profile_tree
.profiles
.is_empty()
{
admin_state
.profile_list_state
.select(Some(0));
} }
format!("Intro Option {} selected", index) format!("Intro Option {} selected", index)
} }
UiContext::Login => match index { UiContext::Login => match index {
0 => login::initiate_login(login_state, app_state, self.auth_client.clone(), self.login_result_sender.clone()), 0 => login::initiate_login(
1 => login::back_to_main(login_state, app_state, buffer_state).await, login_state,
app_state,
self.auth_client.clone(),
self.login_result_sender.clone(),
),
1 => login::back_to_main(
login_state,
app_state,
buffer_state,
)
.await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}, },
UiContext::Register => match index { UiContext::Register => match index {
0 => register::initiate_registration(register_state, app_state, self.auth_client.clone(), self.register_result_sender.clone()), 0 => register::initiate_registration(
1 => register::back_to_login(register_state, app_state, buffer_state).await, register_state,
app_state,
self.auth_client.clone(),
self.register_result_sender.clone(),
),
1 => register::back_to_login(
register_state,
app_state,
buffer_state,
)
.await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}, },
UiContext::Admin => { UiContext::Admin => {
admin::handle_admin_selection(app_state, admin_state); admin::handle_admin_selection(
app_state,
admin_state,
);
format!("Admin Option {} selected", index) format!("Admin Option {} selected", index)
} }
UiContext::Dialog => "Internal error: Unexpected dialog state".to_string(), UiContext::Dialog => "Internal error: Unexpected dialog state"
.to_string(),
}; };
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
@@ -450,19 +616,31 @@ impl EventHandler {
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
if let Some(action) = config.get_common_action(key_code, modifiers) { if let Some(action) =
config.get_common_action(key_code, modifiers)
{
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit"
| "revert" => {
return common_mode::handle_core_action( return common_mode::handle_core_action(
action, form_state, auth_state, login_state, register_state, action,
&mut self.grpc_client, &mut self.auth_client, terminal, app_state, form_state,
).await; auth_state,
login_state,
register_state,
&mut self.grpc_client,
&mut self.auth_client,
terminal,
app_state,
)
.await;
} }
_ => {} _ => {}
} }
} }
let (_should_exit, message) = read_only::handle_read_only_event( let (_should_exit, message) =
read_only::handle_read_only_event(
app_state, app_state,
key_event, key_event,
config, config,
@@ -496,7 +674,8 @@ impl EventHandler {
return Ok(EventOutcome::Ok("".to_string())); return Ok(EventOutcome::Ok("".to_string()));
} }
let (_should_exit, message) = read_only::handle_read_only_event( let (_should_exit, message) =
read_only::handle_read_only_event(
app_state, app_state,
key_event, key_event,
config, config,
@@ -516,13 +695,24 @@ impl EventHandler {
} }
AppMode::Edit => { AppMode::Edit => {
if let Some(action) = config.get_common_action(key_code, modifiers) { if let Some(action) =
config.get_common_action(key_code, modifiers)
{
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit"
| "revert" => {
return common_mode::handle_core_action( return common_mode::handle_core_action(
action, form_state, auth_state, login_state, register_state, action,
&mut self.grpc_client, &mut self.auth_client, terminal, app_state, // <-- FIX 3 form_state,
).await; auth_state,
login_state,
register_state,
&mut self.grpc_client,
&mut self.auth_client,
terminal,
app_state,
)
.await;
} }
_ => {} _ => {}
} }
@@ -530,11 +720,20 @@ impl EventHandler {
let mut current_position = form_state.current_position; let mut current_position = form_state.current_position;
let total_count = form_state.total_count; let total_count = form_state.total_count;
// --- MODIFIED: Pass `self` instead of `grpc_client` ---
let edit_result = edit::handle_edit_event( let edit_result = edit::handle_edit_event(
key_event, config, form_state, login_state, register_state, admin_state, key_event,
&mut self.ideal_cursor_column, &mut current_position, total_count, config,
&mut self.grpc_client, app_state, // <-- FIX 4 form_state,
).await; login_state,
register_state,
admin_state,
&mut current_position,
total_count,
self,
app_state,
)
.await;
match edit_result { match edit_result {
Ok(edit::EditEventOutcome::ExitEditMode) => { Ok(edit::EditEventOutcome::ExitEditMode) => {
@@ -551,14 +750,22 @@ impl EventHandler {
target_state.set_current_cursor_pos(new_pos); target_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = new_pos; self.ideal_cursor_column = new_pos;
} }
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
Ok(edit::EditEventOutcome::Message(msg)) => { Ok(edit::EditEventOutcome::Message(msg)) => {
if !msg.is_empty() { self.command_message = msg; } if !msg.is_empty() {
self.key_sequence_tracker.reset(); self.command_message = msg;
return Ok(EventOutcome::Ok(self.command_message.clone())); }
self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
}
Err(e) => {
return Err(e.into());
} }
Err(e) => { return Err(e.into()); }
} }
} }
@@ -568,21 +775,38 @@ impl EventHandler {
self.command_message.clear(); self.command_message.clear();
self.command_mode = false; self.command_mode = false;
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok("Exited command mode".to_string())); return Ok(EventOutcome::Ok(
"Exited command mode".to_string(),
));
} }
if config.is_command_execute(key_code, modifiers) { if config.is_command_execute(key_code, modifiers) {
let mut current_position = form_state.current_position; let mut current_position = form_state.current_position;
let total_count = form_state.total_count; let total_count = form_state.total_count;
let outcome = command_mode::handle_command_event( let outcome = command_mode::handle_command_event(
key_event, config, app_state, login_state, register_state, form_state, key_event,
&mut self.command_input, &mut self.command_message, &mut self.grpc_client, // <-- FIX 5 config,
command_handler, terminal, &mut current_position, total_count, app_state,
).await?; login_state,
register_state,
form_state,
&mut self.command_input,
&mut self.command_message,
&mut self.grpc_client, // <-- FIX 5
command_handler,
terminal,
&mut current_position,
total_count,
)
.await?;
form_state.current_position = current_position; form_state.current_position = current_position;
self.command_mode = false; self.command_mode = false;
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
let new_mode = ModeManager::derive_mode(app_state, self, admin_state); let new_mode = ModeManager::derive_mode(
app_state,
self,
admin_state,
);
app_state.update_mode(new_mode); app_state.update_mode(new_mode);
return Ok(outcome); return Ok(outcome);
} }
@@ -596,37 +820,59 @@ impl EventHandler {
if let KeyCode::Char(c) = key_code { if let KeyCode::Char(c) = key_code {
if c == 'f' { if c == 'f' {
self.key_sequence_tracker.add_key(key_code); self.key_sequence_tracker.add_key(key_code);
let sequence = self.key_sequence_tracker.get_sequence(); let sequence =
self.key_sequence_tracker.get_sequence();
if config.matches_key_sequence_generalized(&sequence) == Some("find_file_palette_toggle") { if config.matches_key_sequence_generalized(
if app_state.ui.show_form || app_state.ui.show_intro { &sequence,
let mut all_table_paths: Vec<String> = app_state ) == Some("find_file_palette_toggle")
{
if app_state.ui.show_form
|| app_state.ui.show_intro
{
let mut all_table_paths: Vec<String> =
app_state
.profile_tree .profile_tree
.profiles .profiles
.iter() .iter()
.flat_map(|profile| { .flat_map(|profile| {
profile.tables.iter().map(move |table| { profile.tables.iter().map(
format!("{}/{}", profile.name, table.name) move |table| {
}) format!(
"{}/{}",
profile.name,
table.name
)
},
)
}) })
.collect(); .collect();
all_table_paths.sort(); all_table_paths.sort();
self.navigation_state.activate_find_file(all_table_paths); self.navigation_state
.activate_find_file(all_table_paths);
self.command_mode = false; self.command_mode = false;
self.command_input.clear(); self.command_input.clear();
self.command_message.clear(); self.command_message.clear();
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok("Table selection palette activated".to_string())); return Ok(EventOutcome::Ok(
"Table selection palette activated"
.to_string(),
));
} else { } else {
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
self.command_input.push('f'); self.command_input.push('f');
if sequence.len() > 1 && sequence[0] == KeyCode::Char('f') { if sequence.len() > 1
&& sequence[0] == KeyCode::Char('f')
{
self.command_input.push('f'); self.command_input.push('f');
} }
self.command_message = "Find File not available in this view.".to_string(); self.command_message = "Find File not available in this view."
return Ok(EventOutcome::Ok(self.command_message.clone())); .to_string();
return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -635,7 +881,9 @@ impl EventHandler {
} }
} }
if c != 'f' && !self.key_sequence_tracker.current_sequence.is_empty() { if c != 'f'
&& !self.key_sequence_tracker.current_sequence.is_empty()
{
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
} }

View File

@@ -1,4 +1,6 @@
// src/state/canvas_state.rs // src/state/pages/canvas_state.rs
use common::proto::multieko2::search::search_response::Hit;
pub trait CanvasState { pub trait CanvasState {
fn current_field(&self) -> usize; fn current_field(&self) -> usize;
@@ -16,4 +18,7 @@ pub trait CanvasState {
// --- Autocomplete Support --- // --- Autocomplete Support ---
fn get_suggestions(&self) -> Option<&[String]>; fn get_suggestions(&self) -> Option<&[String]>;
fn get_selected_suggestion_index(&self) -> Option<usize>; fn get_selected_suggestion_index(&self) -> Option<usize>;
fn get_rich_suggestions(&self) -> Option<&[Hit]> {
None
}
} }

View File

@@ -1,30 +1,47 @@
// src/state/pages/form.rs // src/state/pages/form.rs
use std::collections::HashMap;
use crate::config::colors::themes::Theme; use crate::config::colors::themes::Theme;
use ratatui::layout::Rect;
use ratatui::Frame;
use crate::state::app::highlight::HighlightState; use crate::state::app::highlight::HighlightState;
use crate::state::pages::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use common::proto::multieko2::search::search_response::Hit; // Import Hit
use ratatui::layout::Rect;
use ratatui::Frame;
use std::collections::HashMap;
// A struct to bridge the display name (label) to the data key from the server.
#[derive(Debug, Clone)]
pub struct FieldDefinition {
pub display_name: String,
pub data_key: String,
pub is_link: bool,
pub link_target_table: Option<String>,
}
#[derive(Clone)]
pub struct FormState { pub struct FormState {
pub id: i64, pub id: i64,
pub profile_name: String, pub profile_name: String,
pub table_name: String, pub table_name: String,
pub total_count: u64, pub total_count: u64,
pub current_position: u64, pub current_position: u64,
pub fields: Vec<String>, pub fields: Vec<FieldDefinition>,
pub values: Vec<String>, pub values: Vec<String>,
pub current_field: usize, pub current_field: usize,
pub has_unsaved_changes: bool, pub has_unsaved_changes: bool,
pub current_cursor_pos: usize, pub current_cursor_pos: usize,
// --- MODIFIED AUTOCOMPLETE STATE ---
pub autocomplete_active: bool,
pub autocomplete_suggestions: Vec<Hit>, // Changed to use the Hit struct
pub selected_suggestion_index: Option<usize>,
pub autocomplete_loading: bool, // To show a loading indicator
} }
impl FormState { impl FormState {
pub fn new( pub fn new(
profile_name: String, profile_name: String,
table_name: String, table_name: String,
fields: Vec<String>, fields: Vec<FieldDefinition>,
) -> Self { ) -> Self {
let values = vec![String::new(); fields.len()]; let values = vec![String::new(); fields.len()];
FormState { FormState {
@@ -38,10 +55,14 @@ impl FormState {
current_field: 0, current_field: 0,
has_unsaved_changes: false, has_unsaved_changes: false,
current_cursor_pos: 0, current_cursor_pos: 0,
// --- INITIALIZE NEW STATE ---
autocomplete_active: false,
autocomplete_suggestions: Vec::new(),
selected_suggestion_index: None,
autocomplete_loading: false, // Initialize loading state
} }
} }
// This signature is now correct and only deals with form-related state.
pub fn render( pub fn render(
&self, &self,
f: &mut Frame, f: &mut Frame,
@@ -51,13 +72,13 @@ impl FormState {
highlight_state: &HighlightState, highlight_state: &HighlightState,
) { ) {
let fields_str_slice: Vec<&str> = let fields_str_slice: Vec<&str> =
self.fields.iter().map(|s| s.as_str()).collect(); self.fields().iter().map(|s| *s).collect();
let values_str_slice: Vec<&String> = self.values.iter().collect(); let values_str_slice: Vec<&String> = self.values.iter().collect();
crate::components::form::form::render_form( crate::components::form::form::render_form(
f, f,
area, area,
self, self, // <--- This now correctly passes the concrete &FormState
&fields_str_slice, &fields_str_slice,
&self.current_field, &self.current_field,
&values_str_slice, &values_str_slice,
@@ -70,7 +91,6 @@ impl FormState {
); );
} }
// ... other methods are unchanged ...
pub fn reset_to_empty(&mut self) { pub fn reset_to_empty(&mut self) {
self.id = 0; self.id = 0;
self.values.iter_mut().for_each(|v| v.clear()); self.values.iter_mut().for_each(|v| v.clear());
@@ -82,6 +102,7 @@ impl FormState {
} else { } else {
self.current_position = 1; self.current_position = 1;
} }
self.deactivate_autocomplete(); // Deactivate on reset
} }
pub fn get_current_input(&self) -> &str { pub fn get_current_input(&self) -> &str {
@@ -102,13 +123,16 @@ impl FormState {
response_data: &HashMap<String, String>, response_data: &HashMap<String, String>,
new_position: u64, new_position: u64,
) { ) {
self.values = self.fields.iter().map(|field_from_schema| { self.values = self
response_data .fields
.iter() .iter()
.find(|(key_from_data, _)| key_from_data.eq_ignore_ascii_case(field_from_schema)) .map(|field_def| {
.map(|(_, value)| value.clone()) response_data
.get(&field_def.data_key)
.cloned()
.unwrap_or_default() .unwrap_or_default()
}).collect(); })
.collect();
let id_str_opt = response_data let id_str_opt = response_data
.iter() .iter()
@@ -119,7 +143,12 @@ impl FormState {
if let Ok(parsed_id) = id_str.parse::<i64>() { if let Ok(parsed_id) = id_str.parse::<i64>() {
self.id = parsed_id; self.id = parsed_id;
} else { } else {
tracing::error!( "Failed to parse 'id' field '{}' for table {}.{}", id_str, self.profile_name, self.table_name); tracing::error!(
"Failed to parse 'id' field '{}' for table {}.{}",
id_str,
self.profile_name,
self.table_name
);
self.id = 0; self.id = 0;
} }
} else { } else {
@@ -130,6 +159,16 @@ impl FormState {
self.has_unsaved_changes = false; self.has_unsaved_changes = false;
self.current_field = 0; self.current_field = 0;
self.current_cursor_pos = 0; self.current_cursor_pos = 0;
self.deactivate_autocomplete(); // Deactivate on update
}
// --- NEW HELPER METHOD ---
/// Deactivates autocomplete and clears its state.
pub fn deactivate_autocomplete(&mut self) {
self.autocomplete_active = false;
self.autocomplete_suggestions.clear();
self.selected_suggestion_index = None;
self.autocomplete_loading = false;
} }
} }
@@ -159,13 +198,18 @@ impl CanvasState for FormState {
} }
fn fields(&self) -> Vec<&str> { fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect() self.fields
.iter()
.map(|f| f.display_name.as_str())
.collect()
} }
fn set_current_field(&mut self, index: usize) { fn set_current_field(&mut self, index: usize) {
if index < self.fields.len() { if index < self.fields.len() {
self.current_field = index; self.current_field = index;
} }
// Deactivate autocomplete when changing fields
self.deactivate_autocomplete();
} }
fn set_current_cursor_pos(&mut self, pos: usize) { fn set_current_cursor_pos(&mut self, pos: usize) {
@@ -176,11 +220,27 @@ impl CanvasState for FormState {
self.has_unsaved_changes = changed; self.has_unsaved_changes = changed;
} }
// --- MODIFIED: Implement autocomplete trait methods ---
/// Returns None because this state uses rich suggestions.
fn get_suggestions(&self) -> Option<&[String]> { fn get_suggestions(&self) -> Option<&[String]> {
None None
} }
fn get_selected_suggestion_index(&self) -> Option<usize> { /// Returns rich suggestions.
fn get_rich_suggestions(&self) -> Option<&[Hit]> {
if self.autocomplete_active {
Some(&self.autocomplete_suggestions)
} else {
None None
} }
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
if self.autocomplete_active {
self.selected_suggestion_index
} else {
None
}
}
} }

View File

@@ -23,7 +23,7 @@ pub async fn save(
let data_map: HashMap<String, String> = form_state.fields.iter() let data_map: HashMap<String, String> = form_state.fields.iter()
.zip(form_state.values.iter()) .zip(form_state.values.iter())
.map(|(field, value)| (field.clone(), value.clone())) .map(|(field_def, value)| (field_def.data_key.clone(), value.clone()))
.collect(); .collect();
let outcome: SaveOutcome; let outcome: SaveOutcome;

View File

@@ -9,7 +9,7 @@ use crate::modes::common::commands::CommandHandler;
use crate::modes::handlers::event::{EventHandler, EventOutcome}; use crate::modes::handlers::event::{EventHandler, EventOutcome};
use crate::modes::handlers::mode_manager::{AppMode, ModeManager}; use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
use crate::state::pages::canvas_state::CanvasState; use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState; use crate::state::pages::form::{FormState, FieldDefinition}; // Import FieldDefinition
use crate::state::pages::auth::AuthState; use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState; use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState; use crate::state::pages::auth::RegisterState;
@@ -92,12 +92,20 @@ pub async fn run_ui() -> Result<()> {
.await .await
.context("Failed to initialize app state and form")?; .context("Failed to initialize app state and form")?;
let filtered_columns = filter_user_columns(initial_columns_from_service); let initial_field_defs: Vec<FieldDefinition> = filter_user_columns(initial_columns_from_service)
.into_iter()
.map(|col_name| FieldDefinition {
display_name: col_name.clone(),
data_key: col_name,
is_link: false,
link_target_table: None,
})
.collect();
let mut form_state = FormState::new( let mut form_state = FormState::new(
initial_profile.clone(), initial_profile.clone(),
initial_table.clone(), initial_table.clone(),
filtered_columns, initial_field_defs,
); );
UiService::fetch_and_set_table_count(&mut grpc_client, &mut form_state) UiService::fetch_and_set_table_count(&mut grpc_client, &mut form_state)
@@ -132,6 +140,9 @@ pub async fn run_ui() -> Result<()> {
let position_before_event = form_state.current_position; let position_before_event = form_state.current_position;
let mut event_processed = false; let mut event_processed = false;
// --- CHANNEL RECEIVERS ---
// For main search palette
match event_handler.search_result_receiver.try_recv() { match event_handler.search_result_receiver.try_recv() {
Ok(hits) => { Ok(hits) => {
info!("--- 4. Main loop received message from channel. ---"); info!("--- 4. Main loop received message from channel. ---");
@@ -147,6 +158,29 @@ pub async fn run_ui() -> Result<()> {
error!("Search result channel disconnected!"); error!("Search result channel disconnected!");
} }
} }
// --- ADDED: For live form autocomplete ---
match event_handler.autocomplete_result_receiver.try_recv() {
Ok(hits) => {
if form_state.autocomplete_active {
form_state.autocomplete_suggestions = hits;
form_state.autocomplete_loading = false;
if !form_state.autocomplete_suggestions.is_empty() {
form_state.selected_suggestion_index = Some(0);
} else {
form_state.selected_suggestion_index = None;
}
event_handler.command_message = format!("Found {} suggestions.", form_state.autocomplete_suggestions.len());
}
needs_redraw = true;
}
Err(mpsc::error::TryRecvError::Empty) => {}
Err(mpsc::error::TryRecvError::Disconnected) => {
error!("Autocomplete result channel disconnected!");
}
}
if app_state.ui.show_search_palette { if app_state.ui.show_search_palette {
needs_redraw = true; needs_redraw = true;
} }
@@ -333,17 +367,56 @@ pub async fn run_ui() -> Result<()> {
.await .await
{ {
Ok(structure_response) => { Ok(structure_response) => {
let new_columns: Vec<String> = structure_response // --- START OF MODIFIED LOGIC ---
let all_columns: Vec<String> = structure_response
.columns .columns
.iter() .iter()
.map(|c| c.name.clone()) .map(|c| c.name.clone())
.collect(); .collect();
let filtered_columns = filter_user_columns(new_columns); let mut field_definitions: Vec<FieldDefinition> =
filter_user_columns(all_columns)
.into_iter()
.filter(|col_name| !col_name.ends_with("_id"))
.map(|col_name| FieldDefinition {
display_name: col_name.clone(),
data_key: col_name,
is_link: false,
link_target_table: None, // Regular fields have no target
})
.collect();
let linked_tables: Vec<String> = app_state
.profile_tree
.profiles
.iter()
.find(|p| p.name == *prof_name)
.and_then(|profile| {
profile.tables.iter().find(|t| t.name == *tbl_name)
})
.map_or(vec![], |table| table.depends_on.clone());
for linked_table_name in linked_tables {
let base_name = linked_table_name
.split_once('_')
.map_or(linked_table_name.as_str(), |(_, rest)| rest);
let data_key = format!("{}_id", base_name);
let display_name = linked_table_name.clone(); // Clone for use below
field_definitions.push(FieldDefinition {
display_name,
data_key,
is_link: true,
// --- POPULATE THE NEW FIELD ---
link_target_table: Some(linked_table_name),
});
}
// --- END OF MODIFIED LOGIC ---
form_state = FormState::new( form_state = FormState::new(
prof_name.clone(), prof_name.clone(),
tbl_name.clone(), tbl_name.clone(),
filtered_columns, field_definitions, // This now contains the complete definitions
); );
if let Err(e) = UiService::fetch_and_set_table_count( if let Err(e) = UiService::fetch_and_set_table_count(
@@ -381,6 +454,7 @@ pub async fn run_ui() -> Result<()> {
prev_view_table_name = current_view_table; prev_view_table_name = current_view_table;
table_just_switched = true; table_just_switched = true;
} }
Err(e) => { Err(e) => {
app_state.update_dialog_content( app_state.update_dialog_content(
&format!("Error fetching table structure: {}", e), &format!("Error fetching table structure: {}", e),

View File

@@ -25,7 +25,7 @@ pub struct SearcherService {
pub pool: PgPool, pub pool: PgPool,
} }
// Normalize diacritics in queries (no changes here) // normalize_slovak_text function remains unchanged...
fn normalize_slovak_text(text: &str) -> String { fn normalize_slovak_text(text: &str) -> String {
// ... function content is unchanged ... // ... function content is unchanged ...
text.chars() text.chars()
@@ -73,9 +73,48 @@ impl Searcher for SearcherService {
let table_name = req.table_name; let table_name = req.table_name;
let query_str = req.query; let query_str = req.query;
// --- MODIFIED LOGIC ---
// If the query is empty, fetch the 5 most recent records.
if query_str.trim().is_empty() { if query_str.trim().is_empty() {
return Err(Status::invalid_argument("Query cannot be empty")); info!(
"Empty query for table '{}'. Fetching default results.",
table_name
);
let qualified_table = format!("gen.\"{}\"", table_name);
let sql = format!(
"SELECT id, to_jsonb(t) AS data FROM {} t ORDER BY id DESC LIMIT 5",
qualified_table
);
let rows = sqlx::query(&sql)
.fetch_all(&self.pool)
.await
.map_err(|e| {
Status::internal(format!(
"DB query for default results failed: {}",
e
))
})?;
let hits: Vec<Hit> = rows
.into_iter()
.map(|row| {
let id: i64 = row.try_get("id").unwrap_or_default();
let json_data: serde_json::Value =
row.try_get("data").unwrap_or_default();
Hit {
id,
// Score is 0.0 as this is not a relevance-ranked search
score: 0.0,
content_json: json_data.to_string(),
} }
})
.collect();
info!("--- SERVER: Successfully processed empty query. Returning {} default hits. ---", hits.len());
return Ok(Response::new(SearchResponse { hits }));
}
// --- END OF MODIFIED LOGIC ---
let index_path = Path::new("./tantivy_indexes").join(&table_name); let index_path = Path::new("./tantivy_indexes").join(&table_name);
if !index_path.exists() { if !index_path.exists() {
@@ -98,15 +137,6 @@ impl Searcher for SearcherService {
let searcher = reader.searcher(); let searcher = reader.searcher();
let schema = index.schema(); let schema = index.schema();
let prefix_edge_field = schema.get_field("prefix_edge").map_err(|_| {
Status::internal("Schema is missing the 'prefix_edge' field.")
})?;
let prefix_full_field = schema.get_field("prefix_full").map_err(|_| {
Status::internal("Schema is missing the 'prefix_full' field.")
})?;
let text_ngram_field = schema.get_field("text_ngram").map_err(|_| {
Status::internal("Schema is missing the 'text_ngram' field.")
})?;
let pg_id_field = schema.get_field("pg_id").map_err(|_| { let pg_id_field = schema.get_field("pg_id").map_err(|_| {
Status::internal("Schema is missing the 'pg_id' field.") Status::internal("Schema is missing the 'pg_id' field.")
})?; })?;

View File

@@ -1,9 +1,10 @@
// src/tables_data/handlers/get_table_data.rs // src/tables_data/handlers/get_table_data.rs
use tonic::Status; use tonic::Status;
use sqlx::{PgPool, Row}; use sqlx::{PgPool, Row};
use std::collections::HashMap; use std::collections::HashMap;
use common::proto::multieko2::tables_data::{GetTableDataRequest, GetTableDataResponse}; use common::proto::multieko2::tables_data::{GetTableDataRequest, GetTableDataResponse};
use crate::shared::schema_qualifier::qualify_table_name_for_data; // Import schema qualifier use crate::shared::schema_qualifier::qualify_table_name_for_data;
pub async fn get_table_data( pub async fn get_table_data(
db_pool: &PgPool, db_pool: &PgPool,
@@ -48,27 +49,44 @@ pub async fn get_table_data(
return Err(Status::internal("Invalid column format")); return Err(Status::internal("Invalid column format"));
} }
let name = parts[0].trim_matches('"').to_string(); let name = parts[0].trim_matches('"').to_string();
let sql_type = parts[1].to_string(); user_columns.push(name);
user_columns.push((name, sql_type));
} }
// Prepare all columns (system + user-defined) // --- START OF FIX ---
let system_columns = vec![
("id".to_string(), "BIGINT".to_string()),
("deleted".to_string(), "BOOLEAN".to_string()),
];
let all_columns: Vec<(String, String)> = system_columns
.into_iter()
.chain(user_columns.into_iter())
.collect();
// Build SELECT clause with COALESCE and type casting // 1. Get all foreign key columns for this table
let columns_clause = all_columns let fk_columns_query = sqlx::query!(
r#"SELECT ltd.table_name
FROM table_definition_links tdl
JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id
WHERE tdl.source_table_id = $1"#,
table_def.id
)
.fetch_all(db_pool)
.await
.map_err(|e| Status::internal(format!("Foreign key lookup error: {}", e)))?;
// 2. Build the list of foreign key column names
let mut foreign_key_columns = Vec::new();
for fk in fk_columns_query {
let base_name = fk.table_name.split_once('_').map_or(fk.table_name.as_str(), |(_, rest)| rest);
foreign_key_columns.push(format!("{}_id", base_name));
}
// 3. Prepare a complete list of all columns to select
let mut all_column_names = vec!["id".to_string(), "deleted".to_string()];
all_column_names.extend(user_columns);
all_column_names.extend(foreign_key_columns);
// 4. Build the SELECT clause with all columns
let columns_clause = all_column_names
.iter() .iter()
.map(|(name, _)| format!("COALESCE(\"{0}\"::TEXT, '') AS \"{0}\"", name)) .map(|name| format!("COALESCE(\"{0}\"::TEXT, '') AS \"{0}\"", name))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
// --- END OF FIX ---
// Qualify table name with schema // Qualify table name with schema
let qualified_table = qualify_table_name_for_data(&table_name)?; let qualified_table = qualify_table_name_for_data(&table_name)?;
@@ -87,7 +105,6 @@ pub async fn get_table_data(
Ok(row) => row, Ok(row) => row,
Err(sqlx::Error::RowNotFound) => return Err(Status::not_found("Record not found")), Err(sqlx::Error::RowNotFound) => return Err(Status::not_found("Record not found")),
Err(e) => { Err(e) => {
// Handle "relation does not exist" error specifically
if let Some(db_err) = e.as_database_error() { if let Some(db_err) = e.as_database_error() {
if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) { if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) {
return Err(Status::internal(format!( return Err(Status::internal(format!(
@@ -100,9 +117,9 @@ pub async fn get_table_data(
} }
}; };
// Build response data // Build response data from the complete list of columns
let mut data = HashMap::new(); let mut data = HashMap::new();
for (column_name, _) in &all_columns { for column_name in &all_column_names {
let value: String = row let value: String = row
.try_get(column_name.as_str()) .try_get(column_name.as_str())
.map_err(|e| Status::internal(format!("Failed to get column {}: {}", column_name, e)))?; .map_err(|e| Status::internal(format!("Failed to get column {}: {}", column_name, e)))?;

View File

@@ -85,7 +85,7 @@ pub async fn post_table_data(
// Build system columns with foreign keys // Build system columns with foreign keys
let mut system_columns = vec!["deleted".to_string()]; let mut system_columns = vec!["deleted".to_string()];
for fk in fk_columns { for fk in fk_columns {
let base_name = fk.table_name.split('_').last().unwrap_or(&fk.table_name); let base_name = fk.table_name.split_once('_').map_or(fk.table_name.as_str(), |(_, rest)| rest);
system_columns.push(format!("{}_id", base_name)); system_columns.push(format!("{}_id", base_name));
} }