Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8f9372bbd | ||
|
|
6e1997fd9d | ||
|
|
4e7213d1aa | ||
|
|
5afb427bb4 | ||
|
|
685361a11a | ||
|
|
bd7c97ca91 | ||
|
|
81235c67dc | ||
|
|
65e8e03224 | ||
|
|
85eb3adec7 | ||
|
|
5d0f958a68 | ||
|
|
b82f50b76b | ||
|
|
0ab11a9bf9 | ||
|
|
d28c310704 | ||
|
|
2e1d7fdf2b |
1
Cargo.lock
generated
1
Cargo.lock
generated
@@ -409,6 +409,7 @@ dependencies = [
|
||||
"prost",
|
||||
"ratatui",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"time",
|
||||
"tokio",
|
||||
"toml",
|
||||
|
||||
@@ -16,6 +16,7 @@ lazy_static = "1.5.0"
|
||||
prost = "0.13.5"
|
||||
ratatui = { version = "0.29.0", features = ["crossterm"] }
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
time = "0.3.41"
|
||||
tokio = { version = "1.44.2", features = ["full", "macros"] }
|
||||
toml = "0.8.20"
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
enter_command_mode = [":", "ctrl+;"]
|
||||
next_buffer = ["ctrl+l"]
|
||||
previous_buffer = ["ctrl+h"]
|
||||
close_buffer = ["ctrl+k"]
|
||||
|
||||
[keybindings.general]
|
||||
move_up = ["k", "Up"]
|
||||
|
||||
@@ -12,17 +12,17 @@ use ratatui::{
|
||||
Frame,
|
||||
};
|
||||
use crate::components::handlers::canvas::render_canvas;
|
||||
use crate::components::common::dialog;
|
||||
use crate::components::common::{dialog, autocomplete}; // Added autocomplete
|
||||
use crate::config::binds::config::EditorKeybindingMode;
|
||||
use crate::components::common::text_editor::TextEditor;
|
||||
use crate::modes::handlers::mode_manager::AppMode; // For checking AppMode::Edit
|
||||
|
||||
pub fn render_add_logic(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
theme: &Theme,
|
||||
app_state: &AppState,
|
||||
add_logic_state: &mut AddLogicState,
|
||||
is_edit_mode: bool,
|
||||
add_logic_state: &mut AddLogicState, // Changed to &mut
|
||||
is_edit_mode: bool, // This is the general edit mode from EventHandler
|
||||
highlight_state: &HighlightState,
|
||||
) {
|
||||
let main_block = Block::default()
|
||||
@@ -35,27 +35,28 @@ pub fn render_add_logic(
|
||||
let inner_area = main_block.inner(area);
|
||||
f.render_widget(main_block, area);
|
||||
|
||||
if add_logic_state.current_focus == AddLogicFocus::InputScriptContent {
|
||||
// Handle full-screen script editing
|
||||
if add_logic_state.current_focus == AddLogicFocus::InsideScriptContent {
|
||||
let mut editor_ref = add_logic_state.script_content_editor.borrow_mut();
|
||||
let border_style_color = if is_edit_mode { theme.highlight } else { theme.secondary };
|
||||
let border_style = Style::default().fg(border_style_color);
|
||||
|
||||
editor_ref.set_cursor_line_style(Style::default());
|
||||
editor_ref.set_cursor_style(Style::default().add_modifier(Modifier::REVERSED));
|
||||
|
||||
let script_title_hint = match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => {
|
||||
let vim_mode_status = TextEditor::get_vim_mode_status(&add_logic_state.vim_state);
|
||||
if is_edit_mode {
|
||||
format!("Script (VIM {}) - Esc for Normal. Tab navigates from Normal.", vim_mode_status)
|
||||
} else {
|
||||
format!("Script (VIM {}) - 'i'/'a'/'o' for Insert. Tab to navigate.", vim_mode_status)
|
||||
}
|
||||
let vim_mode_status = crate::components::common::text_editor::TextEditor::get_vim_mode_status(&add_logic_state.vim_state);
|
||||
// Vim mode status is relevant regardless of the general `is_edit_mode`
|
||||
format!("Script {}", vim_mode_status)
|
||||
}
|
||||
EditorKeybindingMode::Emacs | EditorKeybindingMode::Default => {
|
||||
if is_edit_mode {
|
||||
"Script (Editing - Esc to exit edit. Tab navigates after exit.)".to_string()
|
||||
// For default/emacs, the general `is_edit_mode` (passed to this function)
|
||||
// indicates if the text area itself is in an "editing" state.
|
||||
if is_edit_mode { // This `is_edit_mode` refers to the text area's active editing.
|
||||
"Script (Editing)".to_string()
|
||||
} else {
|
||||
"Script (Press Enter or Ctrl+E to edit. Tab to navigate.)".to_string()
|
||||
"Script".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -68,19 +69,18 @@ pub fn render_add_logic(
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(border_style),
|
||||
);
|
||||
// Remove .widget() call - just pass the reference directly
|
||||
f.render_widget(&*editor_ref, inner_area);
|
||||
return;
|
||||
}
|
||||
|
||||
// ... rest of the layout code ...
|
||||
// Regular layout with preview
|
||||
let main_chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(9),
|
||||
Constraint::Min(5),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(3), // Top info
|
||||
Constraint::Length(9), // Canvas for 3 inputs (each 1 line + 1 padding = 2 lines * 3 + 2 border = 8, +1 for good measure)
|
||||
Constraint::Min(5), // Script preview
|
||||
Constraint::Length(3), // Buttons
|
||||
])
|
||||
.split(inner_area);
|
||||
|
||||
@@ -89,6 +89,7 @@ pub fn render_add_logic(
|
||||
let script_content_area = main_chunks[2];
|
||||
let buttons_area = main_chunks[3];
|
||||
|
||||
// Top info
|
||||
let profile_text = Paragraph::new(vec![
|
||||
Line::from(Span::styled(
|
||||
format!("Profile: {}", add_logic_state.profile_name),
|
||||
@@ -114,52 +115,89 @@ pub fn render_add_logic(
|
||||
);
|
||||
f.render_widget(profile_text, top_info_area);
|
||||
|
||||
// Canvas
|
||||
let focus_on_canvas_inputs = matches!(
|
||||
add_logic_state.current_focus,
|
||||
AddLogicFocus::InputLogicName
|
||||
| AddLogicFocus::InputTargetColumn
|
||||
| AddLogicFocus::InputDescription
|
||||
);
|
||||
render_canvas(
|
||||
// Call render_canvas and get the active_field_rect
|
||||
let active_field_rect = render_canvas(
|
||||
f,
|
||||
canvas_area,
|
||||
add_logic_state,
|
||||
add_logic_state, // Pass the whole state as it impl CanvasState
|
||||
&add_logic_state.fields(),
|
||||
&add_logic_state.current_field(),
|
||||
&add_logic_state.inputs(),
|
||||
theme,
|
||||
is_edit_mode && focus_on_canvas_inputs,
|
||||
is_edit_mode && focus_on_canvas_inputs, // is_edit_mode for canvas fields
|
||||
highlight_state,
|
||||
);
|
||||
|
||||
// --- Render Autocomplete for Target Column ---
|
||||
// `is_edit_mode` here refers to the general edit mode of the EventHandler
|
||||
if is_edit_mode && add_logic_state.current_field() == 1 { // Target Column field
|
||||
if let Some(suggestions) = add_logic_state.get_suggestions() { // Uses CanvasState impl
|
||||
let selected = add_logic_state.get_selected_suggestion_index();
|
||||
if !suggestions.is_empty() { // Only render if there are suggestions to show
|
||||
if let Some(input_rect) = active_field_rect {
|
||||
autocomplete::render_autocomplete_dropdown(
|
||||
f,
|
||||
input_rect,
|
||||
f.area(), // Full frame area for clamping
|
||||
theme,
|
||||
suggestions,
|
||||
selected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Script content preview
|
||||
{
|
||||
let mut editor_ref = add_logic_state.script_content_editor.borrow_mut();
|
||||
editor_ref.set_cursor_line_style(Style::default());
|
||||
|
||||
let border_style_color = if add_logic_state.current_focus == AddLogicFocus::InputScriptContent {
|
||||
let is_script_preview_focused = add_logic_state.current_focus == AddLogicFocus::ScriptContentPreview;
|
||||
|
||||
if is_script_preview_focused {
|
||||
editor_ref.set_cursor_style(Style::default().add_modifier(Modifier::REVERSED));
|
||||
} else {
|
||||
let underscore_cursor_style = Style::default()
|
||||
.add_modifier(Modifier::UNDERLINED)
|
||||
.fg(theme.secondary);
|
||||
editor_ref.set_cursor_style(underscore_cursor_style);
|
||||
}
|
||||
|
||||
let border_style_color = if is_script_preview_focused {
|
||||
theme.highlight
|
||||
} else {
|
||||
theme.secondary
|
||||
};
|
||||
|
||||
let title_hint = match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => "Script Preview (VIM - Focus with Tab, then 'i'/'a'/'o' to edit)",
|
||||
_ => "Script Preview (Focus with Tab, then Enter/Ctrl+E to edit)",
|
||||
let title_text = "Script Preview"; // Title doesn't need to change based on focus here
|
||||
|
||||
let title_style = if is_script_preview_focused {
|
||||
Style::default().fg(theme.highlight).add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.fg)
|
||||
};
|
||||
|
||||
editor_ref.set_block(
|
||||
Block::default()
|
||||
.title(title_hint)
|
||||
.title(Span::styled(title_text, title_style))
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(Style::default().fg(border_style_color)),
|
||||
);
|
||||
// Remove .widget() call here too
|
||||
f.render_widget(&*editor_ref, script_content_area);
|
||||
}
|
||||
|
||||
let get_button_style = |button_focus: AddLogicFocus, current_focus| {
|
||||
let is_focused = current_focus == button_focus;
|
||||
// Buttons
|
||||
let get_button_style = |button_focus: AddLogicFocus, current_focus_state: AddLogicFocus| {
|
||||
let is_focused = current_focus_state == button_focus;
|
||||
let base_style = Style::default().fg(if is_focused {
|
||||
theme.highlight
|
||||
} else {
|
||||
@@ -172,11 +210,11 @@ pub fn render_add_logic(
|
||||
}
|
||||
};
|
||||
|
||||
let get_button_border_style = |is_focused: bool, theme: &Theme| {
|
||||
let get_button_border_style = |is_focused: bool, current_theme: &Theme| {
|
||||
if is_focused {
|
||||
Style::default().fg(theme.highlight)
|
||||
Style::default().fg(current_theme.highlight)
|
||||
} else {
|
||||
Style::default().fg(theme.secondary)
|
||||
Style::default().fg(current_theme.secondary)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -222,6 +260,7 @@ pub fn render_add_logic(
|
||||
);
|
||||
f.render_widget(cancel_button, button_chunks[1]);
|
||||
|
||||
// Dialog
|
||||
if app_state.ui.dialog.dialog_show {
|
||||
dialog::render_dialog(
|
||||
f,
|
||||
|
||||
@@ -6,12 +6,11 @@ use crate::state::app::state::AppState;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
style::Style,
|
||||
text::{Line, Span, Text}, // Added Text
|
||||
text::{Line, Span, Text},
|
||||
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
|
||||
/// Renders the view specific to admin users with a three-pane layout.
|
||||
pub fn render_admin_panel_admin(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
@@ -19,15 +18,13 @@ pub fn render_admin_panel_admin(
|
||||
admin_state: &mut AdminState,
|
||||
theme: &Theme,
|
||||
) {
|
||||
// Split vertically: Top for panes, Bottom for buttons
|
||||
let main_chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Min(0), Constraint::Length(1)].as_ref()) // 1 line for buttons
|
||||
.constraints([Constraint::Min(0), Constraint::Length(1)].as_ref())
|
||||
.split(area);
|
||||
let panes_area = main_chunks[0];
|
||||
let buttons_area = main_chunks[1];
|
||||
|
||||
// Split the top area into three panes: Profiles | Tables | Dependencies
|
||||
let pane_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
@@ -35,207 +32,148 @@ pub fn render_admin_panel_admin(
|
||||
Constraint::Percentage(40), // Tables
|
||||
Constraint::Percentage(35), // Dependencies
|
||||
].as_ref())
|
||||
.split(panes_area); // Use the whole area directly
|
||||
.split(panes_area);
|
||||
|
||||
let profiles_pane = pane_chunks[0];
|
||||
let tables_pane = pane_chunks[1];
|
||||
let deps_pane = pane_chunks[2];
|
||||
|
||||
// --- Profiles Pane (Left) ---
|
||||
let profile_focus = admin_state.current_focus == AdminFocus::Profiles;
|
||||
let profile_border_style = if profile_focus {
|
||||
let profile_pane_has_focus = matches!(admin_state.current_focus, AdminFocus::ProfilesPane | AdminFocus::InsideProfilesList);
|
||||
let profile_border_style = if profile_pane_has_focus {
|
||||
Style::default().fg(theme.highlight)
|
||||
} else {
|
||||
Style::default().fg(theme.border)
|
||||
};
|
||||
|
||||
// Block for the profiles pane
|
||||
let profiles_block = Block::default()
|
||||
.title(" Profiles ")
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(profile_border_style);
|
||||
let profiles_inner_area = profiles_block.inner(profiles_pane); // Get inner area for list
|
||||
f.render_widget(profiles_block, profiles_pane); // Render the block itself
|
||||
|
||||
// Create profile list items
|
||||
let profile_list_items: Vec<ListItem> = app_state
|
||||
.profile_tree
|
||||
.profiles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, profile)| {
|
||||
// Check persistent selection for prefix, navigation state for style/highlight
|
||||
let is_selected = admin_state.selected_profile_index == Some(idx);
|
||||
let prefix = if is_selected { "[*] " } else { "[ ] " };
|
||||
let style = if is_selected { // Style based on selection too
|
||||
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.fg)
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(prefix, style),
|
||||
Span::styled(&profile.name, style)
|
||||
]))
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Build and render profile list inside the block's inner area
|
||||
let profiles_block = Block::default().title(" Profiles ").borders(Borders::ALL).border_type(BorderType::Rounded).border_style(profile_border_style);
|
||||
let profiles_inner_area = profiles_block.inner(profiles_pane);
|
||||
f.render_widget(profiles_block, profiles_pane);
|
||||
let profile_list_items: Vec<ListItem> = app_state.profile_tree.profiles.iter().enumerate().map(|(idx, profile)| {
|
||||
let is_persistently_selected = admin_state.selected_profile_index == Some(idx);
|
||||
let is_nav_highlighted = admin_state.profile_list_state.selected() == Some(idx) && admin_state.current_focus == AdminFocus::InsideProfilesList;
|
||||
let prefix = if is_persistently_selected { "[*] " } else { "[ ] " };
|
||||
let item_style = if is_nav_highlighted { Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD) }
|
||||
else if is_persistently_selected { Style::default().fg(theme.accent) }
|
||||
else { Style::default().fg(theme.fg) };
|
||||
ListItem::new(Line::from(vec![Span::styled(prefix, item_style), Span::styled(&profile.name, item_style)]))
|
||||
}).collect();
|
||||
let profile_list = List::new(profile_list_items)
|
||||
// Highlight style depends only on Profiles focus
|
||||
.highlight_style(if profile_focus {
|
||||
Style::default().add_modifier(ratatui::style::Modifier::REVERSED)
|
||||
} else {
|
||||
Style::default()
|
||||
})
|
||||
.highlight_symbol(if profile_focus { "> " } else { " " });
|
||||
|
||||
.highlight_style(if admin_state.current_focus == AdminFocus::InsideProfilesList { Style::default().add_modifier(ratatui::style::Modifier::REVERSED) } else { Style::default() })
|
||||
.highlight_symbol(if admin_state.current_focus == AdminFocus::InsideProfilesList { "> " } else { " " });
|
||||
f.render_stateful_widget(profile_list, profiles_inner_area, &mut admin_state.profile_list_state);
|
||||
|
||||
|
||||
// --- Tables Pane (Middle) ---
|
||||
let table_pane_has_focus = matches!(admin_state.current_focus, AdminFocus::Tables | AdminFocus::InsideTablesList);
|
||||
let table_border_style = if table_pane_has_focus {
|
||||
Style::default().fg(theme.highlight)
|
||||
let table_border_style = if table_pane_has_focus { Style::default().fg(theme.highlight) } else { Style::default().fg(theme.border) };
|
||||
|
||||
let profile_to_display_tables_for_idx: Option<usize>;
|
||||
if admin_state.current_focus == AdminFocus::InsideProfilesList {
|
||||
profile_to_display_tables_for_idx = admin_state.profile_list_state.selected();
|
||||
} else {
|
||||
Style::default().fg(theme.border)
|
||||
};
|
||||
profile_to_display_tables_for_idx = admin_state.selected_profile_index
|
||||
.or_else(|| admin_state.profile_list_state.selected());
|
||||
}
|
||||
let tables_pane_title_profile_name = profile_to_display_tables_for_idx
|
||||
.and_then(|idx| app_state.profile_tree.profiles.get(idx))
|
||||
.map_or("None Selected", |p| p.name.as_str());
|
||||
let tables_block = Block::default().title(format!(" Tables (Profile: {}) ", tables_pane_title_profile_name)).borders(Borders::ALL).border_type(BorderType::Rounded).border_style(table_border_style);
|
||||
let tables_inner_area = tables_block.inner(tables_pane);
|
||||
f.render_widget(tables_block, tables_pane);
|
||||
|
||||
// Get selected profile information
|
||||
let navigated_profile_idx = admin_state.profile_list_state.selected(); // Use nav state for display
|
||||
let selected_profile_name = app_state
|
||||
.profile_tree
|
||||
.profiles
|
||||
.get(navigated_profile_idx.unwrap_or(usize::MAX)) // Use nav state for title
|
||||
.map_or("None", |p| &p.name);
|
||||
|
||||
// Block for the tables pane
|
||||
let tables_block = Block::default()
|
||||
.title(format!(" Tables (Profile: {}) ", selected_profile_name))
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(table_border_style);
|
||||
let tables_inner_area = tables_block.inner(tables_pane); // Get inner area for list
|
||||
f.render_widget(tables_block, tables_pane); // Render the block itself
|
||||
|
||||
// Create table list items and get dependencies for the selected table
|
||||
let (table_list_items, selected_table_deps): (Vec<ListItem>, Vec<String>) = if let Some(
|
||||
profile, // Get profile based on NAVIGATED profile index
|
||||
) = navigated_profile_idx.and_then(|idx| app_state.profile_tree.profiles.get(idx)) {
|
||||
let items: Vec<ListItem> = profile
|
||||
.tables
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, table)| { // Renamed i to idx for clarity
|
||||
// Check persistent selection for prefix, navigation state for style/highlight
|
||||
let is_selected = admin_state.selected_table_index == Some(idx); // Use persistent state for [*]
|
||||
let is_navigated = admin_state.table_list_state.selected() == Some(idx); // Use nav state for highlight/>
|
||||
let prefix = if is_selected { "[*] " } else { "[ ] " };
|
||||
let style = if is_navigated { // Style based on navigation highlight
|
||||
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.fg)
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(prefix, style),
|
||||
Span::styled(&table.name, style),
|
||||
]))
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Get dependencies only for the PERSISTENTLY selected table in the PERSISTENTLY selected profile
|
||||
let chosen_profile_idx = admin_state.selected_profile_index; // Use persistent profile selection
|
||||
let deps = chosen_profile_idx // Start with the chosen profile index
|
||||
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx)) // Get the chosen profile
|
||||
.and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx))) // Get the chosen table using its index
|
||||
.map_or(Vec::new(), |t| t.depends_on.clone()); // If found, clone its depends_on, otherwise return empty Vec
|
||||
|
||||
(items, deps)
|
||||
} else {
|
||||
// Default when no profile is selected
|
||||
(vec![ListItem::new("Select a profile to see tables")], vec![])
|
||||
};
|
||||
|
||||
// Build and render table list inside the block's inner area
|
||||
let table_list = List::new(table_list_items)
|
||||
// Highlight style only applies when focus is *inside* the list
|
||||
.highlight_style(if admin_state.current_focus == AdminFocus::InsideTablesList {
|
||||
Style::default().add_modifier(ratatui::style::Modifier::REVERSED)
|
||||
let table_list_items_for_display: Vec<ListItem> =
|
||||
if let Some(profile_data_for_tables) = profile_to_display_tables_for_idx
|
||||
.and_then(|idx| app_state.profile_tree.profiles.get(idx)) {
|
||||
profile_data_for_tables.tables.iter().enumerate().map(|(idx, table)| {
|
||||
let is_table_persistently_selected = admin_state.selected_table_index == Some(idx) &&
|
||||
profile_to_display_tables_for_idx == admin_state.selected_profile_index;
|
||||
let is_table_nav_highlighted = admin_state.table_list_state.selected() == Some(idx) &&
|
||||
admin_state.current_focus == AdminFocus::InsideTablesList;
|
||||
let prefix = if is_table_persistently_selected { "[*] " } else { "[ ] " };
|
||||
let style = if is_table_nav_highlighted { Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD) }
|
||||
else if is_table_persistently_selected { Style::default().fg(theme.accent) }
|
||||
else { Style::default().fg(theme.fg) };
|
||||
ListItem::new(Line::from(vec![Span::styled(prefix, style), Span::styled(&table.name, style)]))
|
||||
}).collect()
|
||||
} else {
|
||||
Style::default()
|
||||
})
|
||||
.highlight_symbol(if admin_state.current_focus == AdminFocus::InsideTablesList { "> " } else { "" });
|
||||
|
||||
vec![ListItem::new("Select a profile to see tables")]
|
||||
};
|
||||
let table_list = List::new(table_list_items_for_display)
|
||||
.highlight_style(if admin_state.current_focus == AdminFocus::InsideTablesList { Style::default().add_modifier(ratatui::style::Modifier::REVERSED) } else { Style::default() })
|
||||
.highlight_symbol(if admin_state.current_focus == AdminFocus::InsideTablesList { "> " } else { " " });
|
||||
f.render_stateful_widget(table_list, tables_inner_area, &mut admin_state.table_list_state);
|
||||
|
||||
// --- Dependencies Pane (Right) ---
|
||||
// Get name based on PERSISTENT selections
|
||||
let chosen_profile_idx = admin_state.selected_profile_index; // Use persistent profile selection
|
||||
let selected_table_name = chosen_profile_idx
|
||||
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx))
|
||||
.and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx))) // Use persistent table selection
|
||||
.map_or("N/A", |t| &t.name); // Get name of the selected table
|
||||
|
||||
// Block for the dependencies pane
|
||||
// --- Dependencies Pane (Right) ---
|
||||
let mut deps_pane_title_table_name = "N/A".to_string();
|
||||
let dependencies_to_display: Vec<String>;
|
||||
|
||||
if admin_state.current_focus == AdminFocus::InsideTablesList {
|
||||
// If navigating tables, show dependencies for the '>' highlighted table.
|
||||
// The profile context is `profile_to_display_tables_for_idx` (from Tables pane logic).
|
||||
if let Some(p_idx_for_current_tables) = profile_to_display_tables_for_idx {
|
||||
if let Some(current_profile_showing_tables) = app_state.profile_tree.profiles.get(p_idx_for_current_tables) {
|
||||
if let Some(table_nav_idx) = admin_state.table_list_state.selected() { // The '>' highlighted table
|
||||
if let Some(navigated_table) = current_profile_showing_tables.tables.get(table_nav_idx) {
|
||||
deps_pane_title_table_name = navigated_table.name.clone();
|
||||
dependencies_to_display = navigated_table.depends_on.clone();
|
||||
} else {
|
||||
dependencies_to_display = Vec::new(); // Navigated table index out of bounds
|
||||
}
|
||||
} else {
|
||||
dependencies_to_display = Vec::new(); // No table navigated with '>'
|
||||
}
|
||||
} else {
|
||||
dependencies_to_display = Vec::new(); // Profile for tables out of bounds
|
||||
}
|
||||
} else {
|
||||
dependencies_to_display = Vec::new(); // No profile active for table display
|
||||
}
|
||||
} else {
|
||||
// Otherwise, show dependencies for the '[*]' persistently selected table & profile.
|
||||
if let Some(p_idx) = admin_state.selected_profile_index { // Must be a persistently selected profile
|
||||
if let Some(selected_profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
if let Some(t_idx) = admin_state.selected_table_index { // Must be a persistently selected table
|
||||
if let Some(selected_table) = selected_profile.tables.get(t_idx) {
|
||||
deps_pane_title_table_name = selected_table.name.clone();
|
||||
dependencies_to_display = selected_table.depends_on.clone();
|
||||
} else { dependencies_to_display = Vec::new(); }
|
||||
} else { dependencies_to_display = Vec::new(); }
|
||||
} else { dependencies_to_display = Vec::new(); }
|
||||
} else { dependencies_to_display = Vec::new(); }
|
||||
}
|
||||
|
||||
let deps_block = Block::default()
|
||||
.title(format!(" Dependencies (Table: {}) ", selected_table_name))
|
||||
.title(format!(" Dependencies (Table: {}) ", deps_pane_title_table_name))
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(Style::default().fg(theme.border)); // No focus highlight for deps pane
|
||||
let deps_inner_area = deps_block.inner(deps_pane); // Get inner area for content
|
||||
f.render_widget(deps_block, deps_pane); // Render the block itself
|
||||
.border_style(Style::default().fg(theme.border));
|
||||
let deps_inner_area = deps_block.inner(deps_pane);
|
||||
f.render_widget(deps_block, deps_pane);
|
||||
|
||||
// Prepare content for the dependencies paragraph
|
||||
let mut deps_content = Text::default();
|
||||
deps_content.lines.push(Line::from(Span::styled(
|
||||
"Depends On:",
|
||||
Style::default().fg(theme.accent), // Use accent color for the label
|
||||
Style::default().fg(theme.accent),
|
||||
)));
|
||||
|
||||
if !selected_table_deps.is_empty() {
|
||||
for dep in selected_table_deps {
|
||||
// List each dependency
|
||||
if !dependencies_to_display.is_empty() {
|
||||
for dep in dependencies_to_display {
|
||||
deps_content.lines.push(Line::from(Span::styled(format!("- {}", dep), theme.fg)));
|
||||
}
|
||||
} else {
|
||||
// Indicate if there are no dependencies
|
||||
deps_content.lines.push(Line::from(Span::styled(" None", theme.secondary)));
|
||||
}
|
||||
|
||||
// Build and render dependencies paragraph inside the block's inner area
|
||||
let deps_paragraph = Paragraph::new(deps_content);
|
||||
f.render_widget(deps_paragraph, deps_inner_area);
|
||||
|
||||
// --- Buttons Row ---
|
||||
let button_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage(33),
|
||||
Constraint::Percentage(34),
|
||||
Constraint::Percentage(33),
|
||||
].as_ref())
|
||||
.split(buttons_area);
|
||||
|
||||
let button_chunks = Layout::default().direction(Direction::Horizontal).constraints([Constraint::Percentage(33), Constraint::Percentage(34), Constraint::Percentage(33)].as_ref()).split(buttons_area);
|
||||
let btn_base_style = Style::default().fg(theme.secondary);
|
||||
|
||||
// Define the helper closure to get style based on focus
|
||||
let get_btn_style = |button_focus: AdminFocus| {
|
||||
if admin_state.current_focus == button_focus {
|
||||
// Apply highlight style if this button is focused
|
||||
btn_base_style.add_modifier(ratatui::style::Modifier::REVERSED)
|
||||
} else {
|
||||
btn_base_style // Use base style otherwise
|
||||
}
|
||||
};
|
||||
let btn1 = Paragraph::new("Add Logic")
|
||||
.style(get_btn_style(AdminFocus::Button1))
|
||||
.alignment(Alignment::Center);
|
||||
let btn2 = Paragraph::new("Add Table")
|
||||
.style(get_btn_style(AdminFocus::Button2))
|
||||
.alignment(Alignment::Center);
|
||||
let btn3 = Paragraph::new("Change Table")
|
||||
.style(get_btn_style(AdminFocus::Button3))
|
||||
.alignment(Alignment::Center);
|
||||
|
||||
let get_btn_style = |button_focus: AdminFocus| { if admin_state.current_focus == button_focus { btn_base_style.add_modifier(ratatui::style::Modifier::REVERSED) } else { btn_base_style } };
|
||||
let btn1 = Paragraph::new("Add Logic").style(get_btn_style(AdminFocus::Button1)).alignment(Alignment::Center);
|
||||
let btn2 = Paragraph::new("Add Table").style(get_btn_style(AdminFocus::Button2)).alignment(Alignment::Center);
|
||||
let btn3 = Paragraph::new("Change Table").style(get_btn_style(AdminFocus::Button3)).alignment(Alignment::Center);
|
||||
f.render_widget(btn1, button_chunks[0]);
|
||||
f.render_widget(btn2, button_chunks[1]);
|
||||
f.render_widget(btn3, button_chunks[2]);
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
pub mod binds;
|
||||
pub mod colors;
|
||||
pub mod storage;
|
||||
|
||||
4
client/src/config/storage.rs
Normal file
4
client/src/config/storage.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
// src/config/storage.rs
|
||||
pub mod storage;
|
||||
|
||||
pub use storage::*;
|
||||
101
client/src/config/storage/storage.rs
Normal file
101
client/src/config/storage/storage.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
// src/config/storage/storage.rs
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use anyhow::{Context, Result};
|
||||
use tracing::{error, info};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
pub const APP_NAME: &str = "multieko2_client";
|
||||
pub const TOKEN_FILE_NAME: &str = "auth.token";
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct StoredAuthData {
|
||||
pub access_token: String,
|
||||
pub user_id: String,
|
||||
pub role: String,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
pub fn get_token_storage_path() -> Result<PathBuf> {
|
||||
let state_dir = dirs::state_dir()
|
||||
.or_else(|| dirs::home_dir().map(|home| home.join(".local").join("state")))
|
||||
.ok_or_else(|| anyhow::anyhow!("Could not determine state directory"))?;
|
||||
|
||||
let app_state_dir = state_dir.join(APP_NAME);
|
||||
fs::create_dir_all(&app_state_dir)
|
||||
.with_context(|| format!("Failed to create app state directory at {:?}", app_state_dir))?;
|
||||
|
||||
Ok(app_state_dir.join(TOKEN_FILE_NAME))
|
||||
}
|
||||
|
||||
pub fn save_auth_data(data: &StoredAuthData) -> Result<()> {
|
||||
let path = get_token_storage_path()?;
|
||||
|
||||
let json_data = serde_json::to_string(data)
|
||||
.context("Failed to serialize auth data")?;
|
||||
|
||||
let mut file = File::create(&path)
|
||||
.with_context(|| format!("Failed to create token file at {:?}", path))?;
|
||||
|
||||
file.write_all(json_data.as_bytes())
|
||||
.context("Failed to write token data to file")?;
|
||||
|
||||
// Set file permissions to 600 (owner read/write only) on Unix
|
||||
#[cfg(unix)]
|
||||
{
|
||||
file.set_permissions(std::fs::Permissions::from_mode(0o600))
|
||||
.context("Failed to set token file permissions")?;
|
||||
}
|
||||
|
||||
info!("Auth data saved to {:?}", path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_auth_data() -> Result<Option<StoredAuthData>> {
|
||||
let path = get_token_storage_path()?;
|
||||
|
||||
if !path.exists() {
|
||||
info!("Token file not found at {:?}", path);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let json_data = fs::read_to_string(&path)
|
||||
.with_context(|| format!("Failed to read token file at {:?}", path))?;
|
||||
|
||||
if json_data.trim().is_empty() {
|
||||
info!("Token file is empty at {:?}", path);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
match serde_json::from_str::<StoredAuthData>(&json_data) {
|
||||
Ok(data) => {
|
||||
info!("Auth data loaded from {:?}", path);
|
||||
Ok(Some(data))
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to deserialize token data from {:?}: {}. Deleting corrupt file.", path, e);
|
||||
if let Err(del_e) = fs::remove_file(&path) {
|
||||
error!("Failed to delete corrupt token file: {}", del_e);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_auth_data() -> Result<()> {
|
||||
let path = get_token_storage_path()?;
|
||||
|
||||
if path.exists() {
|
||||
fs::remove_file(&path)
|
||||
.with_context(|| format!("Failed to delete token file at {:?}", path))?;
|
||||
info!("Token file deleted from {:?}", path);
|
||||
} else {
|
||||
info!("Token file not found for deletion at {:?}", path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,277 +1,135 @@
|
||||
// src/functions/modes/edit/add_logic_e.rs
|
||||
use crate::state::pages::add_logic::AddLogicState; // Changed
|
||||
use crate::state::pages::add_logic::AddLogicState;
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use anyhow::Result;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
|
||||
// Word navigation helpers (get_char_type, find_next_word_start, etc.)
|
||||
// can be kept as they are generic.
|
||||
#[derive(PartialEq)]
|
||||
enum CharType {
|
||||
Whitespace,
|
||||
Alphanumeric,
|
||||
Punctuation,
|
||||
}
|
||||
|
||||
fn get_char_type(c: char) -> CharType {
|
||||
if c.is_whitespace() { CharType::Whitespace }
|
||||
else if c.is_alphanumeric() { CharType::Alphanumeric }
|
||||
else { CharType::Punctuation }
|
||||
}
|
||||
|
||||
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len();
|
||||
if len == 0 || current_pos >= len { return len; }
|
||||
let mut pos = current_pos;
|
||||
let initial_type = get_char_type(chars[pos]);
|
||||
while pos < len && get_char_type(chars[pos]) == initial_type { pos += 1; }
|
||||
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace { pos += 1; }
|
||||
pos
|
||||
}
|
||||
|
||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len();
|
||||
if len == 0 { return 0; }
|
||||
let mut pos = current_pos.min(len - 1);
|
||||
if get_char_type(chars[pos]) == CharType::Whitespace {
|
||||
pos = find_next_word_start(text, pos);
|
||||
}
|
||||
if pos >= len { return len.saturating_sub(1); }
|
||||
let word_type = get_char_type(chars[pos]);
|
||||
while pos < len && get_char_type(chars[pos]) == word_type { pos += 1; }
|
||||
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||
}
|
||||
|
||||
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
if chars.is_empty() || current_pos == 0 { return 0; }
|
||||
let mut pos = current_pos.saturating_sub(1);
|
||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace { pos -= 1; }
|
||||
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace { return 0; }
|
||||
let word_type = get_char_type(chars[pos]);
|
||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type { pos -= 1; }
|
||||
pos
|
||||
}
|
||||
|
||||
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let len = chars.len();
|
||||
if len == 0 || current_pos == 0 { return 0; }
|
||||
let mut pos = current_pos.saturating_sub(1);
|
||||
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace { pos -= 1; }
|
||||
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace { return 0; }
|
||||
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace { return 0; }
|
||||
let word_type = get_char_type(chars[pos]);
|
||||
while pos > 0 && get_char_type(chars[pos - 1]) == word_type { pos -= 1; }
|
||||
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace { pos -= 1; }
|
||||
if pos > 0 { pos - 1 } else { 0 }
|
||||
}
|
||||
|
||||
/// Executes edit actions for the AddLogic view canvas.
|
||||
pub async fn execute_edit_action(
|
||||
action: &str,
|
||||
key: KeyEvent,
|
||||
state: &mut AddLogicState, // Changed
|
||||
key: KeyEvent, // Keep key for insert_char
|
||||
state: &mut AddLogicState,
|
||||
ideal_cursor_column: &mut usize,
|
||||
) -> Result<String> {
|
||||
let mut message = String::new();
|
||||
|
||||
match action {
|
||||
"insert_char" => {
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
let cursor_pos = state.current_cursor_pos();
|
||||
let field_value = state.get_current_input_mut();
|
||||
let mut chars: Vec<char> = field_value.chars().collect();
|
||||
if cursor_pos <= chars.len() {
|
||||
chars.insert(cursor_pos, c);
|
||||
*field_value = chars.into_iter().collect();
|
||||
state.set_current_cursor_pos(cursor_pos + 1);
|
||||
state.set_has_unsaved_changes(true);
|
||||
*ideal_cursor_column = state.current_cursor_pos();
|
||||
}
|
||||
} else {
|
||||
return Ok("Error: insert_char called without a char key.".to_string());
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"delete_char_backward" => {
|
||||
if state.current_cursor_pos() > 0 {
|
||||
let cursor_pos = state.current_cursor_pos();
|
||||
let field_value = state.get_current_input_mut();
|
||||
let mut chars: Vec<char> = field_value.chars().collect();
|
||||
if cursor_pos <= chars.len() {
|
||||
chars.remove(cursor_pos - 1);
|
||||
*field_value = chars.into_iter().collect();
|
||||
let new_pos = cursor_pos - 1;
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
state.set_has_unsaved_changes(true);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"delete_char_forward" => {
|
||||
let cursor_pos = state.current_cursor_pos();
|
||||
let field_value = state.get_current_input_mut();
|
||||
let mut chars: Vec<char> = field_value.chars().collect();
|
||||
if cursor_pos < chars.len() {
|
||||
chars.remove(cursor_pos);
|
||||
*field_value = chars.into_iter().collect();
|
||||
state.set_has_unsaved_changes(true);
|
||||
*ideal_cursor_column = cursor_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"next_field" => {
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
if num_fields > 0 {
|
||||
let current_field = state.current_field();
|
||||
let last_field_index = num_fields - 1;
|
||||
if current_field < last_field_index { // Prevent cycling
|
||||
state.set_current_field(current_field + 1);
|
||||
}
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
}
|
||||
Ok("".to_string())
|
||||
let current_field = state.current_field();
|
||||
let next_field = (current_field + 1) % AddLogicState::INPUT_FIELD_COUNT;
|
||||
state.set_current_field(next_field);
|
||||
*ideal_cursor_column = state.current_cursor_pos();
|
||||
message = format!("Focus on field {}", state.fields()[next_field]);
|
||||
}
|
||||
"prev_field" => {
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
if num_fields > 0 {
|
||||
let current_field = state.current_field();
|
||||
if current_field > 0 { // Prevent cycling
|
||||
state.set_current_field(current_field - 1);
|
||||
}
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
let current_field = state.current_field();
|
||||
let prev_field = if current_field == 0 {
|
||||
AddLogicState::INPUT_FIELD_COUNT - 1
|
||||
} else {
|
||||
current_field - 1
|
||||
};
|
||||
state.set_current_field(prev_field);
|
||||
*ideal_cursor_column = state.current_cursor_pos();
|
||||
message = format!("Focus on field {}", state.fields()[prev_field]);
|
||||
}
|
||||
"delete_char_forward" => {
|
||||
let current_pos = state.current_cursor_pos();
|
||||
let current_input_mut = state.get_current_input_mut();
|
||||
if current_pos < current_input_mut.len() {
|
||||
current_input_mut.remove(current_pos);
|
||||
state.set_has_unsaved_changes(true);
|
||||
if state.current_field() == 1 { state.update_target_column_suggestions(); }
|
||||
}
|
||||
}
|
||||
"delete_char_backward" => {
|
||||
let current_pos = state.current_cursor_pos();
|
||||
if current_pos > 0 {
|
||||
let new_pos = current_pos - 1;
|
||||
state.get_current_input_mut().remove(new_pos);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
state.set_has_unsaved_changes(true);
|
||||
if state.current_field() == 1 { state.update_target_column_suggestions(); }
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_left" => {
|
||||
let new_pos = state.current_cursor_pos().saturating_sub(1);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
let current_pos = state.current_cursor_pos();
|
||||
if current_pos > 0 {
|
||||
let new_pos = current_pos - 1;
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
}
|
||||
"move_right" => {
|
||||
let current_input = state.get_current_input();
|
||||
let current_pos = state.current_cursor_pos();
|
||||
if current_pos < current_input.len() {
|
||||
let input_len = state.get_current_input().len();
|
||||
if current_pos < input_len {
|
||||
let new_pos = current_pos + 1;
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_up" => { // In edit mode, up/down usually means prev/next field
|
||||
let current_field = state.current_field();
|
||||
if current_field > 0 {
|
||||
let new_field = current_field - 1;
|
||||
state.set_current_field(new_field);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_down" => { // In edit mode, up/down usually means prev/next field
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
if num_fields > 0 {
|
||||
let current_field = state.current_field();
|
||||
let last_field_index = num_fields - 1;
|
||||
if current_field < last_field_index {
|
||||
let new_field = current_field + 1;
|
||||
state.set_current_field(new_field);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
"insert_char" => {
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
let current_pos = state.current_cursor_pos();
|
||||
state.get_current_input_mut().insert(current_pos, c);
|
||||
let new_pos = current_pos + 1;
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
state.set_has_unsaved_changes(true);
|
||||
if state.current_field() == 1 {
|
||||
state.update_target_column_suggestions();
|
||||
}
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_line_start" => {
|
||||
state.set_current_cursor_pos(0);
|
||||
*ideal_cursor_column = 0;
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_line_end" => {
|
||||
let current_input = state.get_current_input();
|
||||
let new_pos = current_input.len();
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_first_line" => {
|
||||
if AddLogicState::INPUT_FIELD_COUNT > 0 { // Changed
|
||||
state.set_current_field(0);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
"suggestion_down" => {
|
||||
if state.in_target_column_suggestion_mode && !state.target_column_suggestions.is_empty() {
|
||||
let current_selection = state.selected_target_column_suggestion_index.unwrap_or(0);
|
||||
let next_selection = (current_selection + 1) % state.target_column_suggestions.len();
|
||||
state.selected_target_column_suggestion_index = Some(next_selection);
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_last_line" => {
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
if num_fields > 0 {
|
||||
let new_field = num_fields - 1;
|
||||
state.set_current_field(new_field);
|
||||
let current_input = state.get_current_input();
|
||||
let max_pos = current_input.len();
|
||||
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_word_next" => {
|
||||
let current_input = state.get_current_input();
|
||||
if !current_input.is_empty() {
|
||||
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
|
||||
let final_pos = new_pos.min(current_input.len());
|
||||
state.set_current_cursor_pos(final_pos);
|
||||
*ideal_cursor_column = final_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_word_end" => {
|
||||
let current_input = state.get_current_input();
|
||||
if !current_input.is_empty() {
|
||||
let current_pos = state.current_cursor_pos();
|
||||
let new_pos = find_word_end(current_input, current_pos);
|
||||
let final_pos = if new_pos == current_pos && current_pos < current_input.len() { // Ensure not to go past end
|
||||
find_word_end(current_input, current_pos + 1)
|
||||
"suggestion_up" => {
|
||||
if state.in_target_column_suggestion_mode && !state.target_column_suggestions.is_empty() {
|
||||
let current_selection = state.selected_target_column_suggestion_index.unwrap_or(0);
|
||||
let prev_selection = if current_selection == 0 {
|
||||
state.target_column_suggestions.len() - 1
|
||||
} else {
|
||||
new_pos
|
||||
current_selection - 1
|
||||
};
|
||||
let max_valid_index = current_input.len(); // Allow cursor at end
|
||||
let clamped_pos = final_pos.min(max_valid_index);
|
||||
state.set_current_cursor_pos(clamped_pos);
|
||||
*ideal_cursor_column = clamped_pos;
|
||||
state.selected_target_column_suggestion_index = Some(prev_selection);
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_word_prev" => {
|
||||
let current_input = state.get_current_input();
|
||||
if !current_input.is_empty() {
|
||||
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"move_word_end_prev" => {
|
||||
let current_input = state.get_current_input();
|
||||
if !current_input.is_empty() {
|
||||
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
}
|
||||
"exit_edit_mode" | "save" | "revert" => {
|
||||
Ok("Action handled by main loop".to_string())
|
||||
}
|
||||
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
|
||||
}
|
||||
}
|
||||
"select_suggestion" => {
|
||||
if state.in_target_column_suggestion_mode {
|
||||
let mut selected_suggestion_text: Option<String> = None;
|
||||
|
||||
if let Some(selected_idx) = state.selected_target_column_suggestion_index {
|
||||
if let Some(suggestion) = state.target_column_suggestions.get(selected_idx) {
|
||||
selected_suggestion_text = Some(suggestion.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(suggestion_text) = selected_suggestion_text {
|
||||
state.target_column_input = suggestion_text.clone();
|
||||
state.target_column_cursor_pos = state.target_column_input.len();
|
||||
*ideal_cursor_column = state.target_column_cursor_pos;
|
||||
state.set_has_unsaved_changes(true);
|
||||
message = format!("Selected column: '{}'", suggestion_text);
|
||||
}
|
||||
|
||||
state.in_target_column_suggestion_mode = false;
|
||||
state.show_target_column_suggestions = false;
|
||||
state.selected_target_column_suggestion_index = None;
|
||||
state.update_target_column_suggestions();
|
||||
} else {
|
||||
let current_field = state.current_field();
|
||||
let next_field = (current_field + 1) % AddLogicState::INPUT_FIELD_COUNT;
|
||||
state.set_current_field(next_field);
|
||||
*ideal_cursor_column = state.current_cursor_pos();
|
||||
message = format!("Focus on field {}", state.fields()[next_field]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
@@ -10,9 +10,7 @@ use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
|
||||
use crate::services::GrpcClient;
|
||||
use tokio::sync::mpsc;
|
||||
use anyhow::Result;
|
||||
use common::proto::multieko2::table_script::PostTableScriptRequest;
|
||||
use crate::components::common::text_editor::TextEditor;
|
||||
use tui_textarea::Input as TextAreaInput;
|
||||
|
||||
pub type SaveLogicResultSender = mpsc::Sender<Result<String>>;
|
||||
|
||||
@@ -27,236 +25,214 @@ pub fn handle_add_logic_navigation(
|
||||
save_logic_sender: SaveLogicResultSender,
|
||||
command_message: &mut String,
|
||||
) -> bool {
|
||||
let mut handled = false;
|
||||
let general_action = config.get_general_action(key_event.code, key_event.modifiers);
|
||||
|
||||
if add_logic_state.current_focus == AddLogicFocus::InputScriptContent {
|
||||
// === FULLSCREEN SCRIPT EDITING - COMPLETE ISOLATION ===
|
||||
if add_logic_state.current_focus == AddLogicFocus::InsideScriptContent {
|
||||
let mut editor_borrow = add_logic_state.script_content_editor.borrow_mut();
|
||||
|
||||
match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => {
|
||||
if *is_edit_mode { // App considers textarea to be in "typing" (Insert) mode
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
if changed { add_logic_state.has_unsaved_changes = true; }
|
||||
|
||||
// Check if we've transitioned to Normal mode
|
||||
if key_event.code == KeyCode::Esc && TextEditor::is_vim_normal_mode(&add_logic_state.vim_state) {
|
||||
*is_edit_mode = false;
|
||||
*command_message = "VIM: Normal Mode. Tab to navigate.".to_string();
|
||||
}
|
||||
handled = true;
|
||||
} else { // App considers textarea to be in "navigation" (Normal) mode
|
||||
match key_event.code {
|
||||
// Keys to enter Vim Insert mode
|
||||
KeyCode::Char('i') | KeyCode::Char('a') | KeyCode::Char('o') |
|
||||
KeyCode::Char('I') | KeyCode::Char('A') | KeyCode::Char('O') => {
|
||||
*is_edit_mode = true;
|
||||
TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state
|
||||
);
|
||||
*command_message = "VIM: Insert Mode.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => {
|
||||
if general_action.is_none() {
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
if changed { add_logic_state.has_unsaved_changes = true; }
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EditorKeybindingMode::Emacs | EditorKeybindingMode::Default => {
|
||||
if *is_edit_mode {
|
||||
if key_event.code == KeyCode::Esc && key_event.modifiers == KeyModifiers::NONE {
|
||||
*is_edit_mode = false;
|
||||
*command_message = "Exited script edit. Tab to navigate.".to_string();
|
||||
handled = true;
|
||||
} else if general_action.is_some() && (general_action.unwrap() == "next_field" || general_action.unwrap() == "prev_field") {
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state
|
||||
// Handle ONLY Escape to exit fullscreen mode
|
||||
if key_event.code == KeyCode::Esc && key_event.modifiers == KeyModifiers::NONE {
|
||||
match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => {
|
||||
if *is_edit_mode {
|
||||
// First escape: try to go to Vim Normal mode
|
||||
TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
if changed { add_logic_state.has_unsaved_changes = true; }
|
||||
handled = true;
|
||||
if TextEditor::is_vim_normal_mode(&add_logic_state.vim_state) {
|
||||
*is_edit_mode = false;
|
||||
*command_message = "VIM: Normal Mode. Esc again to exit script.".to_string();
|
||||
}
|
||||
} else {
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state
|
||||
);
|
||||
if changed { add_logic_state.has_unsaved_changes = true; }
|
||||
handled = true;
|
||||
// Second escape: exit fullscreen
|
||||
add_logic_state.current_focus = AddLogicFocus::ScriptContentPreview;
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
*is_edit_mode = false;
|
||||
*command_message = "Exited script editing.".to_string();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if *is_edit_mode {
|
||||
*is_edit_mode = false;
|
||||
*command_message = "Exited script edit. Esc again to exit script.".to_string();
|
||||
} else {
|
||||
// Exit fullscreen
|
||||
add_logic_state.current_focus = AddLogicFocus::ScriptContentPreview;
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
*is_edit_mode = false;
|
||||
*command_message = "Exited script editing.".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if handled { return true; }
|
||||
|
||||
// ALL OTHER KEYS: Pass directly to textarea without any interference
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
if changed {
|
||||
add_logic_state.has_unsaved_changes = true;
|
||||
}
|
||||
|
||||
// Update edit mode status for Vim
|
||||
if add_logic_state.editor_keybinding_mode == EditorKeybindingMode::Vim {
|
||||
*is_edit_mode = !TextEditor::is_vim_normal_mode(&add_logic_state.vim_state);
|
||||
}
|
||||
|
||||
return true; // Always consume the event in fullscreen mode
|
||||
}
|
||||
// === END FULLSCREEN ISOLATION ===
|
||||
|
||||
// If not handled above (e.g., Tab/Shift+Tab, or Enter when script content not in edit mode),
|
||||
// process general application-level actions.
|
||||
let action_str = general_action.map(String::from);
|
||||
match action_str.as_deref() {
|
||||
Some("exit_view") | Some("cancel_action") => {
|
||||
buffer_state.update_history(AppView::Admin);
|
||||
app_state.ui.show_add_logic = false;
|
||||
*command_message = "Exited Add Logic".to_string();
|
||||
*is_edit_mode = false;
|
||||
handled = true;
|
||||
// Regular navigation logic for non-fullscreen elements
|
||||
let action = config.get_general_action(key_event.code, key_event.modifiers);
|
||||
let current_focus = add_logic_state.current_focus;
|
||||
let mut handled = true;
|
||||
let mut new_focus = current_focus;
|
||||
|
||||
match action.as_deref() {
|
||||
Some("exit_table_scroll") => {
|
||||
// This shouldn't happen since we handle InsideScriptContent above
|
||||
handled = false;
|
||||
}
|
||||
Some("next_field") | Some("prev_field") => {
|
||||
let is_next = action_str.as_deref() == Some("next_field");
|
||||
let previous_focus = add_logic_state.current_focus;
|
||||
|
||||
add_logic_state.current_focus = if is_next {
|
||||
match add_logic_state.current_focus {
|
||||
AddLogicFocus::InputLogicName => AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::InputTargetColumn => AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::InputDescription => AddLogicFocus::InputScriptContent,
|
||||
AddLogicFocus::InputScriptContent => AddLogicFocus::SaveButton,
|
||||
AddLogicFocus::SaveButton => AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::CancelButton => AddLogicFocus::InputLogicName,
|
||||
Some("move_up") => {
|
||||
match current_focus {
|
||||
AddLogicFocus::InputLogicName => {
|
||||
// Stay at top
|
||||
}
|
||||
} else {
|
||||
match add_logic_state.current_focus {
|
||||
AddLogicFocus::InputLogicName => AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::InputTargetColumn => AddLogicFocus::InputLogicName,
|
||||
AddLogicFocus::InputDescription => AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::InputScriptContent => AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::SaveButton => AddLogicFocus::InputScriptContent,
|
||||
AddLogicFocus::CancelButton => AddLogicFocus::SaveButton,
|
||||
}
|
||||
};
|
||||
|
||||
if add_logic_state.current_focus == AddLogicFocus::InputScriptContent {
|
||||
*is_edit_mode = false;
|
||||
let mode_hint = match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => "'i'/'a'/'o' to insert",
|
||||
_ => "Enter/Ctrl+E to edit",
|
||||
};
|
||||
*command_message = format!("Focus: Script Content. Press {} or Tab.", mode_hint);
|
||||
} else if matches!(add_logic_state.current_focus, AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription) {
|
||||
*is_edit_mode = true;
|
||||
*command_message = format!("Focus: {:?}. Edit mode ON.", add_logic_state.current_focus);
|
||||
} else {
|
||||
*is_edit_mode = false;
|
||||
*command_message = format!("Focus: {:?}", add_logic_state.current_focus);
|
||||
AddLogicFocus::InputTargetColumn => new_focus = AddLogicFocus::InputLogicName,
|
||||
AddLogicFocus::InputDescription => new_focus = AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::ScriptContentPreview => new_focus = AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::SaveButton => new_focus = AddLogicFocus::ScriptContentPreview,
|
||||
AddLogicFocus::CancelButton => new_focus = AddLogicFocus::SaveButton,
|
||||
_ => handled = false,
|
||||
}
|
||||
|
||||
app_state.ui.focus_outside_canvas = !matches!(
|
||||
add_logic_state.current_focus,
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription | AddLogicFocus::InputScriptContent
|
||||
);
|
||||
handled = true;
|
||||
}
|
||||
Some("move_down") => {
|
||||
match current_focus {
|
||||
AddLogicFocus::InputLogicName => new_focus = AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::InputTargetColumn => new_focus = AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::InputDescription => {
|
||||
add_logic_state.last_canvas_field = 2;
|
||||
new_focus = AddLogicFocus::ScriptContentPreview;
|
||||
},
|
||||
AddLogicFocus::ScriptContentPreview => new_focus = AddLogicFocus::SaveButton,
|
||||
AddLogicFocus::SaveButton => new_focus = AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::CancelButton => {
|
||||
// Stay at bottom
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("next_option") => {
|
||||
match current_focus {
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription =>
|
||||
{ new_focus = AddLogicFocus::ScriptContentPreview; }
|
||||
AddLogicFocus::ScriptContentPreview => new_focus = AddLogicFocus::SaveButton,
|
||||
AddLogicFocus::SaveButton => new_focus = AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::CancelButton => { /* Stay at last */ }
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("previous_option") => {
|
||||
match current_focus {
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription =>
|
||||
{ /* Stay at first */ }
|
||||
AddLogicFocus::ScriptContentPreview => new_focus = AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::SaveButton => new_focus = AddLogicFocus::ScriptContentPreview,
|
||||
AddLogicFocus::CancelButton => new_focus = AddLogicFocus::SaveButton,
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("next_field") => {
|
||||
new_focus = match current_focus {
|
||||
AddLogicFocus::InputLogicName => AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::InputTargetColumn => AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::InputDescription => AddLogicFocus::ScriptContentPreview,
|
||||
AddLogicFocus::ScriptContentPreview => AddLogicFocus::SaveButton,
|
||||
AddLogicFocus::SaveButton => AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::CancelButton => AddLogicFocus::InputLogicName,
|
||||
_ => current_focus,
|
||||
};
|
||||
}
|
||||
Some("prev_field") => {
|
||||
new_focus = match current_focus {
|
||||
AddLogicFocus::InputLogicName => AddLogicFocus::CancelButton,
|
||||
AddLogicFocus::InputTargetColumn => AddLogicFocus::InputLogicName,
|
||||
AddLogicFocus::InputDescription => AddLogicFocus::InputTargetColumn,
|
||||
AddLogicFocus::ScriptContentPreview => AddLogicFocus::InputDescription,
|
||||
AddLogicFocus::SaveButton => AddLogicFocus::ScriptContentPreview,
|
||||
AddLogicFocus::CancelButton => AddLogicFocus::SaveButton,
|
||||
_ => current_focus,
|
||||
};
|
||||
}
|
||||
Some("select") => {
|
||||
match add_logic_state.current_focus {
|
||||
AddLogicFocus::InputScriptContent => {
|
||||
*is_edit_mode = true;
|
||||
let mut editor_borrow = add_logic_state.script_content_editor.borrow_mut();
|
||||
match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => {
|
||||
TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE),
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
*command_message = "VIM: Insert Mode.".to_string();
|
||||
}
|
||||
_ => {
|
||||
*command_message = "Entered script edit mode.".to_string();
|
||||
}
|
||||
}
|
||||
handled = true;
|
||||
match current_focus {
|
||||
AddLogicFocus::ScriptContentPreview => {
|
||||
new_focus = AddLogicFocus::InsideScriptContent;
|
||||
*is_edit_mode = false; // Start in preview mode
|
||||
app_state.ui.focus_outside_canvas = false; // Script is like canvas
|
||||
let mode_hint = match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => "VIM mode - 'i'/'a'/'o' to edit",
|
||||
_ => "Enter/Ctrl+E to edit",
|
||||
};
|
||||
*command_message = format!("Fullscreen script editing. {} or Esc to exit.", mode_hint);
|
||||
}
|
||||
AddLogicFocus::SaveButton => {
|
||||
*command_message = "Save logic action".to_string();
|
||||
}
|
||||
AddLogicFocus::CancelButton => {
|
||||
buffer_state.update_history(AppView::Admin);
|
||||
app_state.ui.show_add_logic = false;
|
||||
*command_message = "Cancelled Add Logic".to_string();
|
||||
*is_edit_mode = false;
|
||||
}
|
||||
AddLogicFocus::SaveButton => { handled = true; }
|
||||
AddLogicFocus::CancelButton => { *is_edit_mode = false; handled = true; }
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription => {
|
||||
*is_edit_mode = !*is_edit_mode;
|
||||
*command_message = format!("Field edit mode: {}", if *is_edit_mode { "ON" } else { "OFF" });
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("toggle_edit_mode") => {
|
||||
match add_logic_state.current_focus {
|
||||
AddLogicFocus::InputScriptContent => {
|
||||
let mut editor_borrow = add_logic_state.script_content_editor.borrow_mut();
|
||||
match add_logic_state.editor_keybinding_mode {
|
||||
EditorKeybindingMode::Vim => {
|
||||
if *is_edit_mode {
|
||||
TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
if TextEditor::is_vim_normal_mode(&add_logic_state.vim_state) {
|
||||
*is_edit_mode = false;
|
||||
*command_message = "VIM: Normal Mode. Tab to navigate.".to_string();
|
||||
} else {
|
||||
*command_message = "VIM: Still in Insert Mode (toggle error?).".to_string();
|
||||
}
|
||||
} else {
|
||||
TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE),
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state,
|
||||
);
|
||||
*is_edit_mode = true;
|
||||
*command_message = "VIM: Insert Mode.".to_string();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
*is_edit_mode = !*is_edit_mode;
|
||||
*command_message = format!("Script edit mode: {}", if *is_edit_mode { "ON" } else { "OFF. Tab to navigate." });
|
||||
}
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
match current_focus {
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription => {
|
||||
*is_edit_mode = !*is_edit_mode;
|
||||
*command_message = format!("Canvas field edit mode: {}", if *is_edit_mode { "ON" } else { "OFF" });
|
||||
handled = true;
|
||||
}
|
||||
_ => { *command_message = "Cannot toggle edit mode here.".to_string(); handled = true; }
|
||||
_ => {
|
||||
*command_message = "Cannot toggle edit mode here.".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if add_logic_state.current_focus == AddLogicFocus::InputScriptContent &&
|
||||
!*is_edit_mode &&
|
||||
add_logic_state.editor_keybinding_mode == EditorKeybindingMode::Vim {
|
||||
let mut editor_borrow = add_logic_state.script_content_editor.borrow_mut();
|
||||
let changed = TextEditor::handle_input(
|
||||
&mut editor_borrow,
|
||||
key_event,
|
||||
&add_logic_state.editor_keybinding_mode,
|
||||
&mut add_logic_state.vim_state
|
||||
);
|
||||
if changed { add_logic_state.has_unsaved_changes = true; }
|
||||
handled = true;
|
||||
_ => handled = false,
|
||||
}
|
||||
|
||||
if handled && current_focus != new_focus {
|
||||
add_logic_state.current_focus = new_focus;
|
||||
|
||||
// Set edit mode and canvas focus based on new focus
|
||||
let new_is_canvas_input_focus = matches!(new_focus,
|
||||
AddLogicFocus::InputLogicName | AddLogicFocus::InputTargetColumn | AddLogicFocus::InputDescription
|
||||
);
|
||||
|
||||
if new_is_canvas_input_focus {
|
||||
// Entering canvas - start in readonly mode
|
||||
*is_edit_mode = false;
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
} else {
|
||||
// Outside canvas
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
if matches!(new_focus, AddLogicFocus::ScriptContentPreview) {
|
||||
*is_edit_mode = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handled
|
||||
}
|
||||
|
||||
@@ -12,11 +12,32 @@ use crate::services::GrpcClient;
|
||||
use tokio::sync::mpsc;
|
||||
use anyhow::Result;
|
||||
|
||||
// Define a type for the save result channel
|
||||
pub type SaveTableResultSender = mpsc::Sender<Result<String>>;
|
||||
|
||||
/// Handles navigation events specifically for the Add Table view.
|
||||
/// Returns true if the event was handled, false otherwise.
|
||||
fn navigate_table_up(table_state: &mut TableState, item_count: usize) -> bool {
|
||||
if item_count == 0 { return false; }
|
||||
let current_selection = table_state.selected();
|
||||
match current_selection {
|
||||
Some(index) => {
|
||||
if index > 0 { table_state.select(Some(index - 1)); true }
|
||||
else { false }
|
||||
}
|
||||
None => { table_state.select(Some(0)); true }
|
||||
}
|
||||
}
|
||||
|
||||
fn navigate_table_down(table_state: &mut TableState, item_count: usize) -> bool {
|
||||
if item_count == 0 { return false; }
|
||||
let current_selection = table_state.selected();
|
||||
match current_selection {
|
||||
Some(index) => {
|
||||
if index < item_count - 1 { table_state.select(Some(index + 1)); true }
|
||||
else { false }
|
||||
}
|
||||
None => { table_state.select(Some(0)); true }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_add_table_navigation(
|
||||
key: KeyEvent,
|
||||
config: &Config,
|
||||
@@ -28,61 +49,52 @@ pub fn handle_add_table_navigation(
|
||||
) -> bool {
|
||||
let action = config.get_general_action(key.code, key.modifiers);
|
||||
let current_focus = add_table_state.current_focus;
|
||||
let mut handled = true; // Assume handled unless logic determines otherwise
|
||||
let mut new_focus = current_focus; // Initialize new_focus
|
||||
let mut handled = true;
|
||||
let mut new_focus = current_focus;
|
||||
|
||||
if matches!(current_focus, AddTableFocus::InsideColumnsTable | AddTableFocus::InsideIndexesTable | AddTableFocus::InsideLinksTable) {
|
||||
if matches!(action.as_deref(), Some("next_option") | Some("previous_option")) {
|
||||
*command_message = "Press Esc to exit table item navigation first.".to_string();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
match action.as_deref() {
|
||||
// --- Handle Exiting Table Scroll Mode ---
|
||||
Some("exit_table_scroll") => {
|
||||
match current_focus {
|
||||
AddTableFocus::InsideColumnsTable => {
|
||||
add_table_state.column_table_state.select(None);
|
||||
new_focus = AddTableFocus::ColumnsTable;
|
||||
*command_message = "Exited Columns Table".to_string();
|
||||
// *command_message = "Exited Columns Table".to_string(); // Minimal change: remove message
|
||||
}
|
||||
AddTableFocus::InsideIndexesTable => {
|
||||
add_table_state.index_table_state.select(None);
|
||||
new_focus = AddTableFocus::IndexesTable;
|
||||
*command_message = "Exited Indexes Table".to_string();
|
||||
// *command_message = "Exited Indexes Table".to_string();
|
||||
}
|
||||
AddTableFocus::InsideLinksTable => {
|
||||
add_table_state.link_table_state.select(None);
|
||||
new_focus = AddTableFocus::LinksTable;
|
||||
*command_message = "Exited Links Table".to_string();
|
||||
}
|
||||
_ => {
|
||||
// Action triggered but not applicable in this focus state
|
||||
handled = false;
|
||||
// *command_message = "Exited Links Table".to_string();
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
// If handled (i.e., focus changed), handled remains true.
|
||||
// If not handled, handled becomes false.
|
||||
}
|
||||
|
||||
// --- Vertical Navigation (Up/Down) ---
|
||||
Some("move_up") => {
|
||||
match current_focus {
|
||||
AddTableFocus::InputTableName => new_focus = AddTableFocus::CancelButton,
|
||||
AddTableFocus::InputTableName => {
|
||||
// MINIMAL CHANGE: Do nothing, new_focus remains current_focus
|
||||
// *command_message = "At top of form.".to_string(); // Remove message
|
||||
}
|
||||
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputTableName,
|
||||
AddTableFocus::InputColumnType => new_focus = AddTableFocus::InputColumnName,
|
||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::InputColumnType,
|
||||
// Navigate between blocks when focus is on the table block itself
|
||||
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::AddColumnButton, // Move up to right pane
|
||||
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::AddColumnButton,
|
||||
AddTableFocus::IndexesTable => new_focus = AddTableFocus::ColumnsTable,
|
||||
AddTableFocus::LinksTable => new_focus = AddTableFocus::IndexesTable,
|
||||
// Scroll inside the table when focus is internal
|
||||
AddTableFocus::InsideColumnsTable => {
|
||||
navigate_table_up(&mut add_table_state.column_table_state, add_table_state.columns.len());
|
||||
// Stay inside the table, don't change new_focus
|
||||
}
|
||||
AddTableFocus::InsideIndexesTable => {
|
||||
navigate_table_up(&mut add_table_state.index_table_state, add_table_state.indexes.len());
|
||||
// Stay inside the table
|
||||
}
|
||||
AddTableFocus::InsideLinksTable => {
|
||||
navigate_table_up(&mut add_table_state.link_table_state, add_table_state.links.len());
|
||||
// Stay inside the table
|
||||
}
|
||||
AddTableFocus::InsideColumnsTable => { navigate_table_up(&mut add_table_state.column_table_state, add_table_state.columns.len()); }
|
||||
AddTableFocus::InsideIndexesTable => { navigate_table_up(&mut add_table_state.index_table_state, add_table_state.indexes.len()); }
|
||||
AddTableFocus::InsideLinksTable => { navigate_table_up(&mut add_table_state.link_table_state, add_table_state.links.len()); }
|
||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::LinksTable,
|
||||
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::SaveButton,
|
||||
AddTableFocus::CancelButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||
@@ -92,306 +104,102 @@ pub fn handle_add_table_navigation(
|
||||
match current_focus {
|
||||
AddTableFocus::InputTableName => new_focus = AddTableFocus::InputColumnName,
|
||||
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputColumnType,
|
||||
AddTableFocus::InputColumnType => new_focus = AddTableFocus::AddColumnButton,
|
||||
AddTableFocus::InputColumnType => {
|
||||
add_table_state.last_canvas_field = 2;
|
||||
new_focus = AddTableFocus::AddColumnButton;
|
||||
},
|
||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::ColumnsTable,
|
||||
// Navigate between blocks when focus is on the table block itself
|
||||
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::IndexesTable,
|
||||
AddTableFocus::IndexesTable => new_focus = AddTableFocus::LinksTable,
|
||||
AddTableFocus::LinksTable => new_focus = AddTableFocus::SaveButton, // Move down to right pane
|
||||
// Scroll inside the table when focus is internal
|
||||
AddTableFocus::InsideColumnsTable => {
|
||||
navigate_table_down(&mut add_table_state.column_table_state, add_table_state.columns.len());
|
||||
// Stay inside the table
|
||||
}
|
||||
AddTableFocus::InsideIndexesTable => {
|
||||
navigate_table_down(&mut add_table_state.index_table_state, add_table_state.indexes.len());
|
||||
// Stay inside the table
|
||||
}
|
||||
AddTableFocus::InsideLinksTable => {
|
||||
navigate_table_down(&mut add_table_state.link_table_state, add_table_state.links.len());
|
||||
// Stay inside the table
|
||||
}
|
||||
AddTableFocus::LinksTable => new_focus = AddTableFocus::SaveButton,
|
||||
AddTableFocus::InsideColumnsTable => { navigate_table_down(&mut add_table_state.column_table_state, add_table_state.columns.len()); }
|
||||
AddTableFocus::InsideIndexesTable => { navigate_table_down(&mut add_table_state.index_table_state, add_table_state.indexes.len()); }
|
||||
AddTableFocus::InsideLinksTable => { navigate_table_down(&mut add_table_state.link_table_state, add_table_state.links.len()); }
|
||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::CancelButton,
|
||||
AddTableFocus::CancelButton => new_focus = AddTableFocus::InputTableName,
|
||||
AddTableFocus::CancelButton => {
|
||||
// MINIMAL CHANGE: Do nothing, new_focus remains current_focus
|
||||
// *command_message = "At bottom of form.".to_string(); // Remove message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Horizontal Navigation (Left/Right) ---
|
||||
Some("next_option") => { // 'l' or Right: Move from Left Pane to Right Pane
|
||||
// Horizontal nav within bottom buttons
|
||||
if current_focus == AddTableFocus::SaveButton {
|
||||
new_focus = AddTableFocus::DeleteSelectedButton;
|
||||
} else if current_focus == AddTableFocus::DeleteSelectedButton {
|
||||
new_focus = AddTableFocus::CancelButton;
|
||||
}
|
||||
Some("next_option") => { // This logic should already be non-wrapping
|
||||
match current_focus {
|
||||
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType =>
|
||||
{ new_focus = AddTableFocus::AddColumnButton; }
|
||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::ColumnsTable,
|
||||
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::IndexesTable,
|
||||
AddTableFocus::IndexesTable => new_focus = AddTableFocus::LinksTable,
|
||||
AddTableFocus::LinksTable => new_focus = AddTableFocus::SaveButton,
|
||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::CancelButton,
|
||||
AddTableFocus::CancelButton => { /* *command_message = "At last focusable area.".to_string(); */ } // No change in focus
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("previous_option") => { // 'h' or Left: Move from Right Pane to Left Pane
|
||||
// Horizontal nav within bottom buttons
|
||||
if current_focus == AddTableFocus::CancelButton {
|
||||
new_focus = AddTableFocus::DeleteSelectedButton;
|
||||
} else if current_focus == AddTableFocus::DeleteSelectedButton {
|
||||
new_focus = AddTableFocus::SaveButton;
|
||||
}
|
||||
Some("previous_option") => { // This logic should already be non-wrapping
|
||||
match current_focus {
|
||||
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType =>
|
||||
{ /* *command_message = "At first focusable area.".to_string(); */ } // No change in focus
|
||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::InputColumnType,
|
||||
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::AddColumnButton,
|
||||
AddTableFocus::IndexesTable => new_focus = AddTableFocus::ColumnsTable,
|
||||
AddTableFocus::LinksTable => new_focus = AddTableFocus::IndexesTable,
|
||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::LinksTable,
|
||||
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::SaveButton,
|
||||
AddTableFocus::CancelButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
// --- Tab / Shift+Tab Navigation (Keep as vertical cycle) ---
|
||||
Some("next_field") => { // Tab
|
||||
Some("next_field") => {
|
||||
new_focus = match current_focus {
|
||||
AddTableFocus::InputTableName => AddTableFocus::InputColumnName,
|
||||
AddTableFocus::InputColumnName => AddTableFocus::InputColumnType,
|
||||
AddTableFocus::InputColumnType => AddTableFocus::AddColumnButton,
|
||||
AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable,
|
||||
// Treat Inside* same as block focus for tabbing out
|
||||
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::IndexesTable,
|
||||
AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::LinksTable,
|
||||
AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::SaveButton,
|
||||
AddTableFocus::SaveButton => AddTableFocus::DeleteSelectedButton,
|
||||
AddTableFocus::DeleteSelectedButton => AddTableFocus::CancelButton,
|
||||
AddTableFocus::CancelButton => AddTableFocus::InputTableName, // Wrap
|
||||
AddTableFocus::InputTableName => AddTableFocus::InputColumnName, AddTableFocus::InputColumnName => AddTableFocus::InputColumnType, AddTableFocus::InputColumnType => AddTableFocus::AddColumnButton, AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable,
|
||||
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::IndexesTable, AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::LinksTable, AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::SaveButton,
|
||||
AddTableFocus::SaveButton => AddTableFocus::DeleteSelectedButton, AddTableFocus::DeleteSelectedButton => AddTableFocus::CancelButton, AddTableFocus::CancelButton => AddTableFocus::InputTableName,
|
||||
};
|
||||
}
|
||||
Some("prev_field") => { // Shift+Tab
|
||||
Some("prev_field") => {
|
||||
new_focus = match current_focus {
|
||||
AddTableFocus::InputTableName => AddTableFocus::CancelButton, // Wrap
|
||||
AddTableFocus::InputColumnName => AddTableFocus::InputTableName,
|
||||
AddTableFocus::InputColumnType => AddTableFocus::InputColumnName,
|
||||
AddTableFocus::AddColumnButton => AddTableFocus::InputColumnType,
|
||||
// Treat Inside* same as block focus for tabbing out
|
||||
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::AddColumnButton,
|
||||
AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::ColumnsTable,
|
||||
AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::IndexesTable,
|
||||
AddTableFocus::SaveButton => AddTableFocus::LinksTable,
|
||||
AddTableFocus::DeleteSelectedButton => AddTableFocus::SaveButton,
|
||||
AddTableFocus::CancelButton => AddTableFocus::DeleteSelectedButton,
|
||||
AddTableFocus::InputTableName => AddTableFocus::CancelButton, AddTableFocus::InputColumnName => AddTableFocus::InputTableName, AddTableFocus::InputColumnType => AddTableFocus::InputColumnName, AddTableFocus::AddColumnButton => AddTableFocus::InputColumnType,
|
||||
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::AddColumnButton, AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::ColumnsTable, AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::IndexesTable,
|
||||
AddTableFocus::SaveButton => AddTableFocus::LinksTable, AddTableFocus::DeleteSelectedButton => AddTableFocus::SaveButton, AddTableFocus::CancelButton => AddTableFocus::DeleteSelectedButton,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Selection ---
|
||||
Some("select") => {
|
||||
match current_focus {
|
||||
// --- Enter/Exit Table Focus ---
|
||||
AddTableFocus::ColumnsTable => {
|
||||
new_focus = AddTableFocus::InsideColumnsTable;
|
||||
// Select first item if none selected when entering
|
||||
if add_table_state.column_table_state.selected().is_none() && !add_table_state.columns.is_empty() {
|
||||
add_table_state.column_table_state.select(Some(0));
|
||||
}
|
||||
*command_message = "Entered Columns Table (Scroll with Up/Down, Select to exit)".to_string();
|
||||
}
|
||||
AddTableFocus::IndexesTable => {
|
||||
new_focus = AddTableFocus::InsideIndexesTable;
|
||||
if add_table_state.index_table_state.selected().is_none() && !add_table_state.indexes.is_empty() {
|
||||
add_table_state.index_table_state.select(Some(0));
|
||||
}
|
||||
*command_message = "Entered Indexes Table (Scroll with Up/Down, Select to exit)".to_string();
|
||||
}
|
||||
AddTableFocus::LinksTable => {
|
||||
new_focus = AddTableFocus::InsideLinksTable;
|
||||
if add_table_state.link_table_state.selected().is_none() && !add_table_state.links.is_empty() {
|
||||
add_table_state.link_table_state.select(Some(0));
|
||||
}
|
||||
*command_message = "Entered Links Table (Scroll with Up/Down, Select to toggle/exit)".to_string();
|
||||
}
|
||||
AddTableFocus::InsideColumnsTable => {
|
||||
// Toggle selection when pressing select *inside* the columns table
|
||||
if let Some(index) = add_table_state.column_table_state.selected() {
|
||||
if let Some(col) = add_table_state.columns.get_mut(index) {
|
||||
col.selected = !col.selected;
|
||||
add_table_state.has_unsaved_changes = true;
|
||||
*command_message = format!(
|
||||
"Toggled selection for column: {} to {}",
|
||||
col.name, col.selected
|
||||
);
|
||||
}
|
||||
} else {
|
||||
*command_message = "No column highlighted to toggle selection".to_string();
|
||||
}
|
||||
}
|
||||
AddTableFocus::InsideIndexesTable => {
|
||||
// Select does nothing here anymore, only Esc exits.
|
||||
if let Some(index) = add_table_state.index_table_state.selected() {
|
||||
if let Some(idx_def) = add_table_state.indexes.get_mut(index) {
|
||||
idx_def.selected = !idx_def.selected;
|
||||
add_table_state.has_unsaved_changes = true;
|
||||
*command_message = format!(
|
||||
"Toggled selection for index: {} to {}",
|
||||
idx_def.name, idx_def.selected
|
||||
);
|
||||
} else {
|
||||
*command_message = "Error: Selected index out of bounds".to_string();
|
||||
}
|
||||
} else {
|
||||
*command_message = "No index selected (Press Esc to exit scroll mode)".to_string();
|
||||
}
|
||||
}
|
||||
AddTableFocus::InsideLinksTable => {
|
||||
// Toggle selection when pressing select *inside* the links table
|
||||
if let Some(index) = add_table_state.link_table_state.selected() {
|
||||
if let Some(link) = add_table_state.links.get_mut(index) {
|
||||
link.selected = !link.selected; // Toggle the selected state
|
||||
add_table_state.has_unsaved_changes = true; // Mark changes
|
||||
*command_message = format!(
|
||||
"Toggled selection for link: {} to {}",
|
||||
link.linked_table_name, link.selected
|
||||
);
|
||||
} else {
|
||||
*command_message = "Error: Selected link index out of bounds".to_string();
|
||||
}
|
||||
} else {
|
||||
*command_message = "No link selected to toggle".to_string();
|
||||
}
|
||||
// Stay inside the links table after toggling
|
||||
new_focus = AddTableFocus::InsideLinksTable;
|
||||
// Alternative: Exit after toggle:
|
||||
// new_focus = AddTableFocus::LinksTable;
|
||||
// *command_message = format!("{} - Exited Links Table", command_message);
|
||||
}
|
||||
// --- Other Select Actions ---
|
||||
AddTableFocus::AddColumnButton => {
|
||||
if let Some(focus_after_add) = handle_add_column_action(add_table_state, command_message) {
|
||||
new_focus = focus_after_add;
|
||||
}
|
||||
}
|
||||
AddTableFocus::SaveButton => {
|
||||
// --- Initiate Async Save ---
|
||||
if add_table_state.table_name.is_empty() {
|
||||
*command_message = "Cannot save: Table name is empty.".to_string();
|
||||
} else if add_table_state.columns.is_empty() {
|
||||
*command_message = "Cannot save: No columns defined.".to_string();
|
||||
} else {
|
||||
*command_message = "Saving table...".to_string();
|
||||
app_state.show_loading_dialog("Saving", "Please wait...");
|
||||
|
||||
let mut client_clone = grpc_client.clone();
|
||||
let state_clone = add_table_state.clone();
|
||||
let sender_clone = save_result_sender.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let result = handle_save_table_action(&mut client_clone, &state_clone).await;
|
||||
let _ = sender_clone.send(result).await; // Send result back
|
||||
});
|
||||
}
|
||||
// --- End Initiate Async Save ---
|
||||
}
|
||||
AddTableFocus::DeleteSelectedButton => {
|
||||
// --- Show Confirmation Dialog ---
|
||||
// Collect tuples of (index, name, type) for selected columns
|
||||
let columns_to_delete: Vec<(usize, String, String)> = add_table_state
|
||||
.columns
|
||||
.iter()
|
||||
.enumerate() // Get index along with the column
|
||||
.filter(|(_index, col)| col.selected) // Filter based on selection
|
||||
.map(|(index, col)| (index, col.name.clone(), col.data_type.clone())) // Map to (index, name, type)
|
||||
.collect();
|
||||
|
||||
if columns_to_delete.is_empty() {
|
||||
*command_message = "No columns selected for deletion.".to_string();
|
||||
} else {
|
||||
// Format the message to include index, name, and type
|
||||
let column_details: String = columns_to_delete
|
||||
.iter()
|
||||
// Add 1 to index for 1-based numbering for user display
|
||||
.map(|(index, name, dtype)| format!("{}. {} ({})", index + 1, name, dtype))
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n");
|
||||
|
||||
// Use the formatted column_details string in the message
|
||||
let message = format!(
|
||||
"Delete the following columns?\n\n{}",
|
||||
column_details
|
||||
);
|
||||
let buttons = vec!["Confirm".to_string(), "Cancel".to_string()];
|
||||
app_state.show_dialog(
|
||||
"Confirm Deletion",
|
||||
&message,
|
||||
buttons,
|
||||
DialogPurpose::ConfirmDeleteColumns,
|
||||
);
|
||||
}
|
||||
}
|
||||
AddTableFocus::CancelButton => {
|
||||
*command_message = "Action: Cancel Add Table".to_string();
|
||||
// TODO: Implement logic
|
||||
}
|
||||
_ => { // Input fields
|
||||
*command_message = format!("Select on {:?}", current_focus);
|
||||
handled = false; // Let main loop handle edit mode toggle maybe
|
||||
}
|
||||
AddTableFocus::ColumnsTable => { new_focus = AddTableFocus::InsideColumnsTable; if add_table_state.column_table_state.selected().is_none() && !add_table_state.columns.is_empty() { add_table_state.column_table_state.select(Some(0)); } /* Message removed */ }
|
||||
AddTableFocus::IndexesTable => { new_focus = AddTableFocus::InsideIndexesTable; if add_table_state.index_table_state.selected().is_none() && !add_table_state.indexes.is_empty() { add_table_state.index_table_state.select(Some(0)); } /* Message removed */ }
|
||||
AddTableFocus::LinksTable => { new_focus = AddTableFocus::InsideLinksTable; if add_table_state.link_table_state.selected().is_none() && !add_table_state.links.is_empty() { add_table_state.link_table_state.select(Some(0)); } /* Message removed */ }
|
||||
AddTableFocus::InsideColumnsTable => { if let Some(index) = add_table_state.column_table_state.selected() { if let Some(col) = add_table_state.columns.get_mut(index) { col.selected = !col.selected; add_table_state.has_unsaved_changes = true; /* Message removed */ }} /* else { Message removed } */ }
|
||||
AddTableFocus::InsideIndexesTable => { if let Some(index) = add_table_state.index_table_state.selected() { if let Some(idx_def) = add_table_state.indexes.get_mut(index) { idx_def.selected = !idx_def.selected; add_table_state.has_unsaved_changes = true; /* Message removed */ }} /* else { Message removed } */ }
|
||||
AddTableFocus::InsideLinksTable => { if let Some(index) = add_table_state.link_table_state.selected() { if let Some(link) = add_table_state.links.get_mut(index) { link.selected = !link.selected; add_table_state.has_unsaved_changes = true; /* Message removed */ }} /* else { Message removed } */ }
|
||||
AddTableFocus::AddColumnButton => { if let Some(focus_after_add) = handle_add_column_action(add_table_state, command_message) { new_focus = focus_after_add; } else { /* Message already set by handle_add_column_action */ }}
|
||||
AddTableFocus::SaveButton => { if add_table_state.table_name.is_empty() { *command_message = "Cannot save: Table name is empty.".to_string(); } else if add_table_state.columns.is_empty() { *command_message = "Cannot save: No columns defined.".to_string(); } else { *command_message = "Saving table...".to_string(); app_state.show_loading_dialog("Saving", "Please wait..."); let mut client_clone = grpc_client.clone(); let state_clone = add_table_state.clone(); let sender_clone = save_result_sender.clone(); tokio::spawn(async move { let result = handle_save_table_action(&mut client_clone, &state_clone).await; let _ = sender_clone.send(result).await; }); }}
|
||||
AddTableFocus::DeleteSelectedButton => { let columns_to_delete: Vec<(usize, String, String)> = add_table_state.columns.iter().enumerate().filter(|(_, col)| col.selected).map(|(index, col)| (index, col.name.clone(), col.data_type.clone())).collect(); if columns_to_delete.is_empty() { *command_message = "No columns selected for deletion.".to_string(); } else { let column_details: String = columns_to_delete.iter().map(|(index, name, dtype)| format!("{}. {} ({})", index + 1, name, dtype)).collect::<Vec<String>>().join("\n"); let message = format!("Delete the following columns?\n\n{}", column_details); app_state.show_dialog("Confirm Deletion", &message, vec!["Confirm".to_string(), "Cancel".to_string()], DialogPurpose::ConfirmDeleteColumns); }}
|
||||
AddTableFocus::CancelButton => { *command_message = "Action: Cancel Add Table (Not Implemented)".to_string(); }
|
||||
_ => { handled = false; }
|
||||
}
|
||||
// Keep handled = true for select actions unless specifically set to false
|
||||
}
|
||||
|
||||
// --- Other General Keys ---
|
||||
Some("toggle_sidebar") | Some("toggle_buffer_list") => {
|
||||
handled = false;
|
||||
}
|
||||
|
||||
// --- No matching action ---
|
||||
_ => handled = false,
|
||||
}
|
||||
|
||||
// Update focus state if it changed and was handled
|
||||
if handled && current_focus != new_focus {
|
||||
add_table_state.current_focus = new_focus;
|
||||
// Avoid overwriting specific messages set during 'select' handling
|
||||
if command_message.is_empty() || command_message.starts_with("Focus set to") {
|
||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
||||
// Minimal change: Command message update logic can be simplified or removed if not desired
|
||||
// For now, let's keep it minimal and only update if it was truly a focus change,
|
||||
// and not a boundary message.
|
||||
if !command_message.starts_with("At ") && current_focus != new_focus { // Avoid overwriting boundary messages
|
||||
// *command_message = format!("Focus: {:?}", add_table_state.current_focus); // Optional: restore if needed
|
||||
}
|
||||
|
||||
// Check if the *new* focus target is one of the canvas input fields
|
||||
|
||||
let new_is_canvas_input_focus = matches!(new_focus,
|
||||
AddTableFocus::InputTableName | AddTableFocus::InputColumnName | AddTableFocus::InputColumnType
|
||||
);
|
||||
// Focus is outside canvas if it's not an input field
|
||||
app_state.ui.focus_outside_canvas = !new_is_canvas_input_focus;
|
||||
} else if !handled {
|
||||
// command_message.clear(); // Optional: Clear message if not handled here
|
||||
}
|
||||
// If not handled, command_message remains as it was (e.g., from a deeper function call or previous event)
|
||||
// or can be cleared if that's the desired default. For minimal change, we leave it.
|
||||
|
||||
handled
|
||||
}
|
||||
|
||||
|
||||
// Helper function for navigating up within a table state
|
||||
// Returns true if navigation happened within the table, false if it reached the top
|
||||
fn navigate_table_up(table_state: &mut TableState, item_count: usize) -> bool {
|
||||
if item_count == 0 { return false; }
|
||||
let current_selection = table_state.selected();
|
||||
match current_selection {
|
||||
Some(index) => {
|
||||
if index > 0 {
|
||||
table_state.select(Some(index - 1));
|
||||
true // Navigation happened
|
||||
} else {
|
||||
false // Was at the top
|
||||
}
|
||||
}
|
||||
None => { // No item selected, select the last one
|
||||
table_state.select(Some(item_count - 1));
|
||||
true // Navigation happened (selection set)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for navigating down within a table state
|
||||
// Returns true if navigation happened within the table, false if it reached the bottom
|
||||
fn navigate_table_down(table_state: &mut TableState, item_count: usize) -> bool {
|
||||
if item_count == 0 { return false; }
|
||||
let current_selection = table_state.selected();
|
||||
match current_selection {
|
||||
Some(index) => {
|
||||
if index < item_count - 1 {
|
||||
table_state.select(Some(index + 1));
|
||||
true // Navigation happened
|
||||
} else {
|
||||
false // Was at the bottom
|
||||
}
|
||||
}
|
||||
None => { // No item selected, select the first one
|
||||
table_state.select(Some(0));
|
||||
true // Navigation happened (selection set)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,20 @@
|
||||
// src/functions/modes/navigation/admin_nav.rs
|
||||
|
||||
use crate::state::pages::admin::{AdminFocus, AdminState};
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::state::{
|
||||
app::state::AppState,
|
||||
pages::admin::{AdminFocus, AdminState},
|
||||
};
|
||||
use crossterm::event::KeyEvent;
|
||||
use crate::state::app::buffer::AppView;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use crate::state::app::buffer::{BufferState, AppView};
|
||||
use crate::state::pages::add_table::{AddTableState, LinkDefinition};
|
||||
use crate::state::pages::add_logic::AddLogicState;
|
||||
use ratatui::widgets::ListState;
|
||||
use crate::state::pages::add_logic::{AddLogicState, AddLogicFocus}; // Added AddLogicFocus import
|
||||
|
||||
// --- Helper functions for ListState navigation (similar to TableState) ---
|
||||
// Helper functions list_select_next and list_select_previous remain the same
|
||||
fn list_select_next(list_state: &mut ListState, item_count: usize) {
|
||||
if item_count == 0 {
|
||||
list_state.select(None);
|
||||
return;
|
||||
}
|
||||
let i = match list_state.selected() {
|
||||
Some(i) => {
|
||||
if i >= item_count - 1 { 0 } else { i + 1 }
|
||||
}
|
||||
Some(i) => if i >= item_count - 1 { 0 } else { i + 1 },
|
||||
None => 0,
|
||||
};
|
||||
list_state.select(Some(i));
|
||||
@@ -33,252 +26,323 @@ fn list_select_previous(list_state: &mut ListState, item_count: usize) {
|
||||
return;
|
||||
}
|
||||
let i = match list_state.selected() {
|
||||
Some(i) => {
|
||||
if i == 0 { item_count - 1 } else { i - 1 }
|
||||
}
|
||||
None => item_count - 1, // Select last if nothing was selected
|
||||
Some(i) => if i == 0 { item_count - 1 } else { i - 1 },
|
||||
None => if item_count > 0 { item_count - 1 } else { 0 },
|
||||
};
|
||||
list_state.select(Some(i));
|
||||
}
|
||||
|
||||
|
||||
/// Handles navigation events specifically for the Admin Panel view.
|
||||
/// Returns true if the event was handled, false otherwise.
|
||||
pub fn handle_admin_navigation(
|
||||
key: KeyEvent,
|
||||
key: crossterm::event::KeyEvent,
|
||||
config: &Config,
|
||||
app_state: &mut AppState,
|
||||
admin_state: &mut AdminState,
|
||||
buffer_state: &mut BufferState,
|
||||
command_message: &mut String,
|
||||
) -> bool {
|
||||
let action = config.get_general_action(key.code, key.modifiers).map(String::from); // Clone action string
|
||||
let action = config.get_general_action(key.code, key.modifiers).map(String::from);
|
||||
let current_focus = admin_state.current_focus;
|
||||
let profile_count = app_state.profile_tree.profiles.len();
|
||||
let mut new_focus = current_focus; // Start with current focus
|
||||
let mut handled = true; // Assume handled unless logic says otherwise
|
||||
let mut handled = false;
|
||||
|
||||
match action.as_deref() {
|
||||
// --- Vertical Navigation (Up/Down) ---
|
||||
Some("move_up") => {
|
||||
match current_focus {
|
||||
AdminFocus::Profiles => {
|
||||
if profile_count > 0 {
|
||||
admin_state.previous_profile(profile_count);
|
||||
*command_message = "Navigated profiles list".to_string();
|
||||
}
|
||||
}
|
||||
AdminFocus::Tables => {
|
||||
*command_message = "Press Enter to select and scroll tables".to_string();
|
||||
}
|
||||
AdminFocus::InsideTablesList => {
|
||||
if let Some(p_idx) = admin_state.profile_list_state.selected().or(admin_state.selected_profile_index) {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
list_select_previous(&mut admin_state.table_list_state, profile.tables.len());
|
||||
match current_focus {
|
||||
AdminFocus::ProfilesPane => {
|
||||
match action.as_deref() {
|
||||
Some("select") => {
|
||||
admin_state.current_focus = AdminFocus::InsideProfilesList;
|
||||
if !app_state.profile_tree.profiles.is_empty() {
|
||||
if admin_state.profile_list_state.selected().is_none() {
|
||||
admin_state.profile_list_state.select(Some(0));
|
||||
}
|
||||
}
|
||||
*command_message = "Navigating profiles. Use Up/Down. Esc to exit.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3 => {}
|
||||
}
|
||||
}
|
||||
Some("move_down") => {
|
||||
match current_focus {
|
||||
AdminFocus::Profiles => {
|
||||
if profile_count > 0 {
|
||||
admin_state.next_profile(profile_count);
|
||||
*command_message = "Navigated profiles list".to_string();
|
||||
}
|
||||
Some("next_option") | Some("move_down") => {
|
||||
admin_state.current_focus = AdminFocus::Tables;
|
||||
*command_message = "Focus: Tables Pane".to_string();
|
||||
handled = true;
|
||||
}
|
||||
AdminFocus::Tables => {
|
||||
*command_message = "Press Enter to select and scroll tables".to_string();
|
||||
}
|
||||
AdminFocus::InsideTablesList => {
|
||||
if let Some(p_idx) = admin_state.profile_list_state.selected().or(admin_state.selected_profile_index) {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
list_select_next(&mut admin_state.table_list_state, profile.tables.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3 => {}
|
||||
}
|
||||
}
|
||||
// --- Horizontal Navigation (Focus Change) ---
|
||||
Some("next_option") | Some("previous_option") => {
|
||||
let old_focus = admin_state.current_focus;
|
||||
let is_next = action.as_deref() == Some("next_option");
|
||||
|
||||
admin_state.current_focus = match old_focus {
|
||||
AdminFocus::Profiles => if is_next { AdminFocus::Tables } else { AdminFocus::Button3 },
|
||||
AdminFocus::Tables => if is_next { AdminFocus::Button1 } else { AdminFocus::Profiles },
|
||||
AdminFocus::Button1 => if is_next { AdminFocus::Button2 } else { AdminFocus::Tables },
|
||||
AdminFocus::Button2 => if is_next { AdminFocus::Button3 } else { AdminFocus::Button1 },
|
||||
AdminFocus::Button3 => if is_next { AdminFocus::Profiles } else { AdminFocus::Button2 },
|
||||
AdminFocus::InsideTablesList => old_focus,
|
||||
};
|
||||
|
||||
new_focus = admin_state.current_focus; // Update new_focus after changing admin_state.current_focus
|
||||
*command_message = format!("Focus set to {:?}", new_focus);
|
||||
if old_focus == AdminFocus::Profiles && new_focus == AdminFocus::Tables && is_next {
|
||||
if let Some(profile_idx) = admin_state.profile_list_state.selected() {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
admin_state.table_list_state.select(Some(0));
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
}
|
||||
if old_focus == AdminFocus::Tables && new_focus != AdminFocus::Tables && old_focus != AdminFocus::InsideTablesList {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
// No change needed for profile_list_state clearing here based on current logic
|
||||
}
|
||||
// --- Selection ---
|
||||
Some("select") => {
|
||||
match current_focus {
|
||||
AdminFocus::Profiles => {
|
||||
if let Some(nav_idx) = admin_state.profile_list_state.selected() {
|
||||
admin_state.selected_profile_index = Some(nav_idx);
|
||||
new_focus = AdminFocus::Tables;
|
||||
admin_state.table_list_state.select(None);
|
||||
admin_state.selected_table_index = None;
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(nav_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
admin_state.table_list_state.select(Some(0));
|
||||
}
|
||||
*command_message = format!("Selected profile: {}", app_state.profile_tree.profiles[nav_idx].name);
|
||||
}
|
||||
} else {
|
||||
*command_message = "No profile selected".to_string();
|
||||
}
|
||||
}
|
||||
AdminFocus::Tables => {
|
||||
new_focus = AdminFocus::InsideTablesList;
|
||||
if let Some(p_idx) = admin_state.profile_list_state.selected().or(admin_state.selected_profile_index) {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
if admin_state.table_list_state.selected().is_none() && !profile.tables.is_empty() {
|
||||
admin_state.table_list_state.select(Some(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
*command_message = "Entered Tables List (Select item with Enter, Exit with Esc)".to_string();
|
||||
}
|
||||
AdminFocus::InsideTablesList => {
|
||||
if let Some(nav_idx) = admin_state.table_list_state.selected() {
|
||||
admin_state.selected_table_index = Some(nav_idx);
|
||||
let table_name = admin_state.profile_list_state.selected().or(admin_state.selected_profile_index)
|
||||
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx))
|
||||
.and_then(|p| p.tables.get(nav_idx).map(|t| t.name.clone()))
|
||||
.unwrap_or_else(|| "N/A".to_string());
|
||||
*command_message = format!("Selected table: {}", table_name);
|
||||
} else {
|
||||
*command_message = "No table highlighted".to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// In src/functions/modes/navigation/admin_nav.rs
|
||||
AdminFocus::Button1 => { // Add Logic
|
||||
let mut logic_state_profile_name = "None (Global)".to_string();
|
||||
let mut selected_table_id: Option<i64> = None;
|
||||
let mut selected_table_name_for_logic: Option<String> = None;
|
||||
if let Some(p_idx) = admin_state.selected_profile_index {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
logic_state_profile_name = profile.name.clone();
|
||||
// Check for persistently selected table within this profile
|
||||
if let Some(t_idx) = admin_state.selected_table_index {
|
||||
if let Some(table) = profile.tables.get(t_idx) {
|
||||
selected_table_id = None;
|
||||
selected_table_name_for_logic = Some(table.name.clone());
|
||||
*command_message = format!("Adding logic for table: {}. CRITICAL: Table ID not found in profile tree response!", table.name);
|
||||
} else {
|
||||
*command_message = format!("Selected table index {} out of bounds for profile '{}'. Logic will not be table-specific.", t_idx, profile.name);
|
||||
}} else {
|
||||
*command_message = format!("No table selected in profile '{}'. Logic will not be table-specific.", profile.name);
|
||||
}
|
||||
} else {
|
||||
*command_message = "Error: Selected profile index out of bounds, associating with 'None'.".to_string();
|
||||
}
|
||||
} else {
|
||||
*command_message = "No profile selected ([*]), associating Logic with 'None (Global)'.".to_string();
|
||||
// Keep logic_state_profile_name as "None (Global)"
|
||||
}
|
||||
|
||||
// Create AddLogicState with the loaded config
|
||||
admin_state.add_logic_state = AddLogicState {
|
||||
profile_name: logic_state_profile_name.clone(),
|
||||
editor_keybinding_mode: config.editor.keybinding_mode.clone(), // Add this line
|
||||
..AddLogicState::default()
|
||||
};
|
||||
|
||||
buffer_state.update_history(AppView::AddLogic);
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
// Rest of the code remains the same...
|
||||
}
|
||||
AdminFocus::Button2 => {
|
||||
if let Some(p_idx) = admin_state.selected_profile_index {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
let selected_profile_name = profile.name.clone();
|
||||
let available_links: Vec<LinkDefinition> = profile
|
||||
.tables
|
||||
.iter()
|
||||
.map(|table| LinkDefinition {
|
||||
linked_table_name: table.name.clone(),
|
||||
is_required: false,
|
||||
selected: false,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let new_add_table_state = AddTableState {
|
||||
profile_name: selected_profile_name,
|
||||
links: available_links,
|
||||
..AddTableState::default()
|
||||
};
|
||||
admin_state.add_table_state = new_add_table_state;
|
||||
buffer_state.update_history(AppView::AddTable);
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
*command_message = format!(
|
||||
"Navigating to Add Table for profile '{}'...",
|
||||
admin_state.add_table_state.profile_name
|
||||
);
|
||||
} else {
|
||||
*command_message = "Error: Selected profile index out of bounds.".to_string();
|
||||
}
|
||||
} else {
|
||||
*command_message = "Please select a profile ([*]) first.".to_string();
|
||||
}
|
||||
}
|
||||
AdminFocus::Button3 => {
|
||||
*command_message = "Action: Change Table (Not Implemented)".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("exit_table_scroll") => {
|
||||
match current_focus {
|
||||
AdminFocus::InsideTablesList => {
|
||||
new_focus = AdminFocus::Tables;
|
||||
admin_state.table_list_state.select(None);
|
||||
*command_message = "Exited Tables List".to_string();
|
||||
Some("previous_option") | Some("move_up") => {
|
||||
// No wrap-around: Stay on ProfilesPane if trying to go "before" it
|
||||
*command_message = "At first focusable pane.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
Some("toggle_sidebar") | Some("toggle_buffer_list") | Some("next_field") | Some("prev_field") => {
|
||||
handled = false;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
|
||||
if handled && admin_state.current_focus != new_focus { // Check admin_state.current_focus
|
||||
admin_state.current_focus = new_focus;
|
||||
if command_message.is_empty() || command_message.starts_with("Focus set to") {
|
||||
*command_message = format!("Focus set to {:?}", admin_state.current_focus);
|
||||
AdminFocus::InsideProfilesList => {
|
||||
match action.as_deref() {
|
||||
Some("move_up") => {
|
||||
if profile_count > 0 {
|
||||
list_select_previous(&mut admin_state.profile_list_state, profile_count);
|
||||
*command_message = "".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
Some("move_down") => {
|
||||
if profile_count > 0 {
|
||||
list_select_next(&mut admin_state.profile_list_state, profile_count);
|
||||
*command_message = "".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
Some("select") => {
|
||||
admin_state.selected_profile_index = admin_state.profile_list_state.selected();
|
||||
admin_state.selected_table_index = None; // Deselect table when profile changes
|
||||
if let Some(profile_idx) = admin_state.selected_profile_index {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
admin_state.table_list_state.select(Some(0)); // Auto-select first table for nav
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
*command_message = format!(
|
||||
"Profile '{}' set as active.",
|
||||
admin_state.get_selected_profile_name().unwrap_or(&"N/A".to_string())
|
||||
);
|
||||
handled = true;
|
||||
}
|
||||
Some("exit_table_scroll") => {
|
||||
admin_state.current_focus = AdminFocus::ProfilesPane;
|
||||
*command_message = "Focus: Profiles Pane".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
AdminFocus::Tables => {
|
||||
match action.as_deref() {
|
||||
Some("select") => {
|
||||
admin_state.current_focus = AdminFocus::InsideTablesList;
|
||||
let current_profile_idx = admin_state.selected_profile_index
|
||||
.or_else(|| admin_state.profile_list_state.selected());
|
||||
if let Some(profile_idx) = current_profile_idx {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
if admin_state.table_list_state.selected().is_none() {
|
||||
admin_state.table_list_state.select(Some(0));
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
}
|
||||
} else {
|
||||
admin_state.table_list_state.select(None);
|
||||
*command_message = "Select a profile first to view its tables.".to_string();
|
||||
}
|
||||
if admin_state.current_focus == AdminFocus::InsideTablesList && !admin_state.table_list_state.selected().is_none() {
|
||||
*command_message = "Navigating tables. Use Up/Down. Esc to exit.".to_string();
|
||||
} else if admin_state.table_list_state.selected().is_none() {
|
||||
if current_profile_idx.is_none() {
|
||||
*command_message = "No profile selected to view tables.".to_string();
|
||||
} else {
|
||||
*command_message = "No tables in selected profile.".to_string();
|
||||
}
|
||||
admin_state.current_focus = AdminFocus::Tables; // Stay in Tables pane if no tables to enter
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
Some("previous_option") | Some("move_up") => {
|
||||
admin_state.current_focus = AdminFocus::ProfilesPane;
|
||||
*command_message = "Focus: Profiles Pane".to_string();
|
||||
handled = true;
|
||||
}
|
||||
Some("next_option") | Some("move_down") => {
|
||||
admin_state.current_focus = AdminFocus::Button1;
|
||||
*command_message = "Focus: Add Logic Button".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
AdminFocus::InsideTablesList => {
|
||||
match action.as_deref() {
|
||||
Some("move_up") => {
|
||||
let current_profile_idx = admin_state.selected_profile_index
|
||||
.or_else(|| admin_state.profile_list_state.selected());
|
||||
if let Some(p_idx) = current_profile_idx {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
list_select_previous(&mut admin_state.table_list_state, profile.tables.len());
|
||||
*command_message = "".to_string();
|
||||
handled = true;
|
||||
} else {
|
||||
*command_message = "No tables to navigate.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
*command_message = "No active profile for tables.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
Some("move_down") => {
|
||||
let current_profile_idx = admin_state.selected_profile_index
|
||||
.or_else(|| admin_state.profile_list_state.selected());
|
||||
if let Some(p_idx) = current_profile_idx {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
if !profile.tables.is_empty() {
|
||||
list_select_next(&mut admin_state.table_list_state, profile.tables.len());
|
||||
*command_message = "".to_string();
|
||||
handled = true;
|
||||
} else {
|
||||
*command_message = "No tables to navigate.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
*command_message = "No active profile for tables.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
Some("select") => { // This is for persistently selecting a table with [*]
|
||||
admin_state.selected_table_index = admin_state.table_list_state.selected();
|
||||
let table_name = admin_state.selected_profile_index
|
||||
.and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx))
|
||||
.and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx)))
|
||||
.map_or("N/A", |t| t.name.as_str());
|
||||
*command_message = format!("Table '{}' set as active.", table_name);
|
||||
handled = true;
|
||||
}
|
||||
Some("exit_table_scroll") => {
|
||||
admin_state.current_focus = AdminFocus::Tables;
|
||||
*command_message = "Focus: Tables Pane".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
AdminFocus::Button1 => { // Add Logic Button
|
||||
match action.as_deref() {
|
||||
Some("select") => { // Typically "Enter" key
|
||||
if let Some(p_idx) = admin_state.selected_profile_index {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
if let Some(t_idx) = admin_state.selected_table_index {
|
||||
if let Some(table) = profile.tables.get(t_idx) {
|
||||
// Both profile and table are selected, proceed
|
||||
admin_state.add_logic_state = AddLogicState {
|
||||
profile_name: profile.name.clone(),
|
||||
selected_table_name: Some(table.name.clone()),
|
||||
// selected_table_id: table.id, // If you have table IDs
|
||||
editor_keybinding_mode: config.editor.keybinding_mode.clone(),
|
||||
current_focus: AddLogicFocus::default(), // Reset focus for the new screen
|
||||
..AddLogicState::default()
|
||||
};
|
||||
buffer_state.update_history(AppView::AddLogic); // Switch view
|
||||
app_state.ui.focus_outside_canvas = false; // Ensure canvas focus
|
||||
*command_message = format!(
|
||||
"Opening Add Logic for table '{}' in profile '{}'...",
|
||||
table.name, profile.name
|
||||
);
|
||||
} else {
|
||||
// This case should ideally not be reached if indices are managed correctly
|
||||
*command_message = "Error: Selected table data not found.".to_string();
|
||||
}
|
||||
} else {
|
||||
// Profile is selected, but table is not
|
||||
*command_message = "Select a table first!".to_string();
|
||||
}
|
||||
} else {
|
||||
// This case should ideally not be reached if p_idx is valid
|
||||
*command_message = "Error: Selected profile data not found.".to_string();
|
||||
}
|
||||
} else {
|
||||
// Profile is not selected
|
||||
*command_message = "Select a profile first!".to_string();
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
Some("previous_option") | Some("move_up") => {
|
||||
admin_state.current_focus = AdminFocus::Tables;
|
||||
*command_message = "Focus: Tables Pane".to_string();
|
||||
handled = true;
|
||||
}
|
||||
Some("next_option") | Some("move_down") => {
|
||||
admin_state.current_focus = AdminFocus::Button2;
|
||||
*command_message = "Focus: Add Table Button".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
AdminFocus::Button2 => { // Add Table Button
|
||||
match action.as_deref() {
|
||||
Some("select") => {
|
||||
if let Some(p_idx) = admin_state.selected_profile_index {
|
||||
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||
let selected_profile_name = profile.name.clone();
|
||||
// Prepare links from the selected profile's existing tables
|
||||
let available_links: Vec<LinkDefinition> = profile.tables.iter()
|
||||
.map(|table| LinkDefinition {
|
||||
linked_table_name: table.name.clone(),
|
||||
is_required: false, // Default, can be changed in AddTable screen
|
||||
selected: false,
|
||||
}).collect();
|
||||
|
||||
admin_state.add_table_state = AddTableState {
|
||||
profile_name: selected_profile_name,
|
||||
links: available_links,
|
||||
..AddTableState::default() // Reset other fields
|
||||
};
|
||||
buffer_state.update_history(AppView::AddTable);
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
*command_message = format!("Opening Add Table for profile '{}'...", admin_state.add_table_state.profile_name);
|
||||
handled = true;
|
||||
} else {
|
||||
*command_message = "Error: Selected profile index out of bounds.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
} else {
|
||||
*command_message = "Please select a profile ([*]) first to add a table.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
Some("previous_option") | Some("move_up") => {
|
||||
admin_state.current_focus = AdminFocus::Button1;
|
||||
*command_message = "Focus: Add Logic Button".to_string();
|
||||
handled = true;
|
||||
}
|
||||
Some("next_option") | Some("move_down") => {
|
||||
admin_state.current_focus = AdminFocus::Button3;
|
||||
*command_message = "Focus: Change Table Button".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
|
||||
AdminFocus::Button3 => { // Change Table Button
|
||||
match action.as_deref() {
|
||||
Some("select") => {
|
||||
// Future: Logic to load selected table into AddTableState for editing
|
||||
*command_message = "Action: Change Table (Not Implemented)".to_string();
|
||||
handled = true;
|
||||
}
|
||||
Some("previous_option") | Some("move_up") => {
|
||||
admin_state.current_focus = AdminFocus::Button2;
|
||||
*command_message = "Focus: Add Table Button".to_string();
|
||||
handled = true;
|
||||
}
|
||||
Some("next_option") | Some("move_down") => {
|
||||
// No wrap-around: Stay on Button3 if trying to go "after" it
|
||||
*command_message = "At last focusable button.".to_string();
|
||||
handled = true;
|
||||
}
|
||||
_ => handled = false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handled
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||
pub async fn execute_action(
|
||||
action: &str,
|
||||
app_state: &mut AppState,
|
||||
state: &mut AddLogicState, // Changed
|
||||
state: &mut AddLogicState,
|
||||
ideal_cursor_column: &mut usize,
|
||||
key_sequence_tracker: &mut KeySequenceTracker,
|
||||
command_message: &mut String,
|
||||
@@ -75,7 +75,7 @@ pub async fn execute_action(
|
||||
match action {
|
||||
"move_up" => {
|
||||
key_sequence_tracker.reset();
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT;
|
||||
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||
let current_field = state.current_field();
|
||||
|
||||
@@ -87,20 +87,13 @@ pub async fn execute_action(
|
||||
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
} else {
|
||||
// Moving up from the first field (InputLogicName)
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
// Focus should go to the element logically above the canvas.
|
||||
// Based on AddLogicFocus, this might be CancelButton or another element.
|
||||
// For AddLogic, let's assume it's CancelButton, similar to AddTable.
|
||||
state.current_focus = crate::state::pages::add_logic::AddLogicFocus::CancelButton; // Changed
|
||||
key_sequence_tracker.reset();
|
||||
return Ok("Focus moved above canvas".to_string());
|
||||
*command_message = "At top of form.".to_string();
|
||||
}
|
||||
Ok("".to_string())
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_down" => {
|
||||
key_sequence_tracker.reset();
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT;
|
||||
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||
let current_field = state.current_field();
|
||||
let last_field_index = num_fields - 1;
|
||||
@@ -113,21 +106,19 @@ pub async fn execute_action(
|
||||
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
} else {
|
||||
// Moving down from the last field (InputDescription)
|
||||
// Move focus outside canvas when moving down from the last field
|
||||
// FIX: Go to ScriptContentPreview instead of SaveButton
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
// Focus should go to the element logically below the canvas.
|
||||
// This is likely InputScriptContent or SaveButton.
|
||||
// The add_logic_nav.rs handles transitions to InputScriptContent.
|
||||
// If moving from canvas directly to buttons, it would be SaveButton.
|
||||
state.current_focus = crate::state::pages::add_logic::AddLogicFocus::InputScriptContent; // Or SaveButton
|
||||
key_sequence_tracker.reset();
|
||||
return Ok("Focus moved to script/button area".to_string());
|
||||
state.last_canvas_field = 2;
|
||||
state.current_focus = crate::state::pages::add_logic::AddLogicFocus::ScriptContentPreview; // FIXED!
|
||||
*command_message = "Focus moved to script preview".to_string();
|
||||
}
|
||||
Ok("".to_string())
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
// ... (rest of the actions remain the same) ...
|
||||
"move_first_line" => {
|
||||
key_sequence_tracker.reset();
|
||||
if AddLogicState::INPUT_FIELD_COUNT > 0 { // Changed
|
||||
if AddLogicState::INPUT_FIELD_COUNT > 0 {
|
||||
state.set_current_field(0);
|
||||
let current_input = state.get_current_input();
|
||||
let max_cursor_pos = if current_input.is_empty() { 0 } else { current_input.len().saturating_sub(1) };
|
||||
@@ -139,7 +130,7 @@ pub async fn execute_action(
|
||||
}
|
||||
"move_last_line" => {
|
||||
key_sequence_tracker.reset();
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT; // Changed
|
||||
let num_fields = AddLogicState::INPUT_FIELD_COUNT;
|
||||
if num_fields > 0 {
|
||||
let last_field_index = num_fields - 1;
|
||||
state.set_current_field(last_field_index);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/functions/modes/read_only/add_table_ro.rs
|
||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
use crate::state::pages::canvas_state::CanvasState; // Use trait for common actions
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::state::app::state::AppState;
|
||||
use anyhow::Result;
|
||||
|
||||
@@ -80,41 +80,36 @@ pub async fn execute_action(
|
||||
"move_up" => {
|
||||
key_sequence_tracker.reset();
|
||||
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||
if num_fields == 0 {
|
||||
*command_message = "No fields.".to_string();
|
||||
return Ok(command_message.clone());
|
||||
}
|
||||
let current_field = state.current_field(); // Gets the index (0, 1, or 2)
|
||||
|
||||
if current_field > 0 {
|
||||
// This handles moving from field 2 -> 1, or 1 -> 0
|
||||
let new_field = current_field - 1;
|
||||
state.set_current_field(new_field);
|
||||
// ... (rest of the logic to set cursor position) ...
|
||||
let current_input = state.get_current_input();
|
||||
let max_cursor_pos = current_input.len(); // Allow cursor at end
|
||||
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos; // Update ideal column as cursor moved
|
||||
*command_message = "".to_string(); // Clear message for successful internal navigation
|
||||
} else {
|
||||
// --- THIS IS WHERE THE FIX GOES ---
|
||||
// current_field is 0 (InputTableName), and user pressed Up.
|
||||
// We need to move focus *outside* the canvas.
|
||||
|
||||
// Set the flag to indicate focus is leaving the canvas
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
|
||||
// Decide which element gets focus. Based on your layout and the
|
||||
// downward navigation (CancelButton wraps to InputTableName),
|
||||
// moving up from InputTableName should likely go to CancelButton.
|
||||
state.current_focus = crate::state::pages::add_table::AddTableFocus::CancelButton;
|
||||
|
||||
// Reset the sequence tracker as the action is complete
|
||||
key_sequence_tracker.reset();
|
||||
|
||||
// Return a message indicating the focus change
|
||||
return Ok("Focus moved above canvas".to_string());
|
||||
// --- END FIX ---
|
||||
// Forbid moving up. Do not change focus or cursor.
|
||||
*command_message = "At top of form.".to_string();
|
||||
}
|
||||
// If we moved within the canvas (e.g., 1 -> 0), return empty string
|
||||
Ok("".to_string())
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_down" => {
|
||||
key_sequence_tracker.reset();
|
||||
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||
if num_fields == 0 {
|
||||
*command_message = "No fields.".to_string();
|
||||
return Ok(command_message.clone());
|
||||
}
|
||||
let current_field = state.current_field();
|
||||
let last_field_index = num_fields - 1;
|
||||
|
||||
@@ -125,16 +120,19 @@ pub async fn execute_action(
|
||||
let max_cursor_pos = current_input.len(); // Allow cursor at end
|
||||
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos; // Update ideal column
|
||||
*command_message = "".to_string();
|
||||
} else {
|
||||
// Move focus outside canvas when moving down from the last field
|
||||
app_state.ui.focus_outside_canvas = true;
|
||||
// Set focus to the first element outside canvas (AddColumnButton)
|
||||
state.current_focus = crate::state::pages::add_table::AddTableFocus::AddColumnButton;
|
||||
key_sequence_tracker.reset();
|
||||
return Ok("Focus moved below canvas".to_string());
|
||||
state.current_focus =
|
||||
crate::state::pages::add_table::AddTableFocus::AddColumnButton;
|
||||
*command_message = "Focus moved below canvas".to_string();
|
||||
}
|
||||
Ok("".to_string())
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
// ... (other actions like "move_first_line", "move_left", etc. remain the same) ...
|
||||
"move_first_line" => {
|
||||
key_sequence_tracker.reset();
|
||||
if AddTableState::INPUT_FIELD_COUNT > 0 {
|
||||
@@ -145,7 +143,8 @@ pub async fn execute_action(
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos; // Update ideal column
|
||||
}
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_last_line" => {
|
||||
key_sequence_tracker.reset();
|
||||
@@ -159,14 +158,16 @@ pub async fn execute_action(
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos; // Update ideal column
|
||||
}
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_left" => {
|
||||
let current_pos = state.current_cursor_pos();
|
||||
let new_pos = current_pos.saturating_sub(1);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_right" => {
|
||||
let current_input = state.get_current_input();
|
||||
@@ -177,68 +178,90 @@ pub async fn execute_action(
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
}
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_word_next" => {
|
||||
let current_input = state.get_current_input();
|
||||
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
|
||||
let new_pos = find_next_word_start(
|
||||
current_input,
|
||||
state.current_cursor_pos(),
|
||||
);
|
||||
let final_pos = new_pos.min(current_input.len()); // Allow cursor at end
|
||||
state.set_current_cursor_pos(final_pos);
|
||||
*ideal_cursor_column = final_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_word_end" => {
|
||||
let current_input = state.get_current_input();
|
||||
let current_pos = state.current_cursor_pos();
|
||||
let new_pos = find_word_end(current_input, current_pos);
|
||||
// If find_word_end returns current_pos, try starting search from next char
|
||||
let final_pos = if new_pos == current_pos && current_pos < current_input.len() {
|
||||
find_word_end(current_input, current_pos + 1)
|
||||
} else {
|
||||
new_pos
|
||||
};
|
||||
let final_pos =
|
||||
if new_pos == current_pos && current_pos < current_input.len() {
|
||||
find_word_end(current_input, current_pos + 1)
|
||||
} else {
|
||||
new_pos
|
||||
};
|
||||
let max_valid_index = current_input.len(); // Allow cursor at end
|
||||
let clamped_pos = final_pos.min(max_valid_index);
|
||||
state.set_current_cursor_pos(clamped_pos);
|
||||
*ideal_cursor_column = clamped_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_word_prev" => {
|
||||
let current_input = state.get_current_input();
|
||||
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
|
||||
let new_pos = find_prev_word_start(
|
||||
current_input,
|
||||
state.current_cursor_pos(),
|
||||
);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_word_end_prev" => {
|
||||
let current_input = state.get_current_input();
|
||||
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
|
||||
let new_pos = find_prev_word_end(
|
||||
current_input,
|
||||
state.current_cursor_pos(),
|
||||
);
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_line_start" => {
|
||||
state.set_current_cursor_pos(0);
|
||||
*ideal_cursor_column = 0;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
"move_line_end" => {
|
||||
let current_input = state.get_current_input();
|
||||
let new_pos = current_input.len(); // Allow cursor at end
|
||||
state.set_current_cursor_pos(new_pos);
|
||||
*ideal_cursor_column = new_pos;
|
||||
Ok("".to_string())
|
||||
*command_message = "".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
// Actions handled by main event loop (mode changes)
|
||||
"enter_edit_mode_before" | "enter_edit_mode_after" | "enter_command_mode" | "exit_highlight_mode" => {
|
||||
key_sequence_tracker.reset();
|
||||
Ok("Mode change handled by main loop".to_string())
|
||||
"enter_edit_mode_before" | "enter_edit_mode_after"
|
||||
| "enter_command_mode" | "exit_highlight_mode" => {
|
||||
key_sequence_tracker.reset();
|
||||
// These actions are primarily mode changes handled by the main event loop.
|
||||
// The message here might be overridden by the main loop's message for mode change.
|
||||
*command_message = "Mode change initiated".to_string();
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
_ => {
|
||||
key_sequence_tracker.reset();
|
||||
command_message.clear(); // Clear message for unhandled actions
|
||||
Ok(format!("Unknown read-only action: {}", action))
|
||||
},
|
||||
key_sequence_tracker.reset();
|
||||
*command_message =
|
||||
format!("Unknown read-only action: {}", action);
|
||||
Ok(command_message.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,26 +5,27 @@ use crate::state::pages::{
|
||||
auth::{LoginState, RegisterState},
|
||||
canvas_state::CanvasState,
|
||||
};
|
||||
use crate::state::pages::add_logic::AddLogicState;
|
||||
use crate::state::pages::form::FormState;
|
||||
use crate::state::pages::add_table::AddTableState;
|
||||
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 crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use crossterm::event::KeyEvent; // Removed KeyCode, KeyModifiers as they were unused
|
||||
use tracing::debug;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EditEventOutcome {
|
||||
Message(String), // Return a message, stay in Edit mode
|
||||
ExitEditMode, // Signal to exit Edit mode
|
||||
Message(String),
|
||||
ExitEditMode,
|
||||
}
|
||||
|
||||
pub async fn handle_edit_event(
|
||||
key: KeyEvent,
|
||||
config: &Config,
|
||||
form_state: &mut FormState,
|
||||
form_state: &mut FormState, // Now FormState is in scope
|
||||
login_state: &mut LoginState,
|
||||
register_state: &mut RegisterState,
|
||||
admin_state: &mut AdminState,
|
||||
@@ -34,17 +35,20 @@ pub async fn handle_edit_event(
|
||||
grpc_client: &mut GrpcClient,
|
||||
app_state: &AppState,
|
||||
) -> Result<EditEventOutcome> {
|
||||
// Global command mode check (should ideally be handled before calling this function)
|
||||
// --- Global command mode check ---
|
||||
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
|
||||
&config.keybindings.global,
|
||||
&config.keybindings.global, // Assuming command mode can be entered globally
|
||||
key.code,
|
||||
key.modifiers,
|
||||
) {
|
||||
// This check might be redundant if EventHandler already prevents entering Edit mode
|
||||
// when command_mode is true. However, it's a safeguard.
|
||||
return Ok(EditEventOutcome::Message(
|
||||
"Command mode entry handled globally.".to_string(),
|
||||
"Cannot enter command mode from edit mode here.".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// --- Common actions (save, revert) ---
|
||||
if let Some(action) = config.get_action_for_key_in_mode(
|
||||
&config.keybindings.common,
|
||||
key.code,
|
||||
@@ -52,261 +56,197 @@ pub async fn handle_edit_event(
|
||||
).as_deref() {
|
||||
if matches!(action, "save" | "revert") {
|
||||
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?
|
||||
auth_e::execute_common_action(action, login_state, grpc_client, current_position, total_count).await?
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_common_action(
|
||||
action,
|
||||
register_state,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?
|
||||
auth_e::execute_common_action(action, register_state, grpc_client, current_position, total_count).await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
format!(
|
||||
"Action '{}' not fully implemented for Add Table view here.",
|
||||
action
|
||||
)
|
||||
// TODO: Implement common actions for AddTable if needed
|
||||
format!("Action '{}' not implemented for Add Table in edit mode.", action)
|
||||
} else if app_state.ui.show_add_logic {
|
||||
format!(
|
||||
"Action '{}' not fully implemented for Add Logic view here.",
|
||||
action
|
||||
)
|
||||
} else {
|
||||
let outcome = form_e::execute_common_action(
|
||||
action,
|
||||
form_state,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
)
|
||||
.await?;
|
||||
// TODO: Implement common actions for AddLogic if needed
|
||||
format!("Action '{}' not implemented for Add Logic in edit mode.", action)
|
||||
} else { // Assuming Form view
|
||||
let outcome = form_e::execute_common_action(action, form_state, grpc_client, current_position, total_count).await?;
|
||||
match outcome {
|
||||
EventOutcome::Ok(msg) => msg,
|
||||
EventOutcome::DataSaved(_, msg) => msg,
|
||||
_ => format!(
|
||||
"Unexpected outcome from common action: {:?}",
|
||||
outcome
|
||||
),
|
||||
EventOutcome::Ok(msg) | EventOutcome::DataSaved(_, msg) => msg,
|
||||
_ => format!("Unexpected outcome from common action: {:?}", outcome),
|
||||
}
|
||||
};
|
||||
return Ok(EditEventOutcome::Message(message_string));
|
||||
}
|
||||
}
|
||||
|
||||
// Edit-specific actions
|
||||
if let Some(action) =
|
||||
config.get_edit_action_for_key(key.code, key.modifiers)
|
||||
.as_deref() {
|
||||
// Handle enter_decider first
|
||||
if action == "enter_decider" {
|
||||
// --- Edit-specific actions ---
|
||||
if let Some(action_str) = config.get_edit_action_for_key(key.code, key.modifiers).as_deref() {
|
||||
// --- Handle "enter_decider" (Enter key) ---
|
||||
if action_str == "enter_decider" {
|
||||
let effective_action = if app_state.ui.show_register
|
||||
&& register_state.in_suggestion_mode
|
||||
&& register_state.current_field() == 4 {
|
||||
&& register_state.current_field() == 4 { // Role field
|
||||
"select_suggestion"
|
||||
} else if app_state.ui.show_add_logic
|
||||
&& admin_state.add_logic_state.in_target_column_suggestion_mode
|
||||
&& admin_state.add_logic_state.current_field() == 1 { // Target Column field
|
||||
"select_suggestion"
|
||||
} else {
|
||||
"next_field"
|
||||
"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?
|
||||
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?
|
||||
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?
|
||||
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_e::execute_edit_action(
|
||||
effective_action,
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
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));
|
||||
}
|
||||
|
||||
if action == "exit" {
|
||||
// --- Handle "exit" (Escape key) ---
|
||||
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?;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Special handling for role field suggestions (Register view only)
|
||||
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);
|
||||
return Ok(EditEventOutcome::Message(
|
||||
"Suggestions shown".to_string(),
|
||||
));
|
||||
} else {
|
||||
return Ok(EditEventOutcome::Message(
|
||||
"No suggestions available".to_string(),
|
||||
));
|
||||
// --- Autocomplete for AddLogicState Target Column ---
|
||||
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));
|
||||
}
|
||||
}
|
||||
if register_state.in_suggestion_mode
|
||||
&& matches!(
|
||||
action,
|
||||
"suggestion_down" | "suggestion_up"
|
||||
)
|
||||
{
|
||||
let msg = auth_e::execute_edit_action(
|
||||
action,
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?;
|
||||
} 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));
|
||||
}
|
||||
}
|
||||
|
||||
// Execute other edit actions based on the current view
|
||||
// --- 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 {
|
||||
auth_e::execute_edit_action(
|
||||
action,
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
auth_e::execute_edit_action(action_str, key, login_state, ideal_cursor_column).await?
|
||||
} else if app_state.ui.show_add_table {
|
||||
add_table_e::execute_edit_action(
|
||||
action,
|
||||
key,
|
||||
&mut admin_state.add_table_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
add_table_e::execute_edit_action(action_str, 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(
|
||||
action,
|
||||
key,
|
||||
&mut admin_state.add_logic_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
// If not a suggestion action handled above for AddLogic
|
||||
if !(admin_state.add_logic_state.in_target_column_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) {
|
||||
add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
|
||||
} else { String::new() /* Already handled */ }
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
action,
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
form_e::execute_edit_action(
|
||||
action,
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
if !(register_state.in_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) {
|
||||
auth_e::execute_edit_action(action_str, key, register_state, ideal_cursor_column).await?
|
||||
} else { String::new() /* Already handled */ }
|
||||
} else { // Form view
|
||||
form_e::execute_edit_action(action_str, key, form_state, ideal_cursor_column).await?
|
||||
};
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
}
|
||||
|
||||
// --- Character insertion ---
|
||||
// If character insertion happens while in suggestion mode, exit suggestion mode first.
|
||||
let mut exited_suggestion_mode_for_typing = false;
|
||||
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;
|
||||
exited_suggestion_mode_for_typing = true;
|
||||
}
|
||||
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;
|
||||
exited_suggestion_mode_for_typing = true;
|
||||
}
|
||||
|
||||
let msg = if app_state.ui.show_login {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
login_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
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 {
|
||||
add_table_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
&mut admin_state.add_table_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
add_table_e::execute_edit_action("insert_char", 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(
|
||||
"insert_char",
|
||||
key,
|
||||
&mut admin_state.add_logic_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
add_logic_e::execute_edit_action("insert_char", key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
|
||||
} else if app_state.ui.show_register {
|
||||
auth_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
register_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
form_e::execute_edit_action(
|
||||
"insert_char",
|
||||
key,
|
||||
form_state,
|
||||
ideal_cursor_column,
|
||||
)
|
||||
.await?
|
||||
auth_e::execute_edit_action("insert_char", key, register_state, ideal_cursor_column).await?
|
||||
} else { // Form view
|
||||
form_e::execute_edit_action("insert_char", key, form_state, ideal_cursor_column).await?
|
||||
};
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
return Ok(EditEventOutcome::Message(msg));
|
||||
if exited_suggestion_mode_for_typing && char_insert_msg.is_empty() {
|
||||
char_insert_msg = "Suggestions hidden".to_string();
|
||||
}
|
||||
|
||||
|
||||
Ok(EditEventOutcome::Message(char_insert_msg))
|
||||
}
|
||||
|
||||
@@ -161,6 +161,7 @@ impl EventHandler {
|
||||
return Ok(EventOutcome::Ok(message));
|
||||
}
|
||||
|
||||
|
||||
if !matches!(current_mode, AppMode::Edit | AppMode::Command) {
|
||||
if let Some(action) = config.get_action_for_key_in_mode(
|
||||
&config.keybindings.global, key_code, modifiers
|
||||
@@ -176,6 +177,10 @@ impl EventHandler {
|
||||
return Ok(EventOutcome::Ok("Switched to previous buffer".to_string()));
|
||||
}
|
||||
}
|
||||
"close_buffer" => {
|
||||
let message = buffer_state.close_buffer_with_intro_fallback();
|
||||
return Ok(EventOutcome::Ok(message));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@ use common::proto::multieko2::adresar::adresar_client::AdresarClient;
|
||||
use common::proto::multieko2::adresar::{AdresarResponse, PostAdresarRequest, PutAdresarRequest};
|
||||
use common::proto::multieko2::common::{CountResponse, PositionRequest, Empty};
|
||||
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
|
||||
use common::proto::multieko2::table_structure::TableStructureResponse;
|
||||
// Import the new request type for table structure
|
||||
use common::proto::multieko2::table_structure::{TableStructureResponse, GetTableStructureRequest};
|
||||
use common::proto::multieko2::table_definition::{
|
||||
table_definition_client::TableDefinitionClient,
|
||||
ProfileTreeResponse, PostTableDefinitionRequest, TableDefinitionResponse,
|
||||
@@ -63,9 +64,20 @@ impl GrpcClient {
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse> {
|
||||
let request = tonic::Request::new(Empty::default());
|
||||
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
|
||||
// Updated get_table_structure method
|
||||
pub async fn get_table_structure(
|
||||
&mut self,
|
||||
profile_name: String,
|
||||
table_name: String,
|
||||
) -> Result<TableStructureResponse> {
|
||||
// Create the new request type
|
||||
let grpc_request = GetTableStructureRequest {
|
||||
profile_name,
|
||||
table_name,
|
||||
};
|
||||
let request = tonic::Request::new(grpc_request);
|
||||
// Call the new gRPC method
|
||||
let response = self.table_structure_client.get_table_structure(request).await?;
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
|
||||
@@ -87,4 +99,3 @@ impl GrpcClient {
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,15 @@ impl UiService {
|
||||
let profile_tree = grpc_client.get_profile_tree().await.context("Failed to get profile tree")?;
|
||||
app_state.profile_tree = profile_tree;
|
||||
|
||||
// Fetch table structure
|
||||
let table_structure = grpc_client.get_table_structure().await?;
|
||||
// TODO for general tables and not hardcoded
|
||||
let default_profile_name = "default".to_string();
|
||||
let default_table_name = "2025_customer".to_string();
|
||||
|
||||
// Fetch table structure for the default table
|
||||
let table_structure = grpc_client
|
||||
.get_table_structure(default_profile_name, default_table_name)
|
||||
.await
|
||||
.context("Failed to get initial table structure")?;
|
||||
|
||||
// Extract the column names from the response
|
||||
let column_names: Vec<String> = table_structure
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// src/state/app/buffer.rs
|
||||
|
||||
/// Represents the distinct views or "buffers" the user can navigate.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AppView {
|
||||
Intro,
|
||||
@@ -14,7 +13,6 @@ pub enum AppView {
|
||||
}
|
||||
|
||||
impl AppView {
|
||||
/// Returns the display name for the view.
|
||||
pub fn display_name(&self) -> &str {
|
||||
match self {
|
||||
AppView::Intro => "Intro",
|
||||
@@ -29,7 +27,6 @@ impl AppView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the state related to buffer management (navigation history).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BufferState {
|
||||
pub history: Vec<AppView>,
|
||||
@@ -39,23 +36,17 @@ pub struct BufferState {
|
||||
impl Default for BufferState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
history: vec![AppView::Intro], // Start with Intro view
|
||||
history: vec![AppView::Intro],
|
||||
active_index: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferState {
|
||||
/// Updates the buffer history and active index.
|
||||
/// If the view already exists, it sets it as active.
|
||||
/// Otherwise, it adds the new view and makes it active.
|
||||
pub fn update_history(&mut self, view: AppView) {
|
||||
let existing_pos = self.history.iter().position(|v| v == &view);
|
||||
|
||||
match existing_pos {
|
||||
Some(pos) => {
|
||||
self.active_index = pos;
|
||||
}
|
||||
Some(pos) => self.active_index = pos,
|
||||
None => {
|
||||
self.history.push(view.clone());
|
||||
self.active_index = self.history.len() - 1;
|
||||
@@ -63,34 +54,51 @@ impl BufferState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the currently active view.
|
||||
pub fn get_active_view(&self) -> Option<&AppView> {
|
||||
self.history.get(self.active_index)
|
||||
}
|
||||
|
||||
/// Removes the currently active buffer from the history, unless it's the Intro buffer.
|
||||
/// Sets the new active buffer to the one preceding the closed one.
|
||||
/// # Returns
|
||||
/// * `true` if a non-Intro buffer was closed.
|
||||
/// * `false` if the active buffer was Intro or only Intro remained.
|
||||
pub fn close_active_buffer(&mut self) -> bool {
|
||||
let current_index = self.active_index;
|
||||
if self.history.is_empty() {
|
||||
self.history.push(AppView::Intro);
|
||||
self.active_index = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Rule 1: Cannot close Intro buffer.
|
||||
let current_index = self.active_index;
|
||||
if matches!(self.history.get(current_index), Some(AppView::Intro)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Rule 2: Cannot close if only Intro would remain (or already remains).
|
||||
// This check implicitly covers the case where len <= 1.
|
||||
if self.history.len() <= 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.history.remove(current_index);
|
||||
self.active_index = current_index.saturating_sub(1).min(self.history.len() - 1);
|
||||
|
||||
if self.history.is_empty() {
|
||||
self.history.push(AppView::Intro);
|
||||
self.active_index = 0;
|
||||
} else if self.active_index >= self.history.len() {
|
||||
self.active_index = self.history.len() - 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close_buffer_with_intro_fallback(&mut self) -> String {
|
||||
let current_view_cloned = self.get_active_view().cloned();
|
||||
if let Some(AppView::Intro) = current_view_cloned {
|
||||
return "Cannot close intro buffer".to_string();
|
||||
}
|
||||
|
||||
let closed_name = current_view_cloned
|
||||
.as_ref()
|
||||
.map(|v| v.display_name().to_string())
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
|
||||
if self.close_active_buffer() {
|
||||
if self.history.len() == 1 && matches!(self.history.get(0), Some(AppView::Intro)) {
|
||||
format!("Closed '{}' - returned to intro", closed_name)
|
||||
} else {
|
||||
format!("Closed '{}'", closed_name)
|
||||
}
|
||||
} else {
|
||||
format!("Cannot close buffer: {}", closed_name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/state/pages/add_logic.rs
|
||||
use crate::config::binds::config::{EditorConfig, EditorKeybindingMode};
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::components::common::text_editor::{TextEditor, VimState}; // Add VimState import
|
||||
use crate::components::common::text_editor::{TextEditor, VimState};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use tui_textarea::TextArea;
|
||||
@@ -11,8 +11,9 @@ pub enum AddLogicFocus {
|
||||
#[default]
|
||||
InputLogicName,
|
||||
InputTargetColumn,
|
||||
InputScriptContent,
|
||||
InputDescription,
|
||||
ScriptContentPreview,
|
||||
InsideScriptContent,
|
||||
SaveButton,
|
||||
CancelButton,
|
||||
}
|
||||
@@ -27,12 +28,20 @@ pub struct AddLogicState {
|
||||
pub script_content_editor: Rc<RefCell<TextArea<'static>>>,
|
||||
pub description_input: String,
|
||||
pub current_focus: AddLogicFocus,
|
||||
pub last_canvas_field: usize,
|
||||
pub logic_name_cursor_pos: usize,
|
||||
pub target_column_cursor_pos: usize,
|
||||
pub description_cursor_pos: usize,
|
||||
pub has_unsaved_changes: bool,
|
||||
pub editor_keybinding_mode: EditorKeybindingMode,
|
||||
pub vim_state: VimState, // Add this field
|
||||
pub vim_state: VimState,
|
||||
|
||||
// New fields for Target Column Autocomplete
|
||||
pub table_columns_for_suggestions: Vec<String>, // All columns for the table
|
||||
pub target_column_suggestions: Vec<String>, // Filtered suggestions
|
||||
pub show_target_column_suggestions: bool,
|
||||
pub selected_target_column_suggestion_index: Option<usize>,
|
||||
pub in_target_column_suggestion_mode: bool,
|
||||
}
|
||||
|
||||
impl AddLogicState {
|
||||
@@ -47,16 +56,64 @@ impl AddLogicState {
|
||||
script_content_editor: Rc::new(RefCell::new(editor)),
|
||||
description_input: String::new(),
|
||||
current_focus: AddLogicFocus::InputLogicName,
|
||||
last_canvas_field: 2,
|
||||
logic_name_cursor_pos: 0,
|
||||
target_column_cursor_pos: 0,
|
||||
description_cursor_pos: 0,
|
||||
has_unsaved_changes: false,
|
||||
editor_keybinding_mode: editor_config.keybinding_mode.clone(),
|
||||
vim_state: VimState::default(), // Add this field initialization
|
||||
vim_state: VimState::default(),
|
||||
|
||||
table_columns_for_suggestions: Vec::new(),
|
||||
target_column_suggestions: Vec::new(),
|
||||
show_target_column_suggestions: false,
|
||||
selected_target_column_suggestion_index: None,
|
||||
in_target_column_suggestion_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub const INPUT_FIELD_COUNT: usize = 3;
|
||||
|
||||
/// Updates the target_column_suggestions based on current input.
|
||||
pub fn update_target_column_suggestions(&mut self) {
|
||||
let current_input = self.target_column_input.to_lowercase();
|
||||
if self.table_columns_for_suggestions.is_empty() {
|
||||
self.target_column_suggestions.clear();
|
||||
self.show_target_column_suggestions = false;
|
||||
self.selected_target_column_suggestion_index = None;
|
||||
return;
|
||||
}
|
||||
|
||||
if current_input.is_empty() {
|
||||
self.target_column_suggestions = self.table_columns_for_suggestions.clone();
|
||||
} else {
|
||||
self.target_column_suggestions = self
|
||||
.table_columns_for_suggestions
|
||||
.iter()
|
||||
.filter(|name| name.to_lowercase().contains(¤t_input))
|
||||
.cloned()
|
||||
.collect();
|
||||
}
|
||||
|
||||
self.show_target_column_suggestions = !self.target_column_suggestions.is_empty();
|
||||
if self.show_target_column_suggestions {
|
||||
// If suggestions are shown, ensure a selection (usually the first)
|
||||
// or maintain current if it's still valid.
|
||||
if let Some(selected_idx) = self.selected_target_column_suggestion_index {
|
||||
if selected_idx >= self.target_column_suggestions.len() {
|
||||
self.selected_target_column_suggestion_index = Some(0);
|
||||
}
|
||||
// If the previously selected item is no longer in the filtered list, reset.
|
||||
// This is a bit more complex to check perfectly without iterating again.
|
||||
// For now, just ensuring it's within bounds is a good start.
|
||||
// A more robust way would be to check if the string at selected_idx still matches.
|
||||
} else {
|
||||
self.selected_target_column_suggestion_index = Some(0);
|
||||
}
|
||||
} else {
|
||||
self.selected_target_column_suggestion_index = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AddLogicState {
|
||||
@@ -65,14 +122,13 @@ impl Default for AddLogicState {
|
||||
}
|
||||
}
|
||||
|
||||
// ... rest of the CanvasState implementation remains the same
|
||||
impl CanvasState for AddLogicState {
|
||||
fn current_field(&self) -> usize {
|
||||
match self.current_focus {
|
||||
AddLogicFocus::InputLogicName => 0,
|
||||
AddLogicFocus::InputTargetColumn => 1,
|
||||
AddLogicFocus::InputDescription => 2,
|
||||
_ => 0,
|
||||
_ => self.last_canvas_field,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,12 +176,21 @@ impl CanvasState for AddLogicState {
|
||||
}
|
||||
|
||||
fn set_current_field(&mut self, index: usize) {
|
||||
self.current_focus = match index {
|
||||
let new_focus = match index {
|
||||
0 => AddLogicFocus::InputLogicName,
|
||||
1 => AddLogicFocus::InputTargetColumn,
|
||||
2 => AddLogicFocus::InputDescription,
|
||||
_ => self.current_focus,
|
||||
_ => return, // Or handle error/default
|
||||
};
|
||||
if self.current_focus != new_focus {
|
||||
// If changing field, exit suggestion mode for target column
|
||||
if self.current_focus == AddLogicFocus::InputTargetColumn {
|
||||
self.in_target_column_suggestion_mode = false;
|
||||
self.show_target_column_suggestions = false;
|
||||
}
|
||||
self.current_focus = new_focus;
|
||||
self.last_canvas_field = index;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_current_cursor_pos(&mut self, pos: usize) {
|
||||
@@ -150,10 +215,24 @@ impl CanvasState for AddLogicState {
|
||||
}
|
||||
|
||||
fn get_suggestions(&self) -> Option<&[String]> {
|
||||
None
|
||||
if self.current_field() == 1 // Target Column field index
|
||||
&& self.in_target_column_suggestion_mode
|
||||
&& self.show_target_column_suggestions
|
||||
{
|
||||
Some(&self.target_column_suggestions)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
||||
None
|
||||
if self.current_field() == 1 // Target Column field index
|
||||
&& self.in_target_column_suggestion_mode
|
||||
&& self.show_target_column_suggestions
|
||||
{
|
||||
self.selected_target_column_suggestion_index
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ pub struct AddTableState {
|
||||
pub indexes: Vec<IndexDefinition>,
|
||||
pub links: Vec<LinkDefinition>,
|
||||
pub current_focus: AddTableFocus,
|
||||
pub last_canvas_field: usize,
|
||||
pub column_table_state: TableState,
|
||||
pub index_table_state: TableState,
|
||||
pub link_table_state: TableState,
|
||||
@@ -77,6 +78,7 @@ impl Default for AddTableState {
|
||||
indexes: Vec::new(),
|
||||
links: Vec::new(),
|
||||
current_focus: AddTableFocus::InputTableName,
|
||||
last_canvas_field: 2,
|
||||
column_table_state: TableState::default(),
|
||||
index_table_state: TableState::default(),
|
||||
link_table_state: TableState::default(),
|
||||
@@ -100,7 +102,7 @@ impl CanvasState for AddTableState {
|
||||
AddTableFocus::InputColumnName => 1,
|
||||
AddTableFocus::InputColumnType => 2,
|
||||
// If focus is elsewhere, default to the first field for canvas rendering logic
|
||||
_ => 0,
|
||||
_ => self.last_canvas_field,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,10 +147,20 @@ impl CanvasState for AddTableState {
|
||||
}
|
||||
|
||||
fn set_current_field(&mut self, index: usize) {
|
||||
// Update both current focus and last canvas field
|
||||
self.current_focus = match index {
|
||||
0 => AddTableFocus::InputTableName,
|
||||
1 => AddTableFocus::InputColumnName,
|
||||
2 => AddTableFocus::InputColumnType,
|
||||
0 => {
|
||||
self.last_canvas_field = 0;
|
||||
AddTableFocus::InputTableName
|
||||
},
|
||||
1 => {
|
||||
self.last_canvas_field = 1;
|
||||
AddTableFocus::InputColumnName
|
||||
},
|
||||
2 => {
|
||||
self.last_canvas_field = 2;
|
||||
AddTableFocus::InputColumnType
|
||||
},
|
||||
_ => self.current_focus, // Stay on current focus if index is out of bounds
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::state::pages::add_logic::AddLogicState;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum AdminFocus {
|
||||
#[default] // Default focus is on the profiles list
|
||||
Profiles,
|
||||
ProfilesPane,
|
||||
InsideProfilesList,
|
||||
Tables,
|
||||
InsideTablesList,
|
||||
Button1,
|
||||
|
||||
@@ -2,5 +2,6 @@
|
||||
|
||||
pub mod form;
|
||||
pub mod login;
|
||||
pub mod logout;
|
||||
pub mod register;
|
||||
pub mod add_table;
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::state::pages::auth::AuthState;
|
||||
use crate::state::pages::auth::LoginState;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::state::app::buffer::{AppView, BufferState};
|
||||
use crate::config::storage::storage::{StoredAuthData, save_auth_data};
|
||||
use crate::state::pages::canvas_state::CanvasState;
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use common::proto::multieko2::auth::LoginResponse;
|
||||
@@ -200,6 +201,20 @@ pub fn handle_login_result(
|
||||
auth_state.role = Some(response.role.clone());
|
||||
auth_state.decoded_username = Some(response.username.clone());
|
||||
|
||||
// --- NEW: Save auth data to file ---
|
||||
let data_to_store = StoredAuthData {
|
||||
access_token: response.access_token.clone(),
|
||||
user_id: response.user_id.clone(),
|
||||
role: response.role.clone(),
|
||||
username: response.username.clone(),
|
||||
};
|
||||
|
||||
if let Err(e) = save_auth_data(&data_to_store) {
|
||||
error!("Failed to save auth data to file: {}", e);
|
||||
// Continue anyway - user is still logged in for this session
|
||||
}
|
||||
// --- END NEW ---
|
||||
|
||||
let success_message = format!(
|
||||
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
|
||||
response.username, response.user_id, response.role
|
||||
|
||||
47
client/src/tui/functions/common/logout.rs
Normal file
47
client/src/tui/functions/common/logout.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
// src/tui/functions/common/logout.rs
|
||||
use crate::config::storage::delete_auth_data;
|
||||
use crate::state::pages::auth::AuthState;
|
||||
use crate::state::app::state::AppState;
|
||||
use crate::state::app::buffer::{AppView, BufferState};
|
||||
use crate::ui::handlers::context::DialogPurpose;
|
||||
use tracing::{error, info};
|
||||
|
||||
pub fn logout(
|
||||
auth_state: &mut AuthState,
|
||||
app_state: &mut AppState,
|
||||
buffer_state: &mut BufferState,
|
||||
) -> String {
|
||||
// Clear auth state in memory
|
||||
auth_state.auth_token = None;
|
||||
auth_state.user_id = None;
|
||||
auth_state.role = None;
|
||||
auth_state.decoded_username = None;
|
||||
|
||||
// Delete stored auth data
|
||||
if let Err(e) = delete_auth_data() {
|
||||
error!("Failed to delete stored auth data: {}", e);
|
||||
// Continue anyway - user is logged out in memory
|
||||
}
|
||||
|
||||
// Navigate to intro screen
|
||||
buffer_state.history = vec![AppView::Intro];
|
||||
buffer_state.active_index = 0;
|
||||
|
||||
// Reset UI state
|
||||
app_state.ui.focus_outside_canvas = false;
|
||||
app_state.focused_button_index = 0;
|
||||
|
||||
// Hide any open dialogs
|
||||
app_state.hide_dialog();
|
||||
|
||||
// Show logout confirmation dialog
|
||||
app_state.show_dialog(
|
||||
"Logged Out",
|
||||
"You have been successfully logged out.",
|
||||
vec!["OK".to_string()],
|
||||
DialogPurpose::LoginSuccess, // Reuse or create a new purpose
|
||||
);
|
||||
|
||||
info!("User logged out successfully.");
|
||||
"Logged out successfully".to_string()
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use crate::config::binds::config::Config;
|
||||
use crate::config::colors::themes::Theme;
|
||||
use crate::services::grpc_client::GrpcClient;
|
||||
use crate::services::ui_service::UiService;
|
||||
use crate::config::storage::storage::load_auth_data;
|
||||
use crate::modes::common::commands::CommandHandler;
|
||||
use crate::modes::handlers::event::{EventHandler, EventOutcome};
|
||||
use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
|
||||
@@ -13,6 +14,7 @@ use crate::state::pages::auth::AuthState;
|
||||
use crate::state::pages::auth::LoginState;
|
||||
use crate::state::pages::auth::RegisterState;
|
||||
use crate::state::pages::admin::AdminState;
|
||||
use crate::state::pages::admin::AdminFocus;
|
||||
use crate::state::pages::intro::IntroState;
|
||||
use crate::state::app::buffer::BufferState;
|
||||
use crate::state::app::buffer::AppView;
|
||||
@@ -67,6 +69,28 @@ pub async fn run_ui() -> Result<()> {
|
||||
let mut buffer_state = BufferState::default();
|
||||
let mut app_state = AppState::new().context("Failed to create initial app state")?;
|
||||
|
||||
// --- DATA: Load auth data from file at startup ---
|
||||
let mut auto_logged_in = false;
|
||||
match load_auth_data() {
|
||||
Ok(Some(stored_data)) => {
|
||||
// TODO: Optionally validate token with server here
|
||||
// For now, assume valid if successfully loaded
|
||||
auth_state.auth_token = Some(stored_data.access_token);
|
||||
auth_state.user_id = Some(stored_data.user_id);
|
||||
auth_state.role = Some(stored_data.role);
|
||||
auth_state.decoded_username = Some(stored_data.username);
|
||||
auto_logged_in = true;
|
||||
info!("Auth data loaded from file. User is auto-logged in.");
|
||||
}
|
||||
Ok(None) => {
|
||||
info!("No stored auth data found. User will see intro/login.");
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to load auth data: {}", e);
|
||||
}
|
||||
}
|
||||
// --- END DATA ---
|
||||
|
||||
// Initialize app state with profile tree and table structure
|
||||
let column_names =
|
||||
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
||||
@@ -77,6 +101,16 @@ pub async fn run_ui() -> Result<()> {
|
||||
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
|
||||
form_state.reset_to_empty();
|
||||
|
||||
// --- DATA2: Adjust initial view based on auth status ---
|
||||
if auto_logged_in {
|
||||
// User is auto-logged in, go to main app view
|
||||
buffer_state.history = vec![AppView::Form("Adresar".to_string())];
|
||||
buffer_state.active_index = 0;
|
||||
info!("Initial view set to Form due to auto-login.");
|
||||
}
|
||||
// If not auto-logged in, BufferState default (Intro) will be used
|
||||
// --- END DATA2 ---
|
||||
|
||||
// --- FPS Calculation State ---
|
||||
let mut last_frame_time = Instant::now();
|
||||
let mut current_fps = 0.0;
|
||||
@@ -108,11 +142,24 @@ pub async fn run_ui() -> Result<()> {
|
||||
event_handler.command_message = format!("Error refreshing admin data: {}", e);
|
||||
}
|
||||
}
|
||||
app_state.ui.show_admin = true;
|
||||
let profile_names = app_state.profile_tree.profiles.iter()
|
||||
.map(|p| p.name.clone())
|
||||
.collect();
|
||||
app_state.ui.show_admin = true; // <<< RESTORE THIS
|
||||
let profile_names = app_state.profile_tree.profiles.iter() // <<< RESTORE THIS
|
||||
.map(|p| p.name.clone()) // <<< RESTORE THIS
|
||||
.collect(); // <<< RESTORE THIS
|
||||
admin_state.set_profiles(profile_names);
|
||||
|
||||
// Only reset to ProfilesPane if not already in a specific admin sub-focus
|
||||
if admin_state.current_focus == AdminFocus::default() ||
|
||||
!matches!(admin_state.current_focus,
|
||||
AdminFocus::InsideProfilesList |
|
||||
AdminFocus::Tables | AdminFocus::InsideTablesList |
|
||||
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3) {
|
||||
admin_state.current_focus = AdminFocus::ProfilesPane;
|
||||
}
|
||||
// Pre-select first profile item for visual consistency, but '>' won't show until 'select'
|
||||
if admin_state.profile_list_state.selected().is_none() && !app_state.profile_tree.profiles.is_empty() {
|
||||
admin_state.profile_list_state.select(Some(0));
|
||||
}
|
||||
}
|
||||
AppView::AddTable => app_state.ui.show_add_table = true,
|
||||
AppView::AddLogic => app_state.ui.show_add_logic = true,
|
||||
|
||||
@@ -4,18 +4,22 @@ package multieko2.table_structure;
|
||||
|
||||
import "common.proto";
|
||||
|
||||
message GetTableStructureRequest {
|
||||
string profile_name = 1; // e.g., "default"
|
||||
string table_name = 2; // e.g., "2025_adresar6"
|
||||
}
|
||||
|
||||
message TableStructureResponse {
|
||||
repeated TableColumn columns = 1;
|
||||
}
|
||||
|
||||
message TableColumn {
|
||||
string name = 1;
|
||||
string data_type = 2;
|
||||
string data_type = 2; // e.g., "TEXT", "BIGINT", "VARCHAR(255)", "TIMESTAMPTZ"
|
||||
bool is_nullable = 3;
|
||||
bool is_primary_key = 4;
|
||||
}
|
||||
|
||||
service TableStructureService {
|
||||
rpc GetAdresarTableStructure (common.Empty) returns (TableStructureResponse);
|
||||
rpc GetUctovnictvoTableStructure (common.Empty) returns (TableStructureResponse);
|
||||
rpc GetTableStructure (GetTableStructureRequest) returns (TableStructureResponse);
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,5 +1,14 @@
|
||||
// This file is @generated by prost-build.
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct GetTableStructureRequest {
|
||||
/// e.g., "default"
|
||||
#[prost(string, tag = "1")]
|
||||
pub profile_name: ::prost::alloc::string::String,
|
||||
/// e.g., "2025_adresar6"
|
||||
#[prost(string, tag = "2")]
|
||||
pub table_name: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct TableStructureResponse {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub columns: ::prost::alloc::vec::Vec<TableColumn>,
|
||||
@@ -8,6 +17,7 @@ pub struct TableStructureResponse {
|
||||
pub struct TableColumn {
|
||||
#[prost(string, tag = "1")]
|
||||
pub name: ::prost::alloc::string::String,
|
||||
/// e.g., "TEXT", "BIGINT", "VARCHAR(255)", "TIMESTAMPTZ"
|
||||
#[prost(string, tag = "2")]
|
||||
pub data_type: ::prost::alloc::string::String,
|
||||
#[prost(bool, tag = "3")]
|
||||
@@ -106,9 +116,9 @@ pub mod table_structure_service_client {
|
||||
self.inner = self.inner.max_encoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
pub async fn get_adresar_table_structure(
|
||||
pub async fn get_table_structure(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::super::common::Empty>,
|
||||
request: impl tonic::IntoRequest<super::GetTableStructureRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<super::TableStructureResponse>,
|
||||
tonic::Status,
|
||||
@@ -123,43 +133,14 @@ pub mod table_structure_service_client {
|
||||
})?;
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/multieko2.table_structure.TableStructureService/GetAdresarTableStructure",
|
||||
"/multieko2.table_structure.TableStructureService/GetTableStructure",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut()
|
||||
.insert(
|
||||
GrpcMethod::new(
|
||||
"multieko2.table_structure.TableStructureService",
|
||||
"GetAdresarTableStructure",
|
||||
),
|
||||
);
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
pub async fn get_uctovnictvo_table_structure(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::super::common::Empty>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<super::TableStructureResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
self.inner
|
||||
.ready()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tonic::Status::unknown(
|
||||
format!("Service was not ready: {}", e.into()),
|
||||
)
|
||||
})?;
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/multieko2.table_structure.TableStructureService/GetUctovnictvoTableStructure",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut()
|
||||
.insert(
|
||||
GrpcMethod::new(
|
||||
"multieko2.table_structure.TableStructureService",
|
||||
"GetUctovnictvoTableStructure",
|
||||
"GetTableStructure",
|
||||
),
|
||||
);
|
||||
self.inner.unary(req, path, codec).await
|
||||
@@ -179,16 +160,9 @@ pub mod table_structure_service_server {
|
||||
/// Generated trait containing gRPC methods that should be implemented for use with TableStructureServiceServer.
|
||||
#[async_trait]
|
||||
pub trait TableStructureService: std::marker::Send + std::marker::Sync + 'static {
|
||||
async fn get_adresar_table_structure(
|
||||
async fn get_table_structure(
|
||||
&self,
|
||||
request: tonic::Request<super::super::common::Empty>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<super::TableStructureResponse>,
|
||||
tonic::Status,
|
||||
>;
|
||||
async fn get_uctovnictvo_table_structure(
|
||||
&self,
|
||||
request: tonic::Request<super::super::common::Empty>,
|
||||
request: tonic::Request<super::GetTableStructureRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<super::TableStructureResponse>,
|
||||
tonic::Status,
|
||||
@@ -271,15 +245,13 @@ pub mod table_structure_service_server {
|
||||
}
|
||||
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||
match req.uri().path() {
|
||||
"/multieko2.table_structure.TableStructureService/GetAdresarTableStructure" => {
|
||||
"/multieko2.table_structure.TableStructureService/GetTableStructure" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct GetAdresarTableStructureSvc<T: TableStructureService>(
|
||||
pub Arc<T>,
|
||||
);
|
||||
struct GetTableStructureSvc<T: TableStructureService>(pub Arc<T>);
|
||||
impl<
|
||||
T: TableStructureService,
|
||||
> tonic::server::UnaryService<super::super::common::Empty>
|
||||
for GetAdresarTableStructureSvc<T> {
|
||||
> tonic::server::UnaryService<super::GetTableStructureRequest>
|
||||
for GetTableStructureSvc<T> {
|
||||
type Response = super::TableStructureResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
@@ -287,11 +259,11 @@ pub mod table_structure_service_server {
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::super::common::Empty>,
|
||||
request: tonic::Request<super::GetTableStructureRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as TableStructureService>::get_adresar_table_structure(
|
||||
<T as TableStructureService>::get_table_structure(
|
||||
&inner,
|
||||
request,
|
||||
)
|
||||
@@ -306,58 +278,7 @@ pub mod table_structure_service_server {
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = GetAdresarTableStructureSvc(inner);
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
"/multieko2.table_structure.TableStructureService/GetUctovnictvoTableStructure" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct GetUctovnictvoTableStructureSvc<T: TableStructureService>(
|
||||
pub Arc<T>,
|
||||
);
|
||||
impl<
|
||||
T: TableStructureService,
|
||||
> tonic::server::UnaryService<super::super::common::Empty>
|
||||
for GetUctovnictvoTableStructureSvc<T> {
|
||||
type Response = super::TableStructureResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
tonic::Status,
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::super::common::Empty>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as TableStructureService>::get_uctovnictvo_table_structure(
|
||||
&inner,
|
||||
request,
|
||||
)
|
||||
.await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = GetUctovnictvoTableStructureSvc(inner);
|
||||
let method = GetTableStructureSvc(inner);
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// src/server/services/table_structure_service.rs
|
||||
use tonic::{Request, Response, Status};
|
||||
// Correct the import path for the TableStructureService trait
|
||||
use common::proto::multieko2::table_structure::table_structure_service_server::TableStructureService;
|
||||
use common::proto::multieko2::table_structure::TableStructureResponse;
|
||||
use common::proto::multieko2::common::Empty;
|
||||
use crate::table_structure::handlers::{
|
||||
get_adresar_table_structure, get_uctovnictvo_table_structure,
|
||||
use common::proto::multieko2::table_structure::{
|
||||
GetTableStructureRequest,
|
||||
TableStructureResponse,
|
||||
};
|
||||
use crate::table_structure::handlers::get_table_structure;
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -13,22 +14,21 @@ pub struct TableStructureHandler {
|
||||
pub db_pool: PgPool,
|
||||
}
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl TableStructureService for TableStructureHandler {
|
||||
async fn get_adresar_table_structure(
|
||||
&self,
|
||||
request: Request<Empty>,
|
||||
) -> Result<Response<TableStructureResponse>, Status> {
|
||||
let response = get_adresar_table_structure(&self.db_pool, request.into_inner())
|
||||
.await?;
|
||||
Ok(Response::new(response))
|
||||
impl TableStructureHandler {
|
||||
pub fn new(db_pool: PgPool) -> Self {
|
||||
Self { db_pool }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_uctovnictvo_table_structure(
|
||||
#[tonic::async_trait]
|
||||
impl TableStructureService for TableStructureHandler { // This line should now be correct
|
||||
async fn get_table_structure(
|
||||
&self,
|
||||
request: Request<Empty>,
|
||||
request: Request<GetTableStructureRequest>,
|
||||
) -> Result<Response<TableStructureResponse>, Status> {
|
||||
let response = get_uctovnictvo_table_structure(&self.db_pool, request.into_inner()).await?;
|
||||
let req_payload = request.into_inner();
|
||||
let response =
|
||||
get_table_structure(&self.db_pool, req_payload).await?;
|
||||
Ok(Response::new(response))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,83 +1,39 @@
|
||||
Adresar response:
|
||||
❯ grpcurl -plaintext \
|
||||
-proto proto/table_structure.proto \
|
||||
-import-path proto \
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"profile_name": "default",
|
||||
"table_name": "2025_customer"
|
||||
}' \
|
||||
localhost:50051 \
|
||||
multieko2.table_structure.TableStructureService/GetAdresarTableStructure
|
||||
multieko2.table_structure.TableStructureService/GetTableStructure
|
||||
{
|
||||
"columns": [
|
||||
{
|
||||
"name": "firma",
|
||||
"dataType": "TEXT"
|
||||
"name": "id",
|
||||
"dataType": "INT8",
|
||||
"isPrimaryKey": true
|
||||
},
|
||||
{
|
||||
"name": "kz",
|
||||
"name": "deleted",
|
||||
"dataType": "BOOL"
|
||||
},
|
||||
{
|
||||
"name": "full_name",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "drc",
|
||||
"dataType": "TEXT",
|
||||
"name": "email",
|
||||
"dataType": "VARCHAR(255)",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "ulica",
|
||||
"dataType": "TEXT",
|
||||
"name": "loyalty_status",
|
||||
"dataType": "BOOL",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "psc",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "mesto",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "stat",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "banka",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "ucet",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "skladm",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "ico",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "kontakt",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "telefon",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "skladu",
|
||||
"dataType": "TEXT",
|
||||
"isNullable": true
|
||||
},
|
||||
{
|
||||
"name": "fax",
|
||||
"dataType": "TEXT",
|
||||
"name": "created_at",
|
||||
"dataType": "TIMESTAMPTZ",
|
||||
"isNullable": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// src/table_structure/handlers.rs
|
||||
pub mod table_structure;
|
||||
|
||||
pub use table_structure::{get_adresar_table_structure, get_uctovnictvo_table_structure};
|
||||
pub use table_structure::get_table_structure;
|
||||
|
||||
@@ -1,181 +1,134 @@
|
||||
// src/table_structure/handlers/table_structure.rs
|
||||
use tonic::Status;
|
||||
use sqlx::PgPool;
|
||||
use common::proto::multieko2::{
|
||||
table_structure::{TableStructureResponse, TableColumn},
|
||||
common::Empty
|
||||
use common::proto::multieko2::table_structure::{
|
||||
GetTableStructureRequest, TableColumn, TableStructureResponse,
|
||||
};
|
||||
use sqlx::{PgPool, Row};
|
||||
use tonic::Status;
|
||||
|
||||
pub async fn get_adresar_table_structure(
|
||||
_db_pool: &PgPool,
|
||||
_request: Empty,
|
||||
) -> Result<TableStructureResponse, Status> {
|
||||
let columns = vec![
|
||||
TableColumn {
|
||||
name: "firma".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "kz".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "drc".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "ulica".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "psc".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "mesto".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "stat".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "banka".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "ucet".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "skladm".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "ico".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "kontakt".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "telefon".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "skladu".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "fax".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
];
|
||||
Ok(TableStructureResponse { columns })
|
||||
// Helper struct to map query results
|
||||
#[derive(sqlx::FromRow, Debug)]
|
||||
struct DbColumnInfo {
|
||||
column_name: String,
|
||||
formatted_data_type: String,
|
||||
is_nullable: bool,
|
||||
is_primary_key: bool,
|
||||
}
|
||||
|
||||
pub async fn get_uctovnictvo_table_structure(
|
||||
_db_pool: &PgPool,
|
||||
_request: Empty,
|
||||
pub async fn get_table_structure(
|
||||
db_pool: &PgPool,
|
||||
request: GetTableStructureRequest,
|
||||
) -> Result<TableStructureResponse, Status> {
|
||||
let columns = vec![
|
||||
TableColumn {
|
||||
name: "adresar_id".to_string(),
|
||||
data_type: "BIGINT".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "c_dokladu".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "datum".to_string(),
|
||||
data_type: "DATE".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "c_faktury".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "obsah".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "stredisko".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "c_uctu".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "md".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "identif".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "poznanka".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: true,
|
||||
is_primary_key: false,
|
||||
},
|
||||
TableColumn {
|
||||
name: "firma".to_string(),
|
||||
data_type: "TEXT".to_string(),
|
||||
is_nullable: false,
|
||||
is_primary_key: false,
|
||||
},
|
||||
];
|
||||
let profile_name = request.profile_name;
|
||||
let table_name = request.table_name; // This should be the full table name, e.g., "2025_adresar6"
|
||||
let table_schema = "public"; // Assuming tables are in the 'public' schema
|
||||
|
||||
// 1. Validate Profile
|
||||
let profile = sqlx::query!(
|
||||
"SELECT id FROM profiles WHERE name = $1",
|
||||
profile_name
|
||||
)
|
||||
.fetch_optional(db_pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"Failed to query profile '{}': {}",
|
||||
profile_name, e
|
||||
))
|
||||
})?;
|
||||
|
||||
let profile_id = match profile {
|
||||
Some(p) => p.id,
|
||||
None => {
|
||||
return Err(Status::not_found(format!(
|
||||
"Profile '{}' not found",
|
||||
profile_name
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Validate Table within Profile
|
||||
sqlx::query!(
|
||||
"SELECT id FROM table_definitions WHERE profile_id = $1 AND table_name = $2",
|
||||
profile_id,
|
||||
table_name
|
||||
)
|
||||
.fetch_optional(db_pool)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("Failed to query table_definitions: {}", e)))?
|
||||
.ok_or_else(|| Status::not_found(format!(
|
||||
"Table '{}' not found in profile '{}'",
|
||||
table_name,
|
||||
profile_name
|
||||
)))?;
|
||||
|
||||
// 3. Query information_schema for column details
|
||||
let query_str = r#"
|
||||
SELECT
|
||||
c.column_name,
|
||||
CASE
|
||||
WHEN c.udt_name = 'varchar' AND c.character_maximum_length IS NOT NULL THEN
|
||||
'VARCHAR(' || c.character_maximum_length || ')'
|
||||
WHEN c.udt_name = 'bpchar' AND c.character_maximum_length IS NOT NULL THEN
|
||||
'CHAR(' || c.character_maximum_length || ')'
|
||||
WHEN c.udt_name = 'numeric' AND c.numeric_precision IS NOT NULL AND c.numeric_scale IS NOT NULL THEN
|
||||
'NUMERIC(' || c.numeric_precision || ',' || c.numeric_scale || ')'
|
||||
WHEN c.udt_name = 'numeric' AND c.numeric_precision IS NOT NULL THEN
|
||||
'NUMERIC(' || c.numeric_precision || ')'
|
||||
WHEN STARTS_WITH(c.udt_name, '_') THEN
|
||||
UPPER(SUBSTRING(c.udt_name FROM 2)) || '[]'
|
||||
ELSE
|
||||
UPPER(c.udt_name)
|
||||
END AS formatted_data_type,
|
||||
c.is_nullable = 'YES' AS is_nullable,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.key_column_usage kcu
|
||||
JOIN information_schema.table_constraints tc
|
||||
ON kcu.constraint_name = tc.constraint_name
|
||||
AND kcu.table_schema = tc.table_schema
|
||||
AND kcu.table_name = tc.table_name
|
||||
WHERE tc.table_schema = c.table_schema
|
||||
AND tc.table_name = c.table_name
|
||||
AND tc.constraint_type = 'PRIMARY KEY'
|
||||
AND kcu.column_name = c.column_name
|
||||
) AS is_primary_key
|
||||
FROM
|
||||
information_schema.columns c
|
||||
WHERE
|
||||
c.table_schema = $1
|
||||
AND c.table_name = $2
|
||||
ORDER BY
|
||||
c.ordinal_position;
|
||||
"#;
|
||||
|
||||
let db_columns = sqlx::query_as::<_, DbColumnInfo>(query_str)
|
||||
.bind(table_schema)
|
||||
.bind(&table_name) // Use the validated table_name
|
||||
.fetch_all(db_pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"Failed to query column information for table '{}': {}",
|
||||
table_name, e
|
||||
))
|
||||
})?;
|
||||
|
||||
if db_columns.is_empty() {
|
||||
// This could mean the table exists in table_definitions but not in information_schema,
|
||||
// or it has no columns. The latter is unlikely for a created table.
|
||||
// Depending on desired behavior, you could return an error or an empty list.
|
||||
// For now, returning an empty list if the table was validated.
|
||||
}
|
||||
|
||||
let columns = db_columns
|
||||
.into_iter()
|
||||
.map(|db_col| TableColumn {
|
||||
name: db_col.column_name,
|
||||
data_type: db_col.formatted_data_type,
|
||||
is_nullable: db_col.is_nullable,
|
||||
is_primary_key: db_col.is_primary_key,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(TableStructureResponse { columns })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user