Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ff9399b81 | ||
|
|
d18f7862ab | ||
|
|
dc6c1ce43c | ||
|
|
8d1adccec6 | ||
|
|
420ce71fb2 | ||
|
|
8e5a269ff0 | ||
|
|
f357d6f0ee | ||
|
|
a0467d17a8 | ||
|
|
ef3ecfc73f | ||
|
|
d3fcb23e22 | ||
|
|
5a029283a1 | ||
|
|
09ccad2bd4 | ||
|
|
bdcc10bd40 | ||
|
|
2a1fafc3f9 | ||
|
|
6010b9a0af | ||
|
|
11e8f87fe6 | ||
|
|
14b81cba19 | ||
|
|
2b37de3b4d | ||
|
|
73d9a6367c | ||
|
|
c90233b56f | ||
|
|
39dcf38462 | ||
|
|
efa27cd2dd | ||
|
|
ca231964f2 | ||
|
|
2bb83cb990 | ||
|
|
305bcfcf62 | ||
|
|
92a9011f27 | ||
|
|
e64cebdfc2 | ||
|
|
0db426d278 | ||
|
|
6bfef1c7a0 | ||
|
|
f50fe788cb | ||
|
|
4db78ecf1b | ||
|
|
f22dd7749f | ||
|
|
75af0c3be1 | ||
|
|
6f36b84f85 | ||
|
|
e723198b72 | ||
|
|
8f74febff1 | ||
|
|
d9bd6f8e1d | ||
|
|
bf55417901 | ||
|
|
9511970a1a | ||
|
|
5c8557b369 | ||
|
|
5e47c53fcf | ||
|
|
f7493a8bc4 | ||
|
|
4f39b93edd | ||
|
|
ff8b4eb0f6 | ||
|
|
e921862a7f | ||
|
|
4d7177f15a | ||
|
|
c5d7f56399 |
9
Cargo.lock
generated
9
Cargo.lock
generated
@@ -109,9 +109,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.97"
|
version = "1.0.98"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
|
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "arc-swap"
|
name = "arc-swap"
|
||||||
@@ -423,6 +423,7 @@ dependencies = [
|
|||||||
name = "client"
|
name = "client"
|
||||||
version = "0.3.13"
|
version = "0.3.13"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"common",
|
"common",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
@@ -1656,9 +1657,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "log"
|
name = "log"
|
||||||
version = "0.4.26"
|
version = "0.4.27"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"
|
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lru"
|
name = "lru"
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
anyhow = "1.0.98"
|
||||||
async-trait = "0.1.88"
|
async-trait = "0.1.88"
|
||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ toggle_sidebar = ["ctrl+t"]
|
|||||||
toggle_buffer_list = ["ctrl+b"]
|
toggle_buffer_list = ["ctrl+b"]
|
||||||
next_field = ["Tab"]
|
next_field = ["Tab"]
|
||||||
prev_field = ["Shift+Tab"]
|
prev_field = ["Shift+Tab"]
|
||||||
|
exit_table_scroll = ["esc"]
|
||||||
|
|
||||||
[keybindings.common]
|
[keybindings.common]
|
||||||
save = ["ctrl+s"]
|
save = ["ctrl+s"]
|
||||||
@@ -60,16 +61,17 @@ enter_highlight_mode_linewise = ["ctrl+v"]
|
|||||||
# BIG CHANGES NOW EXIT HANDLES EITHER IF THOSE
|
# BIG CHANGES NOW EXIT HANDLES EITHER IF THOSE
|
||||||
# exit_edit_mode = ["esc","ctrl+e"]
|
# exit_edit_mode = ["esc","ctrl+e"]
|
||||||
# exit_suggestion_mode = ["esc"]
|
# exit_suggestion_mode = ["esc"]
|
||||||
|
# select_suggestion = ["enter"]
|
||||||
|
# next_field = ["enter"]
|
||||||
|
enter_decider = ["enter"]
|
||||||
|
prev_field = ["shift+enter"]
|
||||||
exit = ["esc", "ctrl+e"]
|
exit = ["esc", "ctrl+e"]
|
||||||
delete_char_forward = ["delete"]
|
delete_char_forward = ["delete"]
|
||||||
delete_char_backward = ["backspace"]
|
delete_char_backward = ["backspace"]
|
||||||
next_field = ["enter"]
|
|
||||||
prev_field = ["shift+enter"]
|
|
||||||
move_left = ["left"]
|
move_left = ["left"]
|
||||||
move_right = ["right"]
|
move_right = ["right"]
|
||||||
suggestion_down = ["ctrl+n", "tab"]
|
suggestion_down = ["ctrl+n", "tab"]
|
||||||
suggestion_up = ["ctrl+p", "shift+tab"]
|
suggestion_up = ["ctrl+p", "shift+tab"]
|
||||||
select_suggestion = ["enter"]
|
|
||||||
|
|
||||||
[keybindings.command]
|
[keybindings.command]
|
||||||
exit_command_mode = ["ctrl+g", "esc"]
|
exit_command_mode = ["ctrl+g", "esc"]
|
||||||
|
|||||||
@@ -1,31 +1,47 @@
|
|||||||
// src/components/admin/add_table.rs
|
// src/components/admin/add_table.rs
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::app::highlight::HighlightState;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
|
use crate::state::pages::add_table::{AddTableFocus, AddTableState};
|
||||||
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
|
// use crate::state::pages::add_table::{ColumnDefinition, LinkDefinition}; // Not directly used here
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::{Style, Stylize},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, BorderType, Borders, Paragraph},
|
widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table},
|
||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
use crate::state::app::state::AppState;
|
|
||||||
use crate::state::app::highlight::HighlightState;
|
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
|
||||||
use crate::components::handlers::canvas::render_canvas;
|
use crate::components::handlers::canvas::render_canvas;
|
||||||
use crate::state::pages::add_table::AddTableState;
|
use crate::components::common::dialog;
|
||||||
|
|
||||||
/// Renders a placeholder page for adding tables.
|
/// Renders the Add New Table page layout, structuring the display of table information,
|
||||||
|
/// input fields, and action buttons. Adapts layout based on terminal width.
|
||||||
pub fn render_add_table(
|
pub fn render_add_table(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
_app_state: &AppState,
|
app_state: &AppState, // Currently unused, might be needed later
|
||||||
add_table_state: &mut AddTableState,
|
add_table_state: &mut AddTableState,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool, // Determines if canvas inputs are in edit mode
|
||||||
highlight_state: &HighlightState,
|
highlight_state: &HighlightState, // For text highlighting in canvas
|
||||||
) {
|
) {
|
||||||
// Main block for the whole page
|
// --- Configuration ---
|
||||||
|
// Threshold width to switch between wide and narrow layouts
|
||||||
|
const NARROW_LAYOUT_THRESHOLD: u16 = 120; // Adjust this value as needed
|
||||||
|
|
||||||
|
// --- State Checks ---
|
||||||
|
let focus_on_canvas_inputs = matches!(
|
||||||
|
add_table_state.current_focus,
|
||||||
|
AddTableFocus::InputTableName
|
||||||
|
| AddTableFocus::InputColumnName
|
||||||
|
| AddTableFocus::InputColumnType
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Main Page Block ---
|
||||||
let main_block = Block::default()
|
let main_block = Block::default()
|
||||||
.title(" Add New Table ")
|
.title(" Add New Table ")
|
||||||
|
.title_alignment(Alignment::Center)
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.border_style(Style::default().fg(theme.border))
|
.border_style(Style::default().fg(theme.border))
|
||||||
@@ -33,148 +49,450 @@ pub fn render_add_table(
|
|||||||
let inner_area = main_block.inner(area);
|
let inner_area = main_block.inner(area);
|
||||||
f.render_widget(main_block, area);
|
f.render_widget(main_block, area);
|
||||||
|
|
||||||
// Split the inner area horizontally: Left info pane | Right input/action pane
|
// --- Fullscreen Columns Table Check (Narrow Screens Only) ---
|
||||||
let horizontal_chunks = Layout::default()
|
if area.width < NARROW_LAYOUT_THRESHOLD && add_table_state.current_focus == AddTableFocus::InsideColumnsTable {
|
||||||
.direction(Direction::Horizontal)
|
// Render ONLY the columns table taking the full inner area
|
||||||
.constraints([
|
let columns_border_style = Style::default().fg(theme.highlight); // Always highlighted when fullscreen
|
||||||
Constraint::Percentage(50), // Left Pane
|
let column_rows: Vec<Row<'_>> = add_table_state
|
||||||
Constraint::Percentage(50), // Right Pane
|
.columns
|
||||||
].as_ref())
|
.iter()
|
||||||
.split(inner_area);
|
.map(|col_def| {
|
||||||
|
Row::new(vec![
|
||||||
|
Cell::from(if col_def.selected { "[*]" } else { "[ ]" }),
|
||||||
|
Cell::from(col_def.name.clone()),
|
||||||
|
Cell::from(col_def.data_type.clone()),
|
||||||
|
])
|
||||||
|
.style(Style::default().fg(theme.fg))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let header_cells = ["Sel", "Name", "Type"]
|
||||||
|
.iter()
|
||||||
|
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||||
|
let header = Row::new(header_cells).height(1).bottom_margin(1);
|
||||||
|
let columns_table = Table::new(column_rows, [Constraint::Length(5), Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||||
|
.header(header)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.title(Span::styled(" Columns (Fullscreen) ", theme.fg)) // Indicate fullscreen
|
||||||
|
.title_alignment(Alignment::Center)
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(columns_border_style),
|
||||||
|
)
|
||||||
|
.row_highlight_style(
|
||||||
|
Style::default()
|
||||||
|
.add_modifier(Modifier::REVERSED)
|
||||||
|
.fg(theme.highlight),
|
||||||
|
)
|
||||||
|
.highlight_symbol(" > "); // Use the inside symbol
|
||||||
|
f.render_stateful_widget(columns_table, inner_area, &mut add_table_state.column_table_state);
|
||||||
|
return; // IMPORTANT: Stop rendering here for fullscreen mode
|
||||||
|
}
|
||||||
|
|
||||||
let left_pane = horizontal_chunks[0];
|
// --- Area Variable Declarations ---
|
||||||
let right_pane = horizontal_chunks[1];
|
let top_info_area: Rect;
|
||||||
|
let columns_area: Rect;
|
||||||
|
let canvas_area: Rect;
|
||||||
|
let add_button_area: Rect;
|
||||||
|
let indexes_area: Rect;
|
||||||
|
let links_area: Rect;
|
||||||
|
let bottom_buttons_area: Rect;
|
||||||
|
|
||||||
// --- Left Pane ---
|
// --- Layout Decision ---
|
||||||
let left_vertical_chunks = Layout::default()
|
if area.width >= NARROW_LAYOUT_THRESHOLD {
|
||||||
.direction(Direction::Vertical)
|
// --- WIDE Layout (Based on first screenshot) ---
|
||||||
.constraints([
|
let main_chunks = Layout::default()
|
||||||
Constraint::Length(3), // Profile & Table Name header
|
.direction(Direction::Vertical)
|
||||||
Constraint::Min(5), // Columns section (expandable)
|
.constraints([
|
||||||
Constraint::Length(1), // Separator
|
Constraint::Length(3), // Top Info (Profile/Table Name) - Increased to 3 lines
|
||||||
Constraint::Min(3), // Indexes section (expandable)
|
Constraint::Min(10), // Middle Area (Columns | Right Pane)
|
||||||
Constraint::Length(1), // Separator
|
Constraint::Length(3), // Bottom Buttons
|
||||||
Constraint::Min(3), // Links section (expandable)
|
])
|
||||||
].as_ref())
|
.split(inner_area);
|
||||||
.split(left_pane);
|
|
||||||
|
|
||||||
// Profile & Table Name section
|
top_info_area = main_chunks[0];
|
||||||
let profile_text = Paragraph::new(vec![
|
let middle_area = main_chunks[1];
|
||||||
Line::from(Span::styled("profile: default", theme.fg)), // Placeholder
|
bottom_buttons_area = main_chunks[2];
|
||||||
Line::from(Span::styled("table name: [tablename]", theme.fg)), // Placeholder
|
|
||||||
])
|
// Split Middle Horizontally
|
||||||
|
let middle_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(50), // Left: Columns Table
|
||||||
|
Constraint::Percentage(50), // Right: Inputs etc.
|
||||||
|
])
|
||||||
|
.split(middle_area);
|
||||||
|
|
||||||
|
columns_area = middle_chunks[0];
|
||||||
|
let right_pane_area = middle_chunks[1];
|
||||||
|
|
||||||
|
// Split Right Pane Vertically
|
||||||
|
let right_pane_chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(5), // Input Canvas Area
|
||||||
|
Constraint::Length(3), // Add Button Area
|
||||||
|
Constraint::Min(5), // Indexes & Links Area
|
||||||
|
])
|
||||||
|
.split(right_pane_area);
|
||||||
|
|
||||||
|
canvas_area = right_pane_chunks[0];
|
||||||
|
add_button_area = right_pane_chunks[1];
|
||||||
|
let indexes_links_area = right_pane_chunks[2];
|
||||||
|
|
||||||
|
// Split Indexes/Links Horizontally
|
||||||
|
let indexes_links_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(50), // Indexes Table
|
||||||
|
Constraint::Percentage(50), // Links Table
|
||||||
|
])
|
||||||
|
.split(indexes_links_area);
|
||||||
|
indexes_area = indexes_links_chunks[0];
|
||||||
|
links_area = indexes_links_chunks[1];
|
||||||
|
|
||||||
|
// --- Top Info Rendering (Wide - 2 lines) ---
|
||||||
|
let profile_text = Paragraph::new(vec![
|
||||||
|
Line::from(Span::styled(
|
||||||
|
format!("Profile: {}", add_table_state.profile_name),
|
||||||
|
theme.fg,
|
||||||
|
)),
|
||||||
|
Line::from(Span::styled(
|
||||||
|
format!("Table name: {}", add_table_state.table_name),
|
||||||
|
theme.fg,
|
||||||
|
)),
|
||||||
|
])
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::BOTTOM)
|
||||||
|
.border_style(Style::default().fg(theme.secondary)),
|
||||||
|
);
|
||||||
|
f.render_widget(profile_text, top_info_area);
|
||||||
|
} else {
|
||||||
|
// --- NARROW Layout (Based on second screenshot) ---
|
||||||
|
let main_chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(1), // Top: Profile & Table Name (Single Row)
|
||||||
|
Constraint::Length(5), // Column Definition Input Canvas Area
|
||||||
|
Constraint::Length(3), // Add Button Area
|
||||||
|
Constraint::Min(5), // Columns Table Area
|
||||||
|
Constraint::Min(5), // Indexes & Links Area
|
||||||
|
Constraint::Length(3), // Bottom: Save/Cancel Buttons
|
||||||
|
])
|
||||||
|
.split(inner_area);
|
||||||
|
|
||||||
|
top_info_area = main_chunks[0];
|
||||||
|
canvas_area = main_chunks[1];
|
||||||
|
add_button_area = main_chunks[2];
|
||||||
|
columns_area = main_chunks[3];
|
||||||
|
let indexes_links_area = main_chunks[4];
|
||||||
|
bottom_buttons_area = main_chunks[5];
|
||||||
|
|
||||||
|
// Split Indexes/Links Horizontally
|
||||||
|
let indexes_links_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(50), // Indexes Table
|
||||||
|
Constraint::Percentage(50), // Links Table
|
||||||
|
])
|
||||||
|
.split(indexes_links_area);
|
||||||
|
indexes_area = indexes_links_chunks[0];
|
||||||
|
links_area = indexes_links_chunks[1];
|
||||||
|
|
||||||
|
// --- Top Info Rendering (Narrow - 1 line) ---
|
||||||
|
let top_info_chunks = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(50),
|
||||||
|
Constraint::Percentage(50),
|
||||||
|
])
|
||||||
|
.split(top_info_area);
|
||||||
|
|
||||||
|
let profile_text = Paragraph::new(Span::styled(
|
||||||
|
format!("Profile: {}", add_table_state.profile_name),
|
||||||
|
theme.fg,
|
||||||
|
))
|
||||||
|
.alignment(Alignment::Left);
|
||||||
|
f.render_widget(profile_text, top_info_chunks[0]);
|
||||||
|
|
||||||
|
let table_name_text = Paragraph::new(Span::styled(
|
||||||
|
format!("Table: {}", add_table_state.table_name),
|
||||||
|
theme.fg,
|
||||||
|
))
|
||||||
|
.alignment(Alignment::Left);
|
||||||
|
f.render_widget(table_name_text, top_info_chunks[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Common Widget Rendering (Uses calculated areas) ---
|
||||||
|
|
||||||
|
// --- Columns Table Rendering ---
|
||||||
|
let columns_focused = matches!(add_table_state.current_focus, AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable);
|
||||||
|
let columns_border_style = if columns_focused {
|
||||||
|
Style::default().fg(theme.highlight)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.secondary)
|
||||||
|
};
|
||||||
|
let column_rows: Vec<Row<'_>> = add_table_state
|
||||||
|
.columns
|
||||||
|
.iter()
|
||||||
|
.map(|col_def| {
|
||||||
|
Row::new(vec![
|
||||||
|
Cell::from(if col_def.selected { "[*]" } else { "[ ]" }),
|
||||||
|
Cell::from(col_def.name.clone()),
|
||||||
|
Cell::from(col_def.data_type.clone()),
|
||||||
|
])
|
||||||
|
.style(Style::default().fg(theme.fg))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let header_cells = ["Sel", "Name", "Type"]
|
||||||
|
.iter()
|
||||||
|
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||||
|
let header = Row::new(header_cells).height(1).bottom_margin(1);
|
||||||
|
let columns_table = Table::new(
|
||||||
|
column_rows,
|
||||||
|
[ // Define constraints for 3 columns: Sel, Name, Type
|
||||||
|
Constraint::Length(5),
|
||||||
|
Constraint::Percentage(60),
|
||||||
|
Constraint::Percentage(35),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.header(header)
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::BOTTOM)
|
.title(Span::styled(" Columns ", theme.fg))
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
.title_alignment(Alignment::Center)
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(columns_border_style),
|
||||||
|
)
|
||||||
|
.row_highlight_style(
|
||||||
|
Style::default()
|
||||||
|
.add_modifier(Modifier::REVERSED)
|
||||||
|
.fg(theme.highlight),
|
||||||
|
)
|
||||||
|
.highlight_symbol(" > ");
|
||||||
|
f.render_stateful_widget(
|
||||||
|
columns_table,
|
||||||
|
columns_area,
|
||||||
|
&mut add_table_state.column_table_state,
|
||||||
);
|
);
|
||||||
f.render_widget(profile_text, left_vertical_chunks[0]);
|
|
||||||
|
|
||||||
// Columns section
|
// --- Canvas Rendering (Column Definition Input) ---
|
||||||
let columns_text = Paragraph::new(vec![
|
|
||||||
Line::from(Span::styled("Name Type", theme.accent)), // Header
|
|
||||||
])
|
|
||||||
.block(Block::default().title(Span::styled(" Columns ", theme.fg)));
|
|
||||||
f.render_widget(columns_text, left_vertical_chunks[1]);
|
|
||||||
|
|
||||||
// Indexes section
|
|
||||||
let indexes_text = Paragraph::new(vec![
|
|
||||||
Line::from(Span::styled("Column name", theme.accent)), // Header
|
|
||||||
])
|
|
||||||
.block(
|
|
||||||
Block::default()
|
|
||||||
.title(Span::styled(" Indexes ", theme.fg))
|
|
||||||
.borders(Borders::TOP) // Separator from Columns
|
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
|
||||||
);
|
|
||||||
f.render_widget(indexes_text, left_vertical_chunks[3]);
|
|
||||||
|
|
||||||
// Links section
|
|
||||||
let links_text = Paragraph::new(vec![
|
|
||||||
Line::from(Span::styled("Linked table Required", theme.accent)), // Header
|
|
||||||
])
|
|
||||||
.block(
|
|
||||||
Block::default()
|
|
||||||
.title(Span::styled(" Links ", theme.fg))
|
|
||||||
.borders(Borders::TOP) // Separator from Indexes
|
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
|
||||||
);
|
|
||||||
f.render_widget(links_text, left_vertical_chunks[5]);
|
|
||||||
|
|
||||||
// --- Right Pane ---
|
|
||||||
let right_vertical_chunks = Layout::default()
|
|
||||||
.direction(Direction::Vertical)
|
|
||||||
.constraints([
|
|
||||||
Constraint::Length(5), // Area for render_canvas (3 fields + 2 border)
|
|
||||||
Constraint::Length(3), // Add Button Area
|
|
||||||
Constraint::Min(1), // Spacer
|
|
||||||
Constraint::Length(3), // Save/Cancel buttons area
|
|
||||||
].as_ref())
|
|
||||||
.split(right_pane);
|
|
||||||
|
|
||||||
let canvas_area = right_vertical_chunks[0];
|
|
||||||
let add_button_area = right_vertical_chunks[1];
|
|
||||||
let bottom_buttons_area = right_vertical_chunks[3];
|
|
||||||
|
|
||||||
// --- Use render_canvas for Inputs ---
|
|
||||||
let _active_field_rect = render_canvas(
|
let _active_field_rect = render_canvas(
|
||||||
f,
|
f,
|
||||||
canvas_area,
|
canvas_area,
|
||||||
add_table_state,
|
add_table_state,
|
||||||
&[
|
&add_table_state.fields(),
|
||||||
"Table name",
|
|
||||||
"Name",
|
|
||||||
"Type",
|
|
||||||
],
|
|
||||||
&add_table_state.current_field(),
|
&add_table_state.current_field(),
|
||||||
&add_table_state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(),
|
&add_table_state.inputs(),
|
||||||
theme,
|
theme,
|
||||||
is_edit_mode,
|
is_edit_mode && focus_on_canvas_inputs,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Add Button (Placeholder)
|
// --- Button Style Helpers ---
|
||||||
|
let get_button_style = |button_focus: AddTableFocus, current_focus| {
|
||||||
|
// Only handles text style (FG + Bold) now, no BG
|
||||||
|
let is_focused = current_focus == button_focus;
|
||||||
|
let base_style = Style::default().fg(if is_focused {
|
||||||
|
theme.highlight // Highlighted text color
|
||||||
|
} else {
|
||||||
|
theme.secondary // Normal text color
|
||||||
|
});
|
||||||
|
if is_focused {
|
||||||
|
base_style.add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
base_style
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Updated signature to accept bool and theme
|
||||||
|
let get_button_border_style = |is_focused: bool, theme: &Theme| {
|
||||||
|
if is_focused {
|
||||||
|
Style::default().fg(theme.highlight)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.secondary)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Add Button Rendering ---
|
||||||
|
// Determine if the add button is focused
|
||||||
|
let is_add_button_focused = add_table_state.current_focus == AddTableFocus::AddColumnButton;
|
||||||
|
|
||||||
|
// Create the Add button Paragraph widget
|
||||||
let add_button = Paragraph::new(" Add ")
|
let add_button = Paragraph::new(" Add ")
|
||||||
.style(Style::default().fg(theme.secondary))
|
.style(get_button_style(AddTableFocus::AddColumnButton, add_table_state.current_focus)) // Use existing closure
|
||||||
.alignment(Alignment::Center)
|
.alignment(Alignment::Center)
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
.border_style(get_button_border_style(is_add_button_focused, theme)), // Pass bool and theme
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Render the button in its designated area
|
||||||
f.render_widget(add_button, add_button_area);
|
f.render_widget(add_button, add_button_area);
|
||||||
|
|
||||||
// Bottom Buttons Area (Save, Cancel)
|
// --- Indexes Table Rendering ---
|
||||||
|
let indexes_focused = matches!(add_table_state.current_focus, AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable);
|
||||||
|
let indexes_border_style = if indexes_focused {
|
||||||
|
Style::default().fg(theme.highlight)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.secondary)
|
||||||
|
};
|
||||||
|
let index_rows: Vec<Row<'_>> = add_table_state
|
||||||
|
.indexes
|
||||||
|
.iter()
|
||||||
|
.map(|index_name| {
|
||||||
|
Row::new(vec![Cell::from(index_name.clone())])
|
||||||
|
.style(Style::default().fg(theme.fg))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let index_header_cells = ["Column Name"]
|
||||||
|
.iter()
|
||||||
|
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||||
|
let index_header = Row::new(index_header_cells).height(1).bottom_margin(1);
|
||||||
|
let indexes_table =
|
||||||
|
Table::new(index_rows, [Constraint::Percentage(100)])
|
||||||
|
.header(index_header)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.title(Span::styled(" Indexes ", theme.fg))
|
||||||
|
.title_alignment(Alignment::Center)
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(indexes_border_style),
|
||||||
|
)
|
||||||
|
.row_highlight_style(
|
||||||
|
Style::default()
|
||||||
|
.add_modifier(Modifier::REVERSED)
|
||||||
|
.fg(theme.highlight),
|
||||||
|
)
|
||||||
|
.highlight_symbol(" > ");
|
||||||
|
f.render_stateful_widget(
|
||||||
|
indexes_table,
|
||||||
|
indexes_area,
|
||||||
|
&mut add_table_state.index_table_state,
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Links Table Rendering ---
|
||||||
|
let links_focused = matches!(add_table_state.current_focus, AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable);
|
||||||
|
let links_border_style = if links_focused {
|
||||||
|
Style::default().fg(theme.highlight)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.secondary)
|
||||||
|
};
|
||||||
|
let link_rows: Vec<Row<'_>> = add_table_state
|
||||||
|
.links
|
||||||
|
.iter()
|
||||||
|
.map(|link_def| {
|
||||||
|
Row::new(vec![
|
||||||
|
Cell::from(link_def.linked_table_name.clone()),
|
||||||
|
Cell::from(if link_def.is_required { "[X]" } else { "[ ]" }),
|
||||||
|
])
|
||||||
|
.style(Style::default().fg(theme.fg))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let link_header_cells = ["Linked Table", "Selected"]
|
||||||
|
.iter()
|
||||||
|
.map(|h| Cell::from(*h).style(Style::default().fg(theme.accent)));
|
||||||
|
let link_header = Row::new(link_header_cells).height(1).bottom_margin(1);
|
||||||
|
let links_table =
|
||||||
|
Table::new(link_rows, [Constraint::Percentage(80), Constraint::Min(5)])
|
||||||
|
.header(link_header)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.title(Span::styled(" Links ", theme.fg))
|
||||||
|
.title_alignment(Alignment::Center)
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(links_border_style),
|
||||||
|
)
|
||||||
|
.row_highlight_style(
|
||||||
|
Style::default()
|
||||||
|
.add_modifier(Modifier::REVERSED)
|
||||||
|
.fg(theme.highlight),
|
||||||
|
)
|
||||||
|
.highlight_symbol(" > ");
|
||||||
|
f.render_stateful_widget(
|
||||||
|
links_table,
|
||||||
|
links_area,
|
||||||
|
&mut add_table_state.link_table_state,
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Save/Cancel Buttons Rendering ---
|
||||||
let bottom_button_chunks = Layout::default()
|
let bottom_button_chunks = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Percentage(50), // Save Button
|
Constraint::Percentage(33), // Save Button
|
||||||
Constraint::Percentage(50), // Cancel Button
|
Constraint::Percentage(34), // Delete Button
|
||||||
].as_ref())
|
Constraint::Percentage(33), // Cancel Button
|
||||||
|
])
|
||||||
.split(bottom_buttons_area);
|
.split(bottom_buttons_area);
|
||||||
|
|
||||||
// Save Button (Placeholder)
|
|
||||||
let save_button = Paragraph::new(" Save table ")
|
let save_button = Paragraph::new(" Save table ")
|
||||||
.style(Style::default().fg(theme.secondary))
|
.style(get_button_style(
|
||||||
|
AddTableFocus::SaveButton,
|
||||||
|
add_table_state.current_focus,
|
||||||
|
))
|
||||||
.alignment(Alignment::Center)
|
.alignment(Alignment::Center)
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
.border_style(get_button_border_style(
|
||||||
|
add_table_state.current_focus == AddTableFocus::SaveButton, // Pass bool
|
||||||
|
theme,
|
||||||
|
)),
|
||||||
);
|
);
|
||||||
f.render_widget(save_button, bottom_button_chunks[0]);
|
f.render_widget(save_button, bottom_button_chunks[0]);
|
||||||
|
|
||||||
// Cancel Button (Placeholder)
|
let delete_button = Paragraph::new(" Delete Selected ")
|
||||||
let cancel_button = Paragraph::new(" Cancel ")
|
.style(get_button_style(
|
||||||
.style(Style::default().fg(theme.secondary))
|
AddTableFocus::DeleteSelectedButton,
|
||||||
|
add_table_state.current_focus,
|
||||||
|
))
|
||||||
.alignment(Alignment::Center)
|
.alignment(Alignment::Center)
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.border_style(Style::default().fg(theme.secondary)),
|
.border_style(get_button_border_style(
|
||||||
|
add_table_state.current_focus == AddTableFocus::DeleteSelectedButton, // Pass bool
|
||||||
|
theme,
|
||||||
|
)),
|
||||||
);
|
);
|
||||||
f.render_widget(cancel_button, bottom_button_chunks[1]);
|
f.render_widget(delete_button, bottom_button_chunks[1]);
|
||||||
|
|
||||||
|
let cancel_button = Paragraph::new(" Cancel ")
|
||||||
|
.style(get_button_style(
|
||||||
|
AddTableFocus::CancelButton,
|
||||||
|
add_table_state.current_focus,
|
||||||
|
))
|
||||||
|
.alignment(Alignment::Center)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.border_style(get_button_border_style(
|
||||||
|
add_table_state.current_focus == AddTableFocus::CancelButton, // Pass bool
|
||||||
|
theme,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
f.render_widget(cancel_button, bottom_button_chunks[2]);
|
||||||
|
|
||||||
|
// --- DIALOG ---
|
||||||
|
// Render the dialog overlay if it's active
|
||||||
|
if app_state.ui.dialog.dialog_show { // Use the passed-in app_state
|
||||||
|
dialog::render_dialog(
|
||||||
|
f,
|
||||||
|
f.area(), // Render over the whole frame area
|
||||||
|
theme,
|
||||||
|
&app_state.ui.dialog.dialog_title,
|
||||||
|
&app_state.ui.dialog.dialog_message,
|
||||||
|
&app_state.ui.dialog.dialog_buttons,
|
||||||
|
app_state.ui.dialog.dialog_active_button_index,
|
||||||
|
app_state.ui.dialog.is_loading,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use crate::state::app::state::AppState;
|
|||||||
use crate::state::pages::admin::AdminState;
|
use crate::state::pages::admin::AdminState;
|
||||||
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Constraint, Direction, Layout, Rect},
|
||||||
style::Style,
|
style::Style,
|
||||||
text::{Line, Span, Text},
|
text::{Line, Span, Text},
|
||||||
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
|
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use ratatui::{
|
|||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::Style,
|
style::Style,
|
||||||
text::{Line, Span, Text}, // Added Text
|
text::{Line, Span, Text}, // Added Text
|
||||||
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
|
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},
|
||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -66,8 +66,7 @@ pub fn render_admin_panel_admin(
|
|||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(idx, profile)| {
|
.map(|(idx, profile)| {
|
||||||
// Check persistent selection for prefix, navigation state for style/highlight
|
// Check persistent selection for prefix, navigation state for style/highlight
|
||||||
let is_selected = admin_state.selected_profile_index == Some(idx); // Use persistent state for [*]
|
let is_selected = admin_state.selected_profile_index == Some(idx);
|
||||||
let is_navigated = admin_state.profile_list_state.selected() == Some(idx); // Use nav state for highlight/>
|
|
||||||
let prefix = if is_selected { "[*] " } else { "[ ] " };
|
let prefix = if is_selected { "[*] " } else { "[ ] " };
|
||||||
let style = if is_selected { // Style based on selection too
|
let style = if is_selected { // Style based on selection too
|
||||||
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
|
Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD)
|
||||||
|
|||||||
@@ -142,7 +142,8 @@ pub fn render_login(
|
|||||||
&app_state.ui.dialog.dialog_title,
|
&app_state.ui.dialog.dialog_title,
|
||||||
&app_state.ui.dialog.dialog_message,
|
&app_state.ui.dialog.dialog_message,
|
||||||
&app_state.ui.dialog.dialog_buttons, // Pass buttons slice
|
&app_state.ui.dialog.dialog_buttons, // Pass buttons slice
|
||||||
app_state.ui.dialog.dialog_active_button_index, // Pass active index
|
app_state.ui.dialog.dialog_active_button_index,
|
||||||
|
app_state.ui.dialog.is_loading,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -152,7 +152,7 @@ pub fn render_register(
|
|||||||
let selected = state.get_selected_suggestion_index();
|
let selected = state.get_selected_suggestion_index();
|
||||||
if !suggestions.is_empty() {
|
if !suggestions.is_empty() {
|
||||||
if let Some(input_rect) = active_field_rect {
|
if let Some(input_rect) = active_field_rect {
|
||||||
autocomplete::render_autocomplete_dropdown(f, input_rect, f.size(), theme, suggestions, selected);
|
autocomplete::render_autocomplete_dropdown(f, input_rect, f.area(), theme, suggestions, selected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -168,6 +168,7 @@ pub fn render_register(
|
|||||||
&app_state.ui.dialog.dialog_message,
|
&app_state.ui.dialog.dialog_message,
|
||||||
&app_state.ui.dialog.dialog_buttons,
|
&app_state.ui.dialog.dialog_buttons,
|
||||||
app_state.ui.dialog.dialog_active_button_index,
|
app_state.ui.dialog.dialog_active_button_index,
|
||||||
|
app_state.ui.dialog.is_loading,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ pub fn render_dialog(
|
|||||||
dialog_message: &str,
|
dialog_message: &str,
|
||||||
dialog_buttons: &[String],
|
dialog_buttons: &[String],
|
||||||
dialog_active_button_index: usize,
|
dialog_active_button_index: usize,
|
||||||
|
is_loading: bool,
|
||||||
) {
|
) {
|
||||||
// Calculate required height based on the actual number of lines in the message
|
// Calculate required height based on the actual number of lines in the message
|
||||||
let message_lines: Vec<_> = dialog_message.lines().collect();
|
let message_lines: Vec<_> = dialog_message.lines().collect();
|
||||||
@@ -63,27 +64,36 @@ pub fn render_dialog(
|
|||||||
vertical: 1, // Top/Bottom padding inside border
|
vertical: 1, // Top/Bottom padding inside border
|
||||||
});
|
});
|
||||||
|
|
||||||
// Layout for Message and Buttons based on actual message height
|
if is_loading {
|
||||||
let mut constraints = vec![
|
// --- Loading State ---
|
||||||
// Allocate space for message, ensuring at least 1 line height
|
let loading_text = Paragraph::new(dialog_message) // Use the message passed for loading
|
||||||
Constraint::Length(message_height.max(1)), // Use actual calculated height
|
.style(Style::default().fg(theme.fg).add_modifier(Modifier::ITALIC))
|
||||||
];
|
.alignment(Alignment::Center);
|
||||||
if button_row_height > 0 {
|
// Render loading message centered in the inner area
|
||||||
constraints.push(Constraint::Length(button_row_height));
|
f.render_widget(loading_text, inner_area);
|
||||||
}
|
} else {
|
||||||
|
// --- Normal State (Message + Buttons) ---
|
||||||
|
|
||||||
let chunks = Layout::default()
|
// Layout for Message and Buttons based on actual message height
|
||||||
.direction(Direction::Vertical)
|
let mut constraints = vec![
|
||||||
.constraints(constraints)
|
// Allocate space for message, ensuring at least 1 line height
|
||||||
.split(inner_area);
|
Constraint::Length(message_height.max(1)), // Use actual calculated height
|
||||||
|
];
|
||||||
|
if button_row_height > 0 {
|
||||||
|
constraints.push(Constraint::Length(button_row_height));
|
||||||
|
}
|
||||||
|
|
||||||
// Render Message
|
let chunks = Layout::default()
|
||||||
let available_width = inner_area.width as usize;
|
.direction(Direction::Vertical)
|
||||||
let ellipsis = "...";
|
.constraints(constraints)
|
||||||
let ellipsis_width = UnicodeWidthStr::width(ellipsis);
|
.split(inner_area);
|
||||||
|
|
||||||
let processed_lines: Vec<Line> =
|
// Render Message
|
||||||
message_lines
|
let available_width = inner_area.width as usize;
|
||||||
|
let ellipsis = "...";
|
||||||
|
let ellipsis_width = UnicodeWidthStr::width(ellipsis);
|
||||||
|
|
||||||
|
let processed_lines: Vec<Line> = message_lines
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|line| {
|
.map(|line| {
|
||||||
let line_width = UnicodeWidthStr::width(line);
|
let line_width = UnicodeWidthStr::width(line);
|
||||||
@@ -91,81 +101,83 @@ pub fn render_dialog(
|
|||||||
// Truncate with ellipsis
|
// Truncate with ellipsis
|
||||||
let mut truncated_len = 0;
|
let mut truncated_len = 0;
|
||||||
let mut current_width = 0;
|
let mut current_width = 0;
|
||||||
// Iterate over graphemes to handle multi-byte characters correctly
|
|
||||||
for (idx, grapheme) in line.grapheme_indices(true) {
|
for (idx, grapheme) in line.grapheme_indices(true) {
|
||||||
let grapheme_width = UnicodeWidthStr::width(grapheme);
|
let grapheme_width = UnicodeWidthStr::width(grapheme);
|
||||||
if current_width + grapheme_width > available_width.saturating_sub(ellipsis_width) {
|
if current_width + grapheme_width
|
||||||
break; // Stop before exceeding width needed for text + ellipsis
|
> available_width.saturating_sub(ellipsis_width)
|
||||||
|
{
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
current_width += grapheme_width;
|
current_width += grapheme_width;
|
||||||
truncated_len = idx + grapheme.len(); // Store the byte index of the end of the last fitting grapheme
|
truncated_len = idx + grapheme.len();
|
||||||
}
|
}
|
||||||
let truncated_line = format!("{}{}", &line[..truncated_len], ellipsis);
|
let truncated_line =
|
||||||
Line::from(Span::styled(truncated_line, Style::default().fg(theme.fg)))
|
format!("{}{}", &line[..truncated_len], ellipsis);
|
||||||
|
Line::from(Span::styled(
|
||||||
|
truncated_line,
|
||||||
|
Style::default().fg(theme.fg),
|
||||||
|
))
|
||||||
} else {
|
} else {
|
||||||
// Line fits, use it as is
|
|
||||||
Line::from(Span::styled(line, Style::default().fg(theme.fg)))
|
Line::from(Span::styled(line, Style::default().fg(theme.fg)))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let message_paragraph =
|
let message_paragraph =
|
||||||
Paragraph::new(Text::from(processed_lines)).alignment(Alignment::Center);
|
Paragraph::new(Text::from(processed_lines)).alignment(Alignment::Center);
|
||||||
// Render message in the first chunk
|
f.render_widget(message_paragraph, chunks[0]); // Render message in the first chunk
|
||||||
f.render_widget(message_paragraph, chunks[0]);
|
|
||||||
|
|
||||||
// Render Buttons if they exist and there's a chunk for them
|
// Render Buttons if they exist and there's a chunk for them
|
||||||
if !dialog_buttons.is_empty() && chunks.len() > 1 {
|
if !dialog_buttons.is_empty() && chunks.len() > 1 {
|
||||||
let button_area = chunks[1];
|
let button_area = chunks[1];
|
||||||
let button_count = dialog_buttons.len();
|
let button_count = dialog_buttons.len();
|
||||||
|
|
||||||
// Use Ratio for potentially more even distribution with few buttons
|
let button_constraints = std::iter::repeat(Constraint::Ratio(
|
||||||
let button_constraints = std::iter::repeat(Constraint::Ratio(
|
1,
|
||||||
1,
|
button_count as u32,
|
||||||
button_count as u32,
|
))
|
||||||
))
|
.take(button_count)
|
||||||
.take(button_count)
|
.collect::<Vec<_>>();
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let button_chunks = Layout::default()
|
let button_chunks = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints(button_constraints)
|
.constraints(button_constraints)
|
||||||
.horizontal_margin(1) // Add space between buttons
|
.horizontal_margin(1) // Add space between buttons
|
||||||
.split(button_area);
|
.split(button_area);
|
||||||
|
|
||||||
for (i, button_label) in dialog_buttons.iter().enumerate() {
|
for (i, button_label) in dialog_buttons.iter().enumerate() {
|
||||||
// Ensure we don't try to render into a non-existent chunk
|
if i >= button_chunks.len() {
|
||||||
if i >= button_chunks.len() {
|
break;
|
||||||
break;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let is_active = i == dialog_active_button_index;
|
let is_active = i == dialog_active_button_index;
|
||||||
let (button_style, border_style) = if is_active {
|
let (button_style, border_style) = if is_active {
|
||||||
(
|
(
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.highlight)
|
.fg(theme.highlight)
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
Style::default().fg(theme.accent), // Highlight border
|
Style::default().fg(theme.accent),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
(
|
(
|
||||||
Style::default().fg(theme.fg),
|
Style::default().fg(theme.fg),
|
||||||
Style::default().fg(theme.border), // Normal border
|
Style::default().fg(theme.border),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let button_block = Block::default()
|
let button_block = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Plain)
|
.border_type(BorderType::Plain)
|
||||||
.border_style(border_style);
|
.border_style(border_style);
|
||||||
|
|
||||||
f.render_widget(
|
f.render_widget(
|
||||||
Paragraph::new(button_label.as_str())
|
Paragraph::new(button_label.as_str())
|
||||||
.block(button_block)
|
.block(button_block)
|
||||||
.style(button_style)
|
.style(button_style)
|
||||||
.alignment(Alignment::Center),
|
.alignment(Alignment::Center),
|
||||||
button_chunks[i],
|
button_chunks[i],
|
||||||
);
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::config::colors::themes::Theme;
|
|||||||
use crate::state::app::buffer::BufferState;
|
use crate::state::app::buffer::BufferState;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Rect},
|
layout::{Alignment, Rect},
|
||||||
style::{Style, Stylize},
|
style::Style,
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::Paragraph,
|
widgets::Paragraph,
|
||||||
Frame,
|
Frame,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
use crossterm::event::{KeyCode, KeyModifiers};
|
use crossterm::event::{KeyCode, KeyModifiers};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
#[derive(Debug, Deserialize, Default)]
|
||||||
@@ -43,11 +44,11 @@ pub struct ModeKeybindings {
|
|||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
/// Loads the configuration from "config.toml" in the client crate directory.
|
/// Loads the configuration from "config.toml" in the client crate directory.
|
||||||
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
|
pub fn load() -> Result<Self> {
|
||||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||||
let config_path = Path::new(manifest_dir).join("config.toml");
|
let config_path = Path::new(manifest_dir).join("config.toml");
|
||||||
let config_str = std::fs::read_to_string(&config_path)
|
let config_str = std::fs::read_to_string(&config_path)
|
||||||
.map_err(|e| format!("Failed to read config file at {:?}: {}", config_path, e))?;
|
.with_context(|| format!("Failed to read config file at {:?}", config_path))?;
|
||||||
let config: Config = toml::from_str(&config_str)?;
|
let config: Config = toml::from_str(&config_str)?;
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,4 @@
|
|||||||
|
|
||||||
pub mod form_e;
|
pub mod form_e;
|
||||||
pub mod auth_e;
|
pub mod auth_e;
|
||||||
|
pub mod add_table_e;
|
||||||
|
|||||||
341
client/src/functions/modes/edit/add_table_e.rs
Normal file
341
client/src/functions/modes/edit/add_table_e.rs
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
// src/functions/modes/edit/add_table_e.rs
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
|
use crate::state::pages::canvas_state::CanvasState; // Use trait
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
CharType::Whitespace
|
||||||
|
} else if c.is_alphanumeric() {
|
||||||
|
CharType::Alphanumeric
|
||||||
|
} else {
|
||||||
|
CharType::Punctuation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos >= len {
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == initial_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
|
||||||
|
if get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos >= len {
|
||||||
|
return len.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
|
||||||
|
pos -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pos > 0 {
|
||||||
|
pos - 1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Executes edit actions for the AddTable view canvas.
|
||||||
|
pub async fn execute_edit_action(
|
||||||
|
action: &str,
|
||||||
|
key: KeyEvent, // Needed for insert_char
|
||||||
|
state: &mut AddTableState,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
// Add other params like grpc_client if needed for future actions (e.g., validation)
|
||||||
|
) -> Result<String> {
|
||||||
|
// Use the CanvasState trait methods implemented for AddTableState
|
||||||
|
match action {
|
||||||
|
"insert_char" => {
|
||||||
|
if let KeyCode::Char(c) = key.code {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.insert(cursor_pos, c);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_current_cursor_pos(cursor_pos + 1);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = state.current_cursor_pos();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Ok("Error: insert_char called without a char key.".to_string());
|
||||||
|
}
|
||||||
|
Ok("".to_string()) // No message needed for char insertion
|
||||||
|
}
|
||||||
|
"delete_char_backward" => {
|
||||||
|
if state.current_cursor_pos() > 0 {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos <= chars.len() {
|
||||||
|
chars.remove(cursor_pos - 1);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
let new_pos = cursor_pos - 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"delete_char_forward" => {
|
||||||
|
let cursor_pos = state.current_cursor_pos();
|
||||||
|
let field_value = state.get_current_input_mut();
|
||||||
|
let mut chars: Vec<char> = field_value.chars().collect();
|
||||||
|
if cursor_pos < chars.len() {
|
||||||
|
chars.remove(cursor_pos);
|
||||||
|
*field_value = chars.into_iter().collect();
|
||||||
|
state.set_has_unsaved_changes(true);
|
||||||
|
*ideal_cursor_column = cursor_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"next_field" => {
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
// Prevent cycling forward
|
||||||
|
if current_field < last_field_index {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
"prev_field" => {
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
if current_field > 0 {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
"move_left" => {
|
||||||
|
let new_pos = state.current_cursor_pos().saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
if current_pos < current_input.len() {
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_up" => {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
// Prevent moving up from the first 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("ahoj".to_string())
|
||||||
|
}
|
||||||
|
"move_down" => {
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields > 0 {
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
if current_field < last_field_index {
|
||||||
|
let new_field = current_field + 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_first_line" => {
|
||||||
|
if AddTableState::INPUT_FIELD_COUNT > 0 {
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_last_line" => {
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields > 0 {
|
||||||
|
let new_field = num_fields - 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_pos = current_input.len();
|
||||||
|
state.set_current_cursor_pos((*ideal_cursor_column).min(max_pos));
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
|
||||||
|
let final_pos = new_pos.min(current_input.len());
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
|
||||||
|
let final_pos = if new_pos == current_pos {
|
||||||
|
find_word_end(current_input, new_pos + 1)
|
||||||
|
} else {
|
||||||
|
new_pos
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_valid_index = current_input.len().saturating_sub(1);
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
if !current_input.is_empty() {
|
||||||
|
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
// Actions handled by main event loop (mode changes, save, revert)
|
||||||
|
"exit_edit_mode" | "save" | "revert" => {
|
||||||
|
Ok("Action handled by main loop".to_string())
|
||||||
|
}
|
||||||
|
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ use crate::state::pages::auth::RegisterState;
|
|||||||
use crate::tui::functions::common::form::{revert, save};
|
use crate::tui::functions::common::form::{revert, save};
|
||||||
use crossterm::event::{KeyCode, KeyEvent};
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn execute_common_action<S: CanvasState + Any>(
|
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||||
action: &str,
|
action: &str,
|
||||||
@@ -14,7 +15,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String> {
|
||||||
match action {
|
match action {
|
||||||
"save" | "revert" => {
|
"save" | "revert" => {
|
||||||
if !state.has_unsaved_changes() {
|
if !state.has_unsaved_changes() {
|
||||||
@@ -62,10 +63,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
|||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
state: &mut S,
|
state: &mut S,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
grpc_client: &mut GrpcClient,
|
) -> Result<String> {
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
match action {
|
||||||
"insert_char" => {
|
"insert_char" => {
|
||||||
if let KeyCode::Char(c) = key.code {
|
if let KeyCode::Char(c) = key.code {
|
||||||
@@ -120,7 +118,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
|||||||
let num_fields = state.fields().len();
|
let num_fields = state.fields().len();
|
||||||
if num_fields > 0 {
|
if num_fields > 0 {
|
||||||
let current_field = state.current_field();
|
let current_field = state.current_field();
|
||||||
let new_field = (current_field + 1) % num_fields;
|
let new_field = (current_field + 1).min(num_fields - 1);
|
||||||
state.set_current_field(new_field);
|
state.set_current_field(new_field);
|
||||||
let current_input = state.get_current_input();
|
let current_input = state.get_current_input();
|
||||||
let max_pos = current_input.len();
|
let max_pos = current_input.len();
|
||||||
@@ -135,11 +133,7 @@ pub async fn execute_edit_action<S: CanvasState + Any + Send>(
|
|||||||
let num_fields = state.fields().len();
|
let num_fields = state.fields().len();
|
||||||
if num_fields > 0 {
|
if num_fields > 0 {
|
||||||
let current_field = state.current_field();
|
let current_field = state.current_field();
|
||||||
let new_field = if current_field == 0 {
|
let new_field = current_field.saturating_sub(1);
|
||||||
num_fields - 1
|
|
||||||
} else {
|
|
||||||
current_field - 1
|
|
||||||
};
|
|
||||||
state.set_current_field(new_field);
|
state.set_current_field(new_field);
|
||||||
let current_input = state.get_current_input();
|
let current_input = state.get_current_input();
|
||||||
let max_pos = current_input.len();
|
let max_pos = current_input.len();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use crate::tui::functions::common::form::SaveOutcome;
|
|||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crossterm::event::{KeyCode, KeyEvent};
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn execute_common_action<S: CanvasState + Any>(
|
pub async fn execute_common_action<S: CanvasState + Any>(
|
||||||
action: &str,
|
action: &str,
|
||||||
@@ -15,7 +16,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome> {
|
||||||
match action {
|
match action {
|
||||||
"save" | "revert" => {
|
"save" | "revert" => {
|
||||||
if !state.has_unsaved_changes() {
|
if !state.has_unsaved_changes() {
|
||||||
@@ -76,10 +77,7 @@ pub async fn execute_edit_action<S: CanvasState>(
|
|||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
state: &mut S,
|
state: &mut S,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
grpc_client: &mut GrpcClient,
|
) -> Result<String> {
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
match action {
|
match action {
|
||||||
"insert_char" => {
|
"insert_char" => {
|
||||||
if let KeyCode::Char(c) = key.code {
|
if let KeyCode::Char(c) = key.code {
|
||||||
|
|||||||
@@ -5,209 +5,314 @@ use crate::state::{
|
|||||||
pages::add_table::{AddTableFocus, AddTableState},
|
pages::add_table::{AddTableFocus, AddTableState},
|
||||||
};
|
};
|
||||||
use crossterm::event::{KeyEvent};
|
use crossterm::event::{KeyEvent};
|
||||||
use ratatui::widgets::TableState; // Import TableState
|
use ratatui::widgets::TableState;
|
||||||
|
use crate::tui::functions::common::add_table::handle_add_column_action;
|
||||||
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
|
|
||||||
/// Handles navigation events specifically for the Add Table view.
|
/// Handles navigation events specifically for the Add Table view.
|
||||||
/// Returns true if the event was handled, false otherwise.
|
/// Returns true if the event was handled, false otherwise.
|
||||||
pub fn handle_add_table_navigation(
|
pub fn handle_add_table_navigation(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
_app_state: &AppState, // Keep for potential future use (e.g., checking permissions)
|
app_state: &mut AppState,
|
||||||
add_table_state: &mut AddTableState,
|
add_table_state: &mut AddTableState,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let action = config.get_general_action(key.code, key.modifiers);
|
let action = config.get_general_action(key.code, key.modifiers);
|
||||||
let current_focus = add_table_state.current_focus;
|
let current_focus = add_table_state.current_focus;
|
||||||
let mut handled = true; // Assume handled unless logic determines otherwise
|
let mut handled = true; // Assume handled unless logic determines otherwise
|
||||||
|
let mut new_focus = current_focus; // Initialize new_focus
|
||||||
|
|
||||||
match action.as_deref() {
|
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();
|
||||||
|
}
|
||||||
|
AddTableFocus::InsideIndexesTable => {
|
||||||
|
add_table_state.index_table_state.select(None);
|
||||||
|
new_focus = AddTableFocus::IndexesTable;
|
||||||
|
*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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If handled (i.e., focus changed), handled remains true.
|
||||||
|
// If not handled, handled becomes false.
|
||||||
|
}
|
||||||
|
|
||||||
// --- Vertical Navigation (Up/Down) ---
|
// --- Vertical Navigation (Up/Down) ---
|
||||||
Some("move_up") => {
|
Some("move_up") => {
|
||||||
let mut new_focus = current_focus; // Start with current focus
|
|
||||||
match current_focus {
|
match current_focus {
|
||||||
AddTableFocus::InputTableName => new_focus = AddTableFocus::CancelButton, // Wrap top
|
AddTableFocus::InputTableName => new_focus = AddTableFocus::CancelButton,
|
||||||
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputTableName,
|
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputTableName,
|
||||||
AddTableFocus::InputColumnType => new_focus = AddTableFocus::InputColumnName,
|
AddTableFocus::InputColumnType => new_focus = AddTableFocus::InputColumnName,
|
||||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::InputColumnType,
|
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::InputColumnType,
|
||||||
AddTableFocus::ColumnsTable => {
|
// Navigate between blocks when focus is on the table block itself
|
||||||
if !navigate_table_up(&mut add_table_state.column_table_state, add_table_state.columns.len()) {
|
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::AddColumnButton, // Move up to right pane
|
||||||
new_focus = AddTableFocus::AddColumnButton; // Move focus up if at table top
|
AddTableFocus::IndexesTable => new_focus = AddTableFocus::ColumnsTable,
|
||||||
}
|
AddTableFocus::LinksTable => new_focus = AddTableFocus::IndexesTable,
|
||||||
// Keep focus on table while navigating within it
|
// 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::IndexesTable => {
|
AddTableFocus::InsideIndexesTable => {
|
||||||
if !navigate_table_up(&mut add_table_state.index_table_state, add_table_state.indexes.len()) {
|
navigate_table_up(&mut add_table_state.index_table_state, add_table_state.indexes.len());
|
||||||
new_focus = AddTableFocus::ColumnsTable; // Move focus up
|
// Stay inside the table
|
||||||
}
|
|
||||||
}
|
}
|
||||||
AddTableFocus::LinksTable => {
|
AddTableFocus::InsideLinksTable => {
|
||||||
if !navigate_table_up(&mut add_table_state.link_table_state, add_table_state.links.len()) {
|
navigate_table_up(&mut add_table_state.link_table_state, add_table_state.links.len());
|
||||||
new_focus = AddTableFocus::IndexesTable; // Move focus up
|
// Stay inside the table
|
||||||
}
|
|
||||||
}
|
}
|
||||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::LinksTable,
|
AddTableFocus::SaveButton => new_focus = AddTableFocus::LinksTable,
|
||||||
AddTableFocus::CancelButton => new_focus = AddTableFocus::SaveButton,
|
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::SaveButton,
|
||||||
|
AddTableFocus::CancelButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||||
}
|
}
|
||||||
add_table_state.current_focus = new_focus;
|
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
|
||||||
}
|
}
|
||||||
Some("move_down") => {
|
Some("move_down") => {
|
||||||
let mut new_focus = current_focus; // Start with current focus
|
|
||||||
match current_focus {
|
match current_focus {
|
||||||
AddTableFocus::InputTableName => new_focus = AddTableFocus::InputColumnName,
|
AddTableFocus::InputTableName => new_focus = AddTableFocus::InputColumnName,
|
||||||
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputColumnType,
|
AddTableFocus::InputColumnName => new_focus = AddTableFocus::InputColumnType,
|
||||||
AddTableFocus::InputColumnType => new_focus = AddTableFocus::AddColumnButton,
|
AddTableFocus::InputColumnType => new_focus = AddTableFocus::AddColumnButton,
|
||||||
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::ColumnsTable,
|
AddTableFocus::AddColumnButton => new_focus = AddTableFocus::ColumnsTable,
|
||||||
AddTableFocus::ColumnsTable => {
|
// Navigate between blocks when focus is on the table block itself
|
||||||
if !navigate_table_down(&mut add_table_state.column_table_state, add_table_state.columns.len()) {
|
AddTableFocus::ColumnsTable => new_focus = AddTableFocus::IndexesTable,
|
||||||
new_focus = AddTableFocus::IndexesTable; // Move focus down if at table bottom
|
AddTableFocus::IndexesTable => new_focus = AddTableFocus::LinksTable,
|
||||||
}
|
AddTableFocus::LinksTable => new_focus = AddTableFocus::SaveButton, // Move down to right pane
|
||||||
// Keep focus on table while navigating within it
|
// 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::IndexesTable => {
|
AddTableFocus::InsideIndexesTable => {
|
||||||
if !navigate_table_down(&mut add_table_state.index_table_state, add_table_state.indexes.len()) {
|
navigate_table_down(&mut add_table_state.index_table_state, add_table_state.indexes.len());
|
||||||
new_focus = AddTableFocus::LinksTable; // Move focus down
|
// Stay inside the table
|
||||||
}
|
|
||||||
}
|
}
|
||||||
AddTableFocus::LinksTable => {
|
AddTableFocus::InsideLinksTable => {
|
||||||
if !navigate_table_down(&mut add_table_state.link_table_state, add_table_state.links.len()) {
|
navigate_table_down(&mut add_table_state.link_table_state, add_table_state.links.len());
|
||||||
new_focus = AddTableFocus::SaveButton; // Move focus down
|
// Stay inside the table
|
||||||
}
|
|
||||||
}
|
}
|
||||||
AddTableFocus::SaveButton => new_focus = AddTableFocus::CancelButton,
|
AddTableFocus::SaveButton => new_focus = AddTableFocus::DeleteSelectedButton,
|
||||||
AddTableFocus::CancelButton => new_focus = AddTableFocus::InputTableName, // Wrap bottom
|
AddTableFocus::DeleteSelectedButton => new_focus = AddTableFocus::CancelButton,
|
||||||
|
AddTableFocus::CancelButton => new_focus = AddTableFocus::InputTableName,
|
||||||
}
|
}
|
||||||
add_table_state.current_focus = new_focus;
|
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Horizontal Navigation (Left/Right) ---
|
// --- Horizontal Navigation (Left/Right) ---
|
||||||
Some("next_option") => { // 'l' or Right
|
Some("next_option") => { // 'l' or Right: Move from Left Pane to Right Pane
|
||||||
add_table_state.current_focus = match current_focus {
|
// Horizontal nav within bottom buttons
|
||||||
AddTableFocus::SaveButton => AddTableFocus::CancelButton,
|
if current_focus == AddTableFocus::SaveButton {
|
||||||
_ => current_focus, // No change for others yet
|
new_focus = AddTableFocus::DeleteSelectedButton;
|
||||||
};
|
} else if current_focus == AddTableFocus::DeleteSelectedButton {
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
new_focus = AddTableFocus::CancelButton;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Some("previous_option") => { // 'h' or Left
|
Some("previous_option") => { // 'h' or Left: Move from Right Pane to Left Pane
|
||||||
add_table_state.current_focus = match current_focus {
|
// Horizontal nav within bottom buttons
|
||||||
AddTableFocus::CancelButton => AddTableFocus::SaveButton,
|
if current_focus == AddTableFocus::CancelButton {
|
||||||
_ => current_focus, // No change for others yet
|
new_focus = AddTableFocus::DeleteSelectedButton;
|
||||||
};
|
} else if current_focus == AddTableFocus::DeleteSelectedButton {
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
new_focus = AddTableFocus::SaveButton;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Tab / Shift+Tab Navigation ---
|
// --- Tab / Shift+Tab Navigation (Keep as vertical cycle) ---
|
||||||
Some("next_field") => { // Tab
|
Some("next_field") => { // Tab
|
||||||
add_table_state.current_focus = match current_focus {
|
new_focus = match current_focus {
|
||||||
AddTableFocus::InputTableName => AddTableFocus::InputColumnName,
|
AddTableFocus::InputTableName => AddTableFocus::InputColumnName,
|
||||||
AddTableFocus::InputColumnName => AddTableFocus::InputColumnType,
|
AddTableFocus::InputColumnName => AddTableFocus::InputColumnType,
|
||||||
AddTableFocus::InputColumnType => AddTableFocus::AddColumnButton,
|
AddTableFocus::InputColumnType => AddTableFocus::AddColumnButton,
|
||||||
AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable,
|
AddTableFocus::AddColumnButton => AddTableFocus::ColumnsTable,
|
||||||
AddTableFocus::ColumnsTable => AddTableFocus::IndexesTable,
|
// Treat Inside* same as block focus for tabbing out
|
||||||
AddTableFocus::IndexesTable => AddTableFocus::LinksTable,
|
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::IndexesTable,
|
||||||
AddTableFocus::LinksTable => AddTableFocus::SaveButton,
|
AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::LinksTable,
|
||||||
AddTableFocus::SaveButton => AddTableFocus::CancelButton,
|
AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::SaveButton,
|
||||||
|
AddTableFocus::SaveButton => AddTableFocus::DeleteSelectedButton,
|
||||||
|
AddTableFocus::DeleteSelectedButton => AddTableFocus::CancelButton,
|
||||||
AddTableFocus::CancelButton => AddTableFocus::InputTableName, // Wrap
|
AddTableFocus::CancelButton => AddTableFocus::InputTableName, // Wrap
|
||||||
};
|
};
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
|
||||||
}
|
}
|
||||||
Some("prev_field") => { // Shift+Tab
|
Some("prev_field") => { // Shift+Tab
|
||||||
add_table_state.current_focus = match current_focus {
|
new_focus = match current_focus {
|
||||||
AddTableFocus::InputTableName => AddTableFocus::CancelButton, // Wrap
|
AddTableFocus::InputTableName => AddTableFocus::CancelButton, // Wrap
|
||||||
AddTableFocus::InputColumnName => AddTableFocus::InputTableName,
|
AddTableFocus::InputColumnName => AddTableFocus::InputTableName,
|
||||||
AddTableFocus::InputColumnType => AddTableFocus::InputColumnName,
|
AddTableFocus::InputColumnType => AddTableFocus::InputColumnName,
|
||||||
AddTableFocus::AddColumnButton => AddTableFocus::InputColumnType,
|
AddTableFocus::AddColumnButton => AddTableFocus::InputColumnType,
|
||||||
AddTableFocus::ColumnsTable => AddTableFocus::AddColumnButton,
|
// Treat Inside* same as block focus for tabbing out
|
||||||
AddTableFocus::IndexesTable => AddTableFocus::ColumnsTable,
|
AddTableFocus::ColumnsTable | AddTableFocus::InsideColumnsTable => AddTableFocus::AddColumnButton,
|
||||||
AddTableFocus::LinksTable => AddTableFocus::IndexesTable,
|
AddTableFocus::IndexesTable | AddTableFocus::InsideIndexesTable => AddTableFocus::ColumnsTable,
|
||||||
|
AddTableFocus::LinksTable | AddTableFocus::InsideLinksTable => AddTableFocus::IndexesTable,
|
||||||
AddTableFocus::SaveButton => AddTableFocus::LinksTable,
|
AddTableFocus::SaveButton => AddTableFocus::LinksTable,
|
||||||
AddTableFocus::CancelButton => AddTableFocus::SaveButton,
|
AddTableFocus::DeleteSelectedButton => AddTableFocus::SaveButton,
|
||||||
|
AddTableFocus::CancelButton => AddTableFocus::DeleteSelectedButton,
|
||||||
};
|
};
|
||||||
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Selection ---
|
// --- Selection ---
|
||||||
Some("select") => {
|
Some("select") => {
|
||||||
match current_focus {
|
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() {
|
||||||
|
*command_message = format!("Selected index index {} (Press Esc to exit scroll mode)", index);
|
||||||
|
} 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 => {
|
AddTableFocus::AddColumnButton => {
|
||||||
*command_message = "Action: Add Column (Not Implemented)".to_string();
|
if let Some(focus_after_add) = handle_add_column_action(add_table_state, command_message) {
|
||||||
// TODO: Implement logic to add column based on inputs
|
new_focus = focus_after_add;
|
||||||
// Clear input fields, add to columns list, mark unsaved changes
|
}
|
||||||
// add_table_state.add_column(); // Example method call
|
|
||||||
}
|
}
|
||||||
AddTableFocus::SaveButton => {
|
AddTableFocus::SaveButton => {
|
||||||
*command_message = "Action: Save Table (Not Implemented)".to_string();
|
*command_message = "Action: Save Table (Not Implemented)".to_string();
|
||||||
// TODO: Implement logic to save table (e.g., call API)
|
// TODO: Implement logic
|
||||||
// Mark changes as saved
|
}
|
||||||
// add_table_state.save_table(); // Example method call
|
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 => {
|
AddTableFocus::CancelButton => {
|
||||||
*command_message = "Action: Cancel Add Table".to_string();
|
*command_message = "Action: Cancel Add Table".to_string();
|
||||||
// TODO: Implement logic to navigate back (e.g., update AppView history)
|
// TODO: Implement logic
|
||||||
// Maybe show a confirmation dialog if there are unsaved changes
|
|
||||||
// buffer_state.go_back(); // Example call
|
|
||||||
}
|
}
|
||||||
// Selecting input fields usually means entering Edit mode (handled elsewhere)
|
_ => { // Input fields
|
||||||
// Selecting tables might mean focusing on them for editing/deletion (TODO)
|
|
||||||
AddTableFocus::ColumnsTable => {
|
|
||||||
if let Some(index) = add_table_state.column_table_state.selected() {
|
|
||||||
*command_message = format!("Selected column index {}", index);
|
|
||||||
// TODO: Add logic for editing/deleting selected column
|
|
||||||
} else {
|
|
||||||
*command_message = "No column selected".to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AddTableFocus::IndexesTable => {
|
|
||||||
if let Some(index) = add_table_state.index_table_state.selected() {
|
|
||||||
*command_message = format!("Selected index index {}", index);
|
|
||||||
// TODO: Add logic for editing/deleting selected index
|
|
||||||
} else {
|
|
||||||
*command_message = "No index selected".to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AddTableFocus::LinksTable => {
|
|
||||||
if let Some(index) = add_table_state.link_table_state.selected() {
|
|
||||||
*command_message = format!("Selected link index {}", index);
|
|
||||||
// TODO: Add logic for editing/deleting selected link
|
|
||||||
} else {
|
|
||||||
*command_message = "No link selected".to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
// For InputTableName, InputColumnName, InputColumnType,
|
|
||||||
// the main event loop should handle 'select' by potentially
|
|
||||||
// switching to Edit mode if not already in it.
|
|
||||||
// We don't need specific logic here for that.
|
|
||||||
*command_message = format!("Select on {:?}", current_focus);
|
*command_message = format!("Select on {:?}", current_focus);
|
||||||
handled = false; // Let main loop handle edit mode toggle maybe
|
handled = false; // Let main loop handle edit mode toggle maybe
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Keep handled = true for select actions unless specifically set to false
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Other General Keys (Ignore for add_table nav) ---
|
// --- Other General Keys ---
|
||||||
Some("toggle_sidebar") | Some("toggle_buffer_list") => {
|
Some("toggle_sidebar") | Some("toggle_buffer_list") => {
|
||||||
handled = false; // Let global handler manage these
|
handled = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- No matching action ---
|
// --- No matching action ---
|
||||||
_ => handled = false, // Event not handled by add_table navigation
|
_ => handled = false,
|
||||||
}
|
}
|
||||||
|
|
||||||
// If focus changed TO a table, select the first row if nothing is selected
|
// Update focus state if it changed and was handled
|
||||||
if handled && current_focus != add_table_state.current_focus {
|
if handled && current_focus != new_focus {
|
||||||
match add_table_state.current_focus {
|
add_table_state.current_focus = new_focus;
|
||||||
AddTableFocus::ColumnsTable if add_table_state.column_table_state.selected().is_none() && !add_table_state.columns.is_empty() => {
|
// Avoid overwriting specific messages set during 'select' handling
|
||||||
add_table_state.column_table_state.select(Some(0));
|
if command_message.is_empty() || command_message.starts_with("Focus set to") {
|
||||||
}
|
*command_message = format!("Focus set to {:?}", add_table_state.current_focus);
|
||||||
AddTableFocus::IndexesTable if add_table_state.index_table_state.selected().is_none() && !add_table_state.indexes.is_empty() => {
|
|
||||||
add_table_state.index_table_state.select(Some(0));
|
|
||||||
}
|
|
||||||
AddTableFocus::LinksTable if add_table_state.link_table_state.selected().is_none() && !add_table_state.links.is_empty() => {
|
|
||||||
add_table_state.link_table_state.select(Some(0));
|
|
||||||
}
|
|
||||||
_ => {} // No action needed for other focus states
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
}
|
}
|
||||||
|
|
||||||
handled
|
handled
|
||||||
@@ -217,21 +322,20 @@ pub fn handle_add_table_navigation(
|
|||||||
// Helper function for navigating up within a table state
|
// Helper function for navigating up within a table state
|
||||||
// Returns true if navigation happened within the table, false if it reached the top
|
// 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 {
|
fn navigate_table_up(table_state: &mut TableState, item_count: usize) -> bool {
|
||||||
if item_count == 0 { return false; } // Cannot navigate empty table
|
if item_count == 0 { return false; }
|
||||||
let current_selection = table_state.selected();
|
let current_selection = table_state.selected();
|
||||||
match current_selection {
|
match current_selection {
|
||||||
Some(index) => {
|
Some(index) => {
|
||||||
if index > 0 {
|
if index > 0 {
|
||||||
table_state.select(Some(index - 1));
|
table_state.select(Some(index - 1));
|
||||||
true // Moved up within table
|
true // Navigation happened
|
||||||
} else {
|
} else {
|
||||||
false // Was at the top
|
false // Was at the top
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => { // No item selected, select the last one
|
||||||
// If nothing selected, moving up could select the last item
|
|
||||||
table_state.select(Some(item_count - 1));
|
table_state.select(Some(item_count - 1));
|
||||||
true
|
true // Navigation happened (selection set)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -239,21 +343,20 @@ fn navigate_table_up(table_state: &mut TableState, item_count: usize) -> bool {
|
|||||||
// Helper function for navigating down within a table state
|
// Helper function for navigating down within a table state
|
||||||
// Returns true if navigation happened within the table, false if it reached the bottom
|
// 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 {
|
fn navigate_table_down(table_state: &mut TableState, item_count: usize) -> bool {
|
||||||
if item_count == 0 { return false; } // Cannot navigate empty table
|
if item_count == 0 { return false; }
|
||||||
let current_selection = table_state.selected();
|
let current_selection = table_state.selected();
|
||||||
match current_selection {
|
match current_selection {
|
||||||
Some(index) => {
|
Some(index) => {
|
||||||
if index < item_count - 1 {
|
if index < item_count - 1 {
|
||||||
table_state.select(Some(index + 1));
|
table_state.select(Some(index + 1));
|
||||||
true // Moved down within table
|
true // Navigation happened
|
||||||
} else {
|
} else {
|
||||||
false // Was at the bottom
|
false // Was at the bottom
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => { // No item selected, select the first one
|
||||||
// If nothing selected, moving down could select the first item
|
|
||||||
table_state.select(Some(0));
|
table_state.select(Some(0));
|
||||||
true
|
true // Navigation happened (selection set)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,17 @@ use crate::state::{
|
|||||||
app::state::AppState,
|
app::state::AppState,
|
||||||
pages::admin::{AdminFocus, AdminState},
|
pages::admin::{AdminFocus, AdminState},
|
||||||
};
|
};
|
||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
use crossterm::event::KeyEvent;
|
||||||
use crate::state::app::buffer::AppView;
|
use crate::state::app::buffer::AppView;
|
||||||
use crate::state::app::buffer::BufferState;
|
use crate::state::app::buffer::BufferState;
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
|
|
||||||
/// Handles navigation events specifically for the Admin Panel view.
|
/// Handles navigation events specifically for the Admin Panel view.
|
||||||
/// Returns true if the event was handled, false otherwise.
|
/// Returns true if the event was handled, false otherwise.
|
||||||
pub fn handle_admin_navigation(
|
pub fn handle_admin_navigation(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
app_state: &AppState,
|
app_state: &mut AppState,
|
||||||
admin_state: &mut AdminState,
|
admin_state: &mut AdminState,
|
||||||
buffer_state: &mut BufferState,
|
buffer_state: &mut BufferState,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
@@ -160,8 +161,37 @@ pub fn handle_admin_navigation(
|
|||||||
// TODO: Trigger action for Button 1
|
// TODO: Trigger action for Button 1
|
||||||
}
|
}
|
||||||
AdminFocus::Button2 => {
|
AdminFocus::Button2 => {
|
||||||
buffer_state.update_history(AppView::AddTable);
|
// --- Prepare AddTableState based on persistent selections ---
|
||||||
*command_message = "Navigating to Add Table page...".to_string();
|
if let Some(p_idx) = admin_state.selected_profile_index {
|
||||||
|
if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
|
||||||
|
let selected_profile_name = profile.name.clone();
|
||||||
|
|
||||||
|
|
||||||
|
// Create and populate the new AddTableState
|
||||||
|
let new_add_table_state = AddTableState {
|
||||||
|
profile_name: selected_profile_name,
|
||||||
|
// Reset other fields to defaults for a fresh start
|
||||||
|
..AddTableState::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Assign the prepared state
|
||||||
|
admin_state.add_table_state = new_add_table_state;
|
||||||
|
|
||||||
|
// Switch view
|
||||||
|
buffer_state.update_history(AppView::AddTable);
|
||||||
|
app_state.ui.focus_outside_canvas = false;
|
||||||
|
*command_message = format!(
|
||||||
|
"Navigating to Add Table for profile '{}'...",
|
||||||
|
admin_state.add_table_state.profile_name
|
||||||
|
);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
*command_message = "Error: Selected profile index out of bounds.".to_string();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*command_message = "Please select a profile ([*]) first.".to_string();
|
||||||
|
}
|
||||||
|
// --- End preparation ---
|
||||||
}
|
}
|
||||||
AdminFocus::Button3 => {
|
AdminFocus::Button3 => {
|
||||||
*command_message = "Action: Change Table (Not Implemented)".to_string();
|
*command_message = "Action: Change Table (Not Implemented)".to_string();
|
||||||
|
|||||||
@@ -2,3 +2,4 @@
|
|||||||
|
|
||||||
pub mod auth_ro;
|
pub mod auth_ro;
|
||||||
pub mod form_ro;
|
pub mod form_ro;
|
||||||
|
pub mod add_table_ro;
|
||||||
|
|||||||
244
client/src/functions/modes/read_only/add_table_ro.rs
Normal file
244
client/src/functions/modes/read_only/add_table_ro.rs
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
// src/functions/modes/read_only/add_table_ro.rs
|
||||||
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
|
use crate::state::pages::canvas_state::CanvasState; // Use trait for common actions
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
// Re-use word navigation helpers if they are public or move them to a common module
|
||||||
|
// For now, duplicating them here for simplicity. Consider refactoring later.
|
||||||
|
#[derive(PartialEq)]
|
||||||
|
enum CharType {
|
||||||
|
Whitespace,
|
||||||
|
Alphanumeric,
|
||||||
|
Punctuation,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_char_type(c: char) -> CharType {
|
||||||
|
if c.is_whitespace() { CharType::Whitespace }
|
||||||
|
else if c.is_alphanumeric() { CharType::Alphanumeric }
|
||||||
|
else { CharType::Punctuation }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 || current_pos >= len { return len; }
|
||||||
|
let mut pos = current_pos;
|
||||||
|
let initial_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == initial_type { pos += 1; }
|
||||||
|
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace { pos += 1; }
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
let len = chars.len();
|
||||||
|
if len == 0 { return 0; }
|
||||||
|
let mut pos = current_pos.min(len - 1);
|
||||||
|
if get_char_type(chars[pos]) == CharType::Whitespace {
|
||||||
|
pos = find_next_word_start(text, pos);
|
||||||
|
}
|
||||||
|
if pos >= len { return len.saturating_sub(1); }
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos < len && get_char_type(chars[pos]) == word_type { pos += 1; }
|
||||||
|
pos.saturating_sub(1).min(len.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
|
||||||
|
let chars: Vec<char> = text.chars().collect();
|
||||||
|
if chars.is_empty() || current_pos == 0 { return 0; }
|
||||||
|
let mut pos = current_pos.saturating_sub(1);
|
||||||
|
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace { pos -= 1; }
|
||||||
|
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace { return 0; }
|
||||||
|
let word_type = get_char_type(chars[pos]);
|
||||||
|
while pos > 0 && get_char_type(chars[pos - 1]) == word_type { pos -= 1; }
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: find_prev_word_end might need adjustments based on desired behavior.
|
||||||
|
// This version finds the end of the word *before* the previous word start.
|
||||||
|
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
|
let prev_start = find_prev_word_start(text, current_pos);
|
||||||
|
if prev_start == 0 { return 0; }
|
||||||
|
// Find the end of the word that starts at prev_start - 1
|
||||||
|
find_word_end(text, prev_start.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Executes read-only actions for the AddTable view canvas.
|
||||||
|
pub async fn execute_action(
|
||||||
|
action: &str,
|
||||||
|
app_state: &mut AppState, // Needed for focus_outside_canvas
|
||||||
|
state: &mut AddTableState,
|
||||||
|
ideal_cursor_column: &mut usize,
|
||||||
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
|
command_message: &mut String, // Keep for potential messages
|
||||||
|
) -> Result<String> {
|
||||||
|
// Use the CanvasState trait methods implemented for AddTableState
|
||||||
|
match action {
|
||||||
|
"move_up" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||||
|
let current_field = state.current_field(); // Gets the index (0, 1, or 2)
|
||||||
|
|
||||||
|
if current_field > 0 {
|
||||||
|
// This handles moving from field 2 -> 1, or 1 -> 0
|
||||||
|
let new_field = current_field - 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
// ... (rest of the logic to set cursor position) ...
|
||||||
|
} else {
|
||||||
|
// --- THIS IS WHERE THE FIX GOES ---
|
||||||
|
// current_field is 0 (InputTableName), and user pressed Up.
|
||||||
|
// We need to move focus *outside* the canvas.
|
||||||
|
|
||||||
|
// Set the flag to indicate focus is leaving the canvas
|
||||||
|
app_state.ui.focus_outside_canvas = true;
|
||||||
|
|
||||||
|
// Decide which element gets focus. Based on your layout and the
|
||||||
|
// downward navigation (CancelButton wraps to InputTableName),
|
||||||
|
// moving up from InputTableName should likely go to CancelButton.
|
||||||
|
state.current_focus = crate::state::pages::add_table::AddTableFocus::CancelButton;
|
||||||
|
|
||||||
|
// Reset the sequence tracker as the action is complete
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
|
||||||
|
// Return a message indicating the focus change
|
||||||
|
return Ok("Focus moved above canvas".to_string());
|
||||||
|
// --- END FIX ---
|
||||||
|
}
|
||||||
|
// If we moved within the canvas (e.g., 1 -> 0), return empty string
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_down" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields == 0 { return Ok("No fields.".to_string()); }
|
||||||
|
let current_field = state.current_field();
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
|
||||||
|
if current_field < last_field_index {
|
||||||
|
let new_field = current_field + 1;
|
||||||
|
state.set_current_field(new_field);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = current_input.len(); // Allow cursor at end
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
} else {
|
||||||
|
// Move focus outside canvas when moving down from the last field
|
||||||
|
app_state.ui.focus_outside_canvas = true;
|
||||||
|
// Set focus to the first element outside canvas (AddColumnButton)
|
||||||
|
state.current_focus = crate::state::pages::add_table::AddTableFocus::AddColumnButton;
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
return Ok("Focus moved below canvas".to_string());
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_first_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
if AddTableState::INPUT_FIELD_COUNT > 0 {
|
||||||
|
state.set_current_field(0);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = current_input.len();
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos; // Update ideal column
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_last_line" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
let num_fields = AddTableState::INPUT_FIELD_COUNT;
|
||||||
|
if num_fields > 0 {
|
||||||
|
let last_field_index = num_fields - 1;
|
||||||
|
state.set_current_field(last_field_index);
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let max_cursor_pos = current_input.len();
|
||||||
|
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos; // Update ideal column
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_left" => {
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = current_pos.saturating_sub(1);
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_right" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
// Allow moving cursor one position past the end
|
||||||
|
if current_pos < current_input.len() {
|
||||||
|
let new_pos = current_pos + 1;
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
}
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_next" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = find_next_word_start(current_input, state.current_cursor_pos());
|
||||||
|
let final_pos = new_pos.min(current_input.len()); // Allow cursor at end
|
||||||
|
state.set_current_cursor_pos(final_pos);
|
||||||
|
*ideal_cursor_column = final_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let current_pos = state.current_cursor_pos();
|
||||||
|
let new_pos = find_word_end(current_input, current_pos);
|
||||||
|
// If find_word_end returns current_pos, try starting search from next char
|
||||||
|
let final_pos = if new_pos == current_pos && current_pos < current_input.len() {
|
||||||
|
find_word_end(current_input, current_pos + 1)
|
||||||
|
} else {
|
||||||
|
new_pos
|
||||||
|
};
|
||||||
|
let max_valid_index = current_input.len(); // Allow cursor at end
|
||||||
|
let clamped_pos = final_pos.min(max_valid_index);
|
||||||
|
state.set_current_cursor_pos(clamped_pos);
|
||||||
|
*ideal_cursor_column = clamped_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = find_prev_word_start(current_input, state.current_cursor_pos());
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_word_end_prev" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = find_prev_word_end(current_input, state.current_cursor_pos());
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_start" => {
|
||||||
|
state.set_current_cursor_pos(0);
|
||||||
|
*ideal_cursor_column = 0;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
"move_line_end" => {
|
||||||
|
let current_input = state.get_current_input();
|
||||||
|
let new_pos = current_input.len(); // Allow cursor at end
|
||||||
|
state.set_current_cursor_pos(new_pos);
|
||||||
|
*ideal_cursor_column = new_pos;
|
||||||
|
Ok("".to_string())
|
||||||
|
}
|
||||||
|
// Actions handled by main event loop (mode changes)
|
||||||
|
"enter_edit_mode_before" | "enter_edit_mode_after" | "enter_command_mode" | "exit_highlight_mode" => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
Ok("Mode change handled by main loop".to_string())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
key_sequence_tracker.reset();
|
||||||
|
command_message.clear(); // Clear message for unhandled actions
|
||||||
|
Ok(format!("Unknown read-only action: {}", action))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use std::error::Error;
|
use anyhow::Result;
|
||||||
|
|
||||||
#[derive(PartialEq)]
|
#[derive(PartialEq)]
|
||||||
enum CharType {
|
enum CharType {
|
||||||
@@ -19,7 +19,7 @@ pub async fn execute_action<S: CanvasState>(
|
|||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
) -> Result<String, Box<dyn Error>> {
|
) -> Result<String> {
|
||||||
match action {
|
match action {
|
||||||
"previous_entry" | "next_entry" => {
|
"previous_entry" | "next_entry" => {
|
||||||
key_sequence_tracker.reset();
|
key_sequence_tracker.reset();
|
||||||
@@ -252,28 +252,6 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
|||||||
pos
|
pos
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let next_start = find_next_word_start(text, current_pos);
|
|
||||||
|
|
||||||
if next_start >= chars.len() {
|
|
||||||
return chars.len().saturating_sub(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = next_start;
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
let chars: Vec<char> = text.chars().collect();
|
let chars: Vec<char> = text.chars().collect();
|
||||||
let len = chars.len();
|
let len = chars.len();
|
||||||
@@ -282,8 +260,6 @@ fn find_word_end(text: &str, current_pos: usize) -> usize {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut pos = current_pos.min(len - 1);
|
let mut pos = current_pos.min(len - 1);
|
||||||
let original_pos = pos;
|
|
||||||
|
|
||||||
let current_type = get_char_type(chars[pos]);
|
let current_type = get_char_type(chars[pos]);
|
||||||
if current_type != CharType::Whitespace {
|
if current_type != CharType::Whitespace {
|
||||||
while pos < len && get_char_type(chars[pos]) == current_type {
|
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use std::error::Error;
|
use anyhow::Result;
|
||||||
|
|
||||||
#[derive(PartialEq)]
|
#[derive(PartialEq)]
|
||||||
enum CharType {
|
enum CharType {
|
||||||
@@ -17,7 +17,7 @@ pub async fn execute_action<S: CanvasState>(
|
|||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
) -> Result<String, Box<dyn Error>> {
|
) -> Result<String> {
|
||||||
match action {
|
match action {
|
||||||
"previous_entry" | "next_entry" => {
|
"previous_entry" | "next_entry" => {
|
||||||
key_sequence_tracker.reset();
|
key_sequence_tracker.reset();
|
||||||
@@ -238,28 +238,6 @@ fn find_next_word_start(text: &str, current_pos: usize) -> usize {
|
|||||||
pos
|
pos
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
|
|
||||||
let chars: Vec<char> = text.chars().collect();
|
|
||||||
if chars.is_empty() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let next_start = find_next_word_start(text, current_pos);
|
|
||||||
|
|
||||||
if next_start >= chars.len() {
|
|
||||||
return chars.len().saturating_sub(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pos = next_start;
|
|
||||||
let word_type = get_char_type(chars[pos]);
|
|
||||||
|
|
||||||
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
fn find_word_end(text: &str, current_pos: usize) -> usize {
|
||||||
let chars: Vec<char> = text.chars().collect();
|
let chars: Vec<char> = text.chars().collect();
|
||||||
let len = chars.len();
|
let len = chars.len();
|
||||||
@@ -268,8 +246,6 @@ fn find_word_end(text: &str, current_pos: usize) -> usize {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut pos = current_pos.min(len - 1);
|
let mut pos = current_pos.min(len - 1);
|
||||||
let original_pos = pos;
|
|
||||||
|
|
||||||
let current_type = get_char_type(chars[pos]);
|
let current_type = get_char_type(chars[pos]);
|
||||||
if current_type != CharType::Whitespace {
|
if current_type != CharType::Whitespace {
|
||||||
while pos < len && get_char_type(chars[pos]) == current_type {
|
while pos < len && get_char_type(chars[pos]) == current_type {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// client/src/main.rs
|
// client/src/main.rs
|
||||||
use client::run_ui;
|
use client::run_ui;
|
||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
use std::error::Error;
|
use anyhow::Result;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn Error>> {
|
async fn main() -> Result<()> {
|
||||||
dotenv().ok();
|
dotenv().ok();
|
||||||
run_ui().await
|
run_ui().await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ use crate::services::grpc_client::GrpcClient;
|
|||||||
use crate::services::auth::AuthClient;
|
use crate::services::auth::AuthClient;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crate::tui::functions::common::form::SaveOutcome;
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
use crate::tui::functions::common::{
|
use crate::tui::functions::common::{
|
||||||
form::{save as form_save, revert as form_revert},
|
form::{save as form_save, revert as form_revert},
|
||||||
login::{save as login_save, revert as login_revert},
|
login::{save as login_save, revert as login_revert},
|
||||||
register::{save as register_save, revert as register_revert},
|
register::{revert as register_revert},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn handle_core_action(
|
pub async fn handle_core_action(
|
||||||
@@ -25,14 +26,11 @@ pub async fn handle_core_action(
|
|||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome> {
|
||||||
match action {
|
match action {
|
||||||
"save" => {
|
"save" => {
|
||||||
if app_state.ui.show_login {
|
if app_state.ui.show_login {
|
||||||
let message = login_save(auth_state, login_state, auth_client, app_state).await?;
|
let message = login_save(auth_state, login_state, auth_client, app_state).await.context("Login save action failed")?;
|
||||||
Ok(EventOutcome::Ok(message))
|
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
let message = register_save(register_state, auth_client, app_state).await?;
|
|
||||||
Ok(EventOutcome::Ok(message))
|
Ok(EventOutcome::Ok(message))
|
||||||
} else {
|
} else {
|
||||||
let save_outcome = form_save(
|
let save_outcome = form_save(
|
||||||
@@ -40,7 +38,7 @@ pub async fn handle_core_action(
|
|||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await?;
|
).await.context("Register save action failed")?;
|
||||||
let message = match save_outcome {
|
let message = match save_outcome {
|
||||||
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
|
||||||
@@ -55,9 +53,7 @@ pub async fn handle_core_action(
|
|||||||
},
|
},
|
||||||
"save_and_quit" => {
|
"save_and_quit" => {
|
||||||
let message = if app_state.ui.show_login {
|
let message = if app_state.ui.show_login {
|
||||||
login_save(auth_state, login_state, auth_client, app_state).await?
|
login_save(auth_state, login_state, auth_client, app_state).await.context("Login save n quit action failed")?
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
register_save(register_state, auth_client, app_state).await?
|
|
||||||
} else {
|
} else {
|
||||||
let save_outcome = form_save(
|
let save_outcome = form_save(
|
||||||
form_state,
|
form_state,
|
||||||
@@ -87,7 +83,7 @@ pub async fn handle_core_action(
|
|||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
).await?;
|
).await.context("Form revert x action failed")?;
|
||||||
Ok(EventOutcome::Ok(message))
|
Ok(EventOutcome::Ok(message))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
// src/modes/canvas/edit.rs
|
// src/modes/canvas/edit.rs
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::{auth::{LoginState, RegisterState}, canvas_state::CanvasState};
|
use crate::state::pages::{
|
||||||
|
auth::{LoginState, RegisterState},
|
||||||
|
canvas_state::CanvasState,
|
||||||
|
};
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crate::functions::modes::edit::{auth_e, form_e};
|
use crate::functions::modes::edit::{auth_e, form_e};
|
||||||
|
use crate::functions::modes::edit::add_table_e;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
|
use anyhow::Result;
|
||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
// Removed duplicate/unused imports
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum EditEventOutcome {
|
pub enum EditEventOutcome {
|
||||||
@@ -21,214 +26,257 @@ pub async fn handle_edit_event(
|
|||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
register_state: &mut RegisterState,
|
register_state: &mut RegisterState,
|
||||||
|
add_table_state: &mut AddTableState,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
// command_message: &mut String, // Removed as messages are returned
|
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &AppState,
|
app_state: &AppState,
|
||||||
) -> Result<EditEventOutcome, Box<dyn std::error::Error>> {
|
) -> 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(
|
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
|
||||||
&config.keybindings.global,
|
&config.keybindings.global,
|
||||||
key.code,
|
key.code,
|
||||||
key.modifiers
|
key.modifiers,
|
||||||
) {
|
) {
|
||||||
return Ok(EditEventOutcome::Message("Switching to Command Mode...".to_string()));
|
return Ok(EditEventOutcome::Message(
|
||||||
|
"Command mode entry handled globally.".to_string(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Common actions (save/revert)
|
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(
|
if let Some(action) = config.get_action_for_key_in_mode(
|
||||||
&config.keybindings.common,
|
&config.keybindings.common,
|
||||||
key.code,
|
key.code,
|
||||||
key.modifiers
|
key.modifiers,
|
||||||
) {
|
).as_deref() {
|
||||||
if matches!(action, "save" | "revert") {
|
if matches!(action, "save" | "revert") {
|
||||||
// Ensure all branches result in Result<String, Error> before the final Ok(...) wrap
|
|
||||||
let message_string: String = if app_state.ui.show_login {
|
let message_string: String = if app_state.ui.show_login {
|
||||||
auth_e::execute_common_action(
|
auth_e::execute_common_action(
|
||||||
action,
|
action,
|
||||||
login_state,
|
login_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count
|
total_count,
|
||||||
).await? // Results in String on success
|
)
|
||||||
|
.await?
|
||||||
} else if app_state.ui.show_register {
|
} else if app_state.ui.show_register {
|
||||||
auth_e::execute_common_action(
|
auth_e::execute_common_action(
|
||||||
action,
|
action,
|
||||||
register_state,
|
register_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count
|
total_count,
|
||||||
).await? // Results in String on success
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_add_table {
|
||||||
|
format!(
|
||||||
|
"Action '{}' not fully implemented for Add Table view here.",
|
||||||
|
action
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
let outcome = form_e::execute_common_action(
|
let outcome = form_e::execute_common_action(
|
||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
current_position,
|
||||||
total_count
|
total_count,
|
||||||
).await?; // This returns EventOutcome on success
|
)
|
||||||
|
.await?;
|
||||||
// Extract the message string from the EventOutcome
|
|
||||||
match outcome {
|
match outcome {
|
||||||
EventOutcome::Ok(msg) => msg,
|
EventOutcome::Ok(msg) => msg,
|
||||||
EventOutcome::DataSaved(_, msg) => msg,
|
EventOutcome::DataSaved(_, msg) => msg,
|
||||||
_ => format!("Unexpected outcome from common action: {:?}", outcome),
|
_ => format!(
|
||||||
|
"Unexpected outcome from common action: {:?}",
|
||||||
|
outcome
|
||||||
|
),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Wrap the resulting String message
|
|
||||||
return Ok(EditEventOutcome::Message(message_string));
|
return Ok(EditEventOutcome::Message(message_string));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit-specific actions
|
// Edit-specific actions
|
||||||
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
|
if let Some(action) =
|
||||||
|
config.get_edit_action_for_key(key.code, key.modifiers)
|
||||||
|
.as_deref() {
|
||||||
|
// Handle enter_decider first
|
||||||
|
if action == "enter_decider" {
|
||||||
|
let effective_action = if app_state.ui.show_register
|
||||||
|
&& register_state.in_suggestion_mode
|
||||||
|
&& register_state.current_field() == 4 {
|
||||||
|
"select_suggestion"
|
||||||
|
} else {
|
||||||
|
"next_field"
|
||||||
|
};
|
||||||
|
|
||||||
|
let msg = if app_state.ui.show_login {
|
||||||
|
auth_e::execute_edit_action(
|
||||||
|
effective_action,
|
||||||
|
key,
|
||||||
|
login_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_add_table {
|
||||||
|
add_table_e::execute_edit_action(
|
||||||
|
effective_action,
|
||||||
|
key,
|
||||||
|
add_table_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?
|
||||||
|
};
|
||||||
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
|
}
|
||||||
|
|
||||||
if action == "exit" {
|
if action == "exit" {
|
||||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||||
// Call the action, get Result<String, Error>
|
|
||||||
let msg = auth_e::execute_edit_action(
|
let msg = auth_e::execute_edit_action(
|
||||||
"exit_suggestion_mode",
|
"exit_suggestion_mode",
|
||||||
key,
|
key,
|
||||||
register_state,
|
register_state,
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
current_position,
|
.await?;
|
||||||
total_count,
|
|
||||||
).await?; // Results in String on success
|
|
||||||
// Wrap the String message
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
} else {
|
} else {
|
||||||
// Signal exit
|
|
||||||
return Ok(EditEventOutcome::ExitEditMode);
|
return Ok(EditEventOutcome::ExitEditMode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Special handling for role field suggestions
|
// Special handling for role field suggestions (Register view only)
|
||||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||||
if !register_state.in_suggestion_mode && key.code == KeyCode::Tab && key.modifiers == KeyModifiers::NONE {
|
if !register_state.in_suggestion_mode
|
||||||
|
&& key.code == KeyCode::Tab
|
||||||
|
&& key.modifiers == KeyModifiers::NONE
|
||||||
|
{
|
||||||
register_state.update_role_suggestions();
|
register_state.update_role_suggestions();
|
||||||
if !register_state.role_suggestions.is_empty() {
|
if !register_state.role_suggestions.is_empty() {
|
||||||
register_state.in_suggestion_mode = true;
|
register_state.in_suggestion_mode = true;
|
||||||
register_state.selected_suggestion_index = Some(0);
|
register_state.selected_suggestion_index = Some(0);
|
||||||
return Ok(EditEventOutcome::Message("Suggestions shown".to_string()));
|
return Ok(EditEventOutcome::Message(
|
||||||
} else { // Added else here for clarity
|
"Suggestions shown".to_string(),
|
||||||
return Ok(EditEventOutcome::Message("No suggestions available".to_string()));
|
));
|
||||||
|
} else {
|
||||||
|
return Ok(EditEventOutcome::Message(
|
||||||
|
"No suggestions available".to_string(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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?;
|
||||||
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute other edit actions
|
// Execute other edit actions based on the current view
|
||||||
let msg = if app_state.ui.show_login {
|
let msg = if app_state.ui.show_login {
|
||||||
auth_e::execute_edit_action(
|
auth_e::execute_edit_action(
|
||||||
action,
|
action,
|
||||||
key,
|
key,
|
||||||
login_state,
|
login_state,
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
current_position,
|
.await?
|
||||||
total_count
|
} else if app_state.ui.show_add_table {
|
||||||
).await? // Results in String
|
add_table_e::execute_edit_action(
|
||||||
|
action,
|
||||||
|
key,
|
||||||
|
add_table_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
} else if app_state.ui.show_register {
|
} else if app_state.ui.show_register {
|
||||||
auth_e::execute_edit_action(
|
auth_e::execute_edit_action(
|
||||||
action,
|
action,
|
||||||
key,
|
key,
|
||||||
register_state,
|
register_state,
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
current_position,
|
.await?
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
} else {
|
} else {
|
||||||
form_e::execute_edit_action(
|
form_e::execute_edit_action(
|
||||||
action,
|
action,
|
||||||
key,
|
key,
|
||||||
form_state,
|
form_state,
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
grpc_client,
|
)
|
||||||
current_position,
|
.await?
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
};
|
};
|
||||||
// Wrap the resulting String message
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Character insertion
|
// --- Character insertion ---
|
||||||
if let KeyCode::Char(_) = key.code {
|
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
||||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
register_state.in_suggestion_mode = false;
|
||||||
register_state.in_suggestion_mode = false;
|
register_state.show_role_suggestions = false;
|
||||||
register_state.show_role_suggestions = false;
|
register_state.selected_suggestion_index = None;
|
||||||
register_state.selected_suggestion_index = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute insert_char action
|
|
||||||
let msg = if app_state.ui.show_login {
|
|
||||||
auth_e::execute_edit_action(
|
|
||||||
"insert_char",
|
|
||||||
key,
|
|
||||||
login_state,
|
|
||||||
ideal_cursor_column,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
auth_e::execute_edit_action(
|
|
||||||
"insert_char",
|
|
||||||
key,
|
|
||||||
register_state,
|
|
||||||
ideal_cursor_column,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
} else {
|
|
||||||
form_e::execute_edit_action(
|
|
||||||
"insert_char",
|
|
||||||
key,
|
|
||||||
form_state,
|
|
||||||
ideal_cursor_column,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
};
|
|
||||||
// Wrap the resulting String message
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle Backspace/Delete
|
let msg = if app_state.ui.show_login {
|
||||||
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
|
auth_e::execute_edit_action(
|
||||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
"insert_char",
|
||||||
register_state.in_suggestion_mode = false;
|
key,
|
||||||
register_state.show_role_suggestions = false;
|
login_state,
|
||||||
register_state.selected_suggestion_index = None;
|
ideal_cursor_column,
|
||||||
}
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_add_table {
|
||||||
|
add_table_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
add_table_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_register {
|
||||||
|
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?
|
||||||
|
};
|
||||||
|
|
||||||
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
|
if app_state.ui.show_register && register_state.current_field() == 4 {
|
||||||
// Ensure both branches result in a String *before* wrapping
|
register_state.update_role_suggestions();
|
||||||
let result_msg: String = if app_state.ui.show_register {
|
|
||||||
auth_e::execute_edit_action(
|
|
||||||
action_str,
|
|
||||||
key,
|
|
||||||
register_state,
|
|
||||||
ideal_cursor_column,
|
|
||||||
grpc_client,
|
|
||||||
current_position,
|
|
||||||
total_count
|
|
||||||
).await? // Results in String
|
|
||||||
} else {
|
|
||||||
// Return String directly, not Ok(String)
|
|
||||||
"Action not applicable here".to_string()
|
|
||||||
}; // Semicolon here ends the if/else expression
|
|
||||||
|
|
||||||
// Wrap the resulting String message
|
|
||||||
return Ok(EditEventOutcome::Message(result_msg));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default return if no other handler matched
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
Ok(EditEventOutcome::Message("".to_string()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ use crate::services::grpc_client::GrpcClient;
|
|||||||
use crate::state::pages::{canvas_state::CanvasState, auth::RegisterState};
|
use crate::state::pages::{canvas_state::CanvasState, auth::RegisterState};
|
||||||
use crate::state::pages::auth::LoginState;
|
use crate::state::pages::auth::LoginState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use crate::functions::modes::read_only::{auth_ro, form_ro};
|
use crate::functions::modes::read_only::{auth_ro, form_ro, add_table_ro};
|
||||||
use crossterm::event::KeyEvent;
|
use crossterm::event::KeyEvent;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn handle_read_only_event(
|
pub async fn handle_read_only_event(
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
@@ -17,6 +19,7 @@ pub async fn handle_read_only_event(
|
|||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
register_state: &mut RegisterState,
|
register_state: &mut RegisterState,
|
||||||
|
add_table_state: &mut AddTableState,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
@@ -24,7 +27,7 @@ pub async fn handle_read_only_event(
|
|||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
edit_mode_cooldown: &mut bool,
|
edit_mode_cooldown: &mut bool,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String)> {
|
||||||
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
|
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
|
||||||
*edit_mode_cooldown = true;
|
*edit_mode_cooldown = true;
|
||||||
*command_message = "Entering Edit mode".to_string();
|
*command_message = "Entering Edit mode".to_string();
|
||||||
@@ -32,34 +35,17 @@ pub async fn handle_read_only_event(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
|
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
|
||||||
let (current_input, current_pos) = if app_state.ui.show_login { // Check Login first
|
// Determine target state to adjust cursor
|
||||||
(
|
let target_state: &mut dyn CanvasState = if app_state.ui.show_login { login_state }
|
||||||
login_state.get_current_input(),
|
else if app_state.ui.show_register { register_state }
|
||||||
login_state.current_cursor_pos(),
|
else if app_state.ui.show_add_table { add_table_state }
|
||||||
)
|
else { form_state };
|
||||||
} else if app_state.ui.show_register { // Then check Register
|
let current_input = target_state.get_current_input();
|
||||||
(
|
let current_pos = target_state.current_cursor_pos();
|
||||||
register_state.get_current_input(),
|
|
||||||
register_state.current_cursor_pos(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
(
|
|
||||||
form_state.get_current_input(),
|
|
||||||
form_state.current_cursor_pos(),
|
|
||||||
) // Default to Form
|
|
||||||
};
|
|
||||||
|
|
||||||
if !current_input.is_empty() && current_pos < current_input.len() {
|
if !current_input.is_empty() && current_pos < current_input.len() {
|
||||||
if app_state.ui.show_login {
|
target_state.set_current_cursor_pos(current_pos + 1);
|
||||||
login_state.set_current_cursor_pos(current_pos + 1);
|
*ideal_cursor_column = target_state.current_cursor_pos();
|
||||||
*ideal_cursor_column = login_state.current_cursor_pos();
|
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
register_state.set_current_cursor_pos(current_pos + 1);
|
|
||||||
*ideal_cursor_column = register_state.current_cursor_pos();
|
|
||||||
} else { // Default to Form
|
|
||||||
form_state.set_current_cursor_pos(current_pos + 1);
|
|
||||||
*ideal_cursor_column = form_state.current_cursor_pos();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
*edit_mode_cooldown = true;
|
*edit_mode_cooldown = true;
|
||||||
*command_message = "Entering Edit mode (after cursor)".to_string();
|
*command_message = "Entering Edit mode (after cursor)".to_string();
|
||||||
@@ -74,16 +60,12 @@ pub async fn handle_read_only_event(
|
|||||||
"previous_entry",
|
"previous_entry",
|
||||||
"next_entry",
|
"next_entry",
|
||||||
];
|
];
|
||||||
// Add context actions specific to register if needed, otherwise reuse login/form ones
|
|
||||||
const CONTEXT_ACTIONS_REGISTER: &[&str] = &[
|
|
||||||
// Add actions like "next_field", "prev_field" if handled differently than general read-only
|
|
||||||
];
|
|
||||||
|
|
||||||
if key.modifiers.is_empty() {
|
if key.modifiers.is_empty() {
|
||||||
key_sequence_tracker.add_key(key.code);
|
key_sequence_tracker.add_key(key.code);
|
||||||
let sequence = key_sequence_tracker.get_sequence();
|
let sequence = key_sequence_tracker.get_sequence();
|
||||||
|
|
||||||
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
|
if let Some(action) = config.matches_key_sequence_generalized(&sequence).as_deref() {
|
||||||
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
crate::tui::functions::form::handle_action(
|
crate::tui::functions::form::handle_action(
|
||||||
action,
|
action,
|
||||||
@@ -96,6 +78,15 @@ pub async fn handle_read_only_event(
|
|||||||
.await?
|
.await?
|
||||||
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
||||||
crate::tui::functions::login::handle_action(action).await?
|
crate::tui::functions::login::handle_action(action).await?
|
||||||
|
} else if app_state.ui.show_add_table {
|
||||||
|
add_table_ro::execute_action(
|
||||||
|
action,
|
||||||
|
app_state,
|
||||||
|
add_table_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
).await?
|
||||||
} else if app_state.ui.show_register{
|
} else if app_state.ui.show_register{
|
||||||
auth_ro::execute_action(
|
auth_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
@@ -134,7 +125,7 @@ pub async fn handle_read_only_event(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
|
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
|
||||||
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
|
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers).as_deref() {
|
||||||
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
crate::tui::functions::form::handle_action(
|
crate::tui::functions::form::handle_action(
|
||||||
action,
|
action,
|
||||||
@@ -147,7 +138,16 @@ pub async fn handle_read_only_event(
|
|||||||
.await?
|
.await?
|
||||||
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
||||||
crate::tui::functions::login::handle_action(action).await?
|
crate::tui::functions::login::handle_action(action).await?
|
||||||
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
|
} else if app_state.ui.show_add_table {
|
||||||
|
add_table_ro::execute_action(
|
||||||
|
action,
|
||||||
|
app_state,
|
||||||
|
add_table_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
).await?
|
||||||
|
} else if app_state.ui.show_register {
|
||||||
auth_ro::execute_action(
|
auth_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
app_state,
|
app_state,
|
||||||
@@ -184,7 +184,7 @@ pub async fn handle_read_only_event(
|
|||||||
} else {
|
} else {
|
||||||
key_sequence_tracker.reset();
|
key_sequence_tracker.reset();
|
||||||
|
|
||||||
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
|
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers).as_deref() {
|
||||||
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
|
||||||
crate::tui::functions::form::handle_action(
|
crate::tui::functions::form::handle_action(
|
||||||
action,
|
action,
|
||||||
@@ -195,9 +195,18 @@ pub async fn handle_read_only_event(
|
|||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
crate::tui::functions::login::handle_action(action).await?
|
crate::tui::functions::login::handle_action(action).await?
|
||||||
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
|
} else if app_state.ui.show_add_table {
|
||||||
|
add_table_ro::execute_action(
|
||||||
|
action,
|
||||||
|
app_state,
|
||||||
|
add_table_state,
|
||||||
|
ideal_cursor_column,
|
||||||
|
key_sequence_tracker,
|
||||||
|
command_message,
|
||||||
|
).await?
|
||||||
|
} else if app_state.ui.show_register {
|
||||||
auth_ro::execute_action(
|
auth_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
app_state,
|
app_state,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::tui::terminal::core::TerminalCore;
|
|||||||
use crate::tui::functions::common::form::{save, revert};
|
use crate::tui::functions::common::form::{save, revert};
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crate::tui::functions::common::form::SaveOutcome;
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
use std::error::Error;
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn handle_command_event(
|
pub async fn handle_command_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
@@ -26,7 +26,7 @@ pub async fn handle_command_event(
|
|||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<EventOutcome, Box<dyn Error>> {
|
) -> Result<EventOutcome> {
|
||||||
// Exit command mode (via configurable keybinding)
|
// Exit command mode (via configurable keybinding)
|
||||||
if config.is_exit_command_mode(key.code, key.modifiers) {
|
if config.is_exit_command_mode(key.code, key.modifiers) {
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
@@ -84,7 +84,7 @@ async fn process_command(
|
|||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<EventOutcome, Box<dyn Error>> {
|
) -> Result<EventOutcome> {
|
||||||
// Clone the trimmed command to avoid borrow issues
|
// Clone the trimmed command to avoid borrow issues
|
||||||
let command = command_input.trim().to_string();
|
let command = command_input.trim().to_string();
|
||||||
if command.is_empty() {
|
if command.is_empty() {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ use crate::tui::terminal::core::TerminalCore;
|
|||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
|
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub struct CommandHandler;
|
pub struct CommandHandler;
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ impl CommandHandler {
|
|||||||
form_state: &FormState,
|
form_state: &FormState,
|
||||||
login_state: &LoginState,
|
login_state: &LoginState,
|
||||||
register_state: &RegisterState,
|
register_state: &RegisterState,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String)> {
|
||||||
match action {
|
match action {
|
||||||
"quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
|
"quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
|
||||||
"force_quit" => self.handle_force_quit(terminal).await,
|
"force_quit" => self.handle_force_quit(terminal).await,
|
||||||
@@ -35,7 +36,7 @@ impl CommandHandler {
|
|||||||
form_state: &FormState,
|
form_state: &FormState,
|
||||||
login_state: &LoginState,
|
login_state: &LoginState,
|
||||||
register_state: &RegisterState,
|
register_state: &RegisterState,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String)> {
|
||||||
// Use actual unsaved changes state instead of is_saved flag
|
// Use actual unsaved changes state instead of is_saved flag
|
||||||
let has_unsaved = if app_state.ui.show_login {
|
let has_unsaved = if app_state.ui.show_login {
|
||||||
login_state.has_unsaved_changes()
|
login_state.has_unsaved_changes()
|
||||||
@@ -56,7 +57,7 @@ impl CommandHandler {
|
|||||||
async fn handle_force_quit(
|
async fn handle_force_quit(
|
||||||
&self,
|
&self,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String)> {
|
||||||
terminal.cleanup()?;
|
terminal.cleanup()?;
|
||||||
Ok((true, "Force exiting without saving.".into()))
|
Ok((true, "Force exiting without saving.".into()))
|
||||||
}
|
}
|
||||||
@@ -64,7 +65,7 @@ impl CommandHandler {
|
|||||||
async fn handle_save_quit(
|
async fn handle_save_quit(
|
||||||
&mut self,
|
&mut self,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
) -> Result<(bool, String)> {
|
||||||
terminal.cleanup()?;
|
terminal.cleanup()?;
|
||||||
Ok((true, "State saved. Exiting.".into()))
|
Ok((true, "State saved. Exiting.".into()))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ use crate::config::binds::config::Config;
|
|||||||
use crate::ui::handlers::context::DialogPurpose;
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use crate::state::app::buffer::BufferState;
|
use crate::state::app::buffer::BufferState;
|
||||||
use crate::state::pages::auth::AuthState;
|
use crate::state::pages::auth::{LoginState, RegisterState};
|
||||||
use crate::state::pages::auth::LoginState;
|
use crate::state::pages::admin::AdminState;
|
||||||
use crate::state::pages::auth::RegisterState;
|
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crate::tui::functions::common::{login, register};
|
use crate::tui::functions::common::{login, register};
|
||||||
|
use crate::tui::functions::common::add_table::handle_delete_selected_columns;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
/// Handles key events specifically when a dialog is active.
|
/// Handles key events specifically when a dialog is active.
|
||||||
/// Returns Some(Result<EventOutcome, Error>) if the event was handled (consumed),
|
/// Returns Some(Result<EventOutcome, Error>) if the event was handled (consumed),
|
||||||
@@ -18,11 +19,11 @@ pub async fn handle_dialog_event(
|
|||||||
event: &Event,
|
event: &Event,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
auth_state: &mut AuthState,
|
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
register_state: &mut RegisterState,
|
register_state: &mut RegisterState,
|
||||||
buffer_state: &mut BufferState,
|
buffer_state: &mut BufferState,
|
||||||
) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> {
|
admin_state: &mut AdminState,
|
||||||
|
) -> Option<Result<EventOutcome>> {
|
||||||
if let Event::Key(key) = event {
|
if let Event::Key(key) = event {
|
||||||
// Always allow Esc to dismiss
|
// Always allow Esc to dismiss
|
||||||
if key.code == KeyCode::Esc {
|
if key.code == KeyCode::Esc {
|
||||||
@@ -114,6 +115,20 @@ pub async fn handle_dialog_event(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
DialogPurpose::ConfirmDeleteColumns => {
|
||||||
|
match selected_index {
|
||||||
|
0 => { // "Confirm" button selected
|
||||||
|
let outcome_message = handle_delete_selected_columns(&mut admin_state.add_table_state);
|
||||||
|
app_state.hide_dialog();
|
||||||
|
return Some(Ok(EventOutcome::Ok(outcome_message)));
|
||||||
|
}
|
||||||
|
1 => { // "Cancel" button selected
|
||||||
|
app_state.hide_dialog();
|
||||||
|
return Some(Ok(EventOutcome::Ok("Deletion cancelled.".to_string())));
|
||||||
|
}
|
||||||
|
_ => { /* Handle unexpected index */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {} // Ignore other general actions when dialog is shown
|
_ => {} // Ignore other general actions when dialog is shown
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use crate::state::pages::admin::AdminState;
|
|||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::ui::handlers::context::UiContext;
|
use crate::ui::handlers::context::UiContext;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn handle_navigation_event(
|
pub async fn handle_navigation_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
@@ -24,7 +25,7 @@ pub async fn handle_navigation_event(
|
|||||||
command_mode: &mut bool,
|
command_mode: &mut bool,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome> {
|
||||||
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
||||||
match action {
|
match action {
|
||||||
"move_up" => {
|
"move_up" => {
|
||||||
|
|||||||
@@ -7,14 +7,11 @@ use crate::config::binds::config::Config;
|
|||||||
use crate::ui::handlers::rat_state::UiStateHandler;
|
use crate::ui::handlers::rat_state::UiStateHandler;
|
||||||
use crate::ui::handlers::context::UiContext;
|
use crate::ui::handlers::context::UiContext;
|
||||||
use crate::functions::common::buffer;
|
use crate::functions::common::buffer;
|
||||||
|
use anyhow::Result;
|
||||||
use crate::tui::{
|
use crate::tui::{
|
||||||
terminal::core::TerminalCore,
|
terminal::core::TerminalCore,
|
||||||
functions::{
|
functions::{
|
||||||
common::{
|
common::{form::SaveOutcome, login, register},
|
||||||
form::SaveOutcome,
|
|
||||||
login,
|
|
||||||
register,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{intro, admin},
|
{intro, admin},
|
||||||
};
|
};
|
||||||
@@ -36,11 +33,13 @@ use crate::modes::{
|
|||||||
common::{command_mode, commands::CommandHandler},
|
common::{command_mode, commands::CommandHandler},
|
||||||
handlers::mode_manager::{ModeManager, AppMode},
|
handlers::mode_manager::{ModeManager, AppMode},
|
||||||
canvas::{edit, read_only, common_mode},
|
canvas::{edit, read_only, common_mode},
|
||||||
highlight::highlight,
|
|
||||||
general::{navigation, dialog},
|
general::{navigation, dialog},
|
||||||
};
|
};
|
||||||
use crate::functions::modes::navigation::{admin_nav, add_table_nav};
|
use crate::functions::modes::navigation::{admin_nav, add_table_nav};
|
||||||
use crate::config::binds::key_sequences::KeySequenceTracker;
|
use crate::config::binds::key_sequences::KeySequenceTracker;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use crate::tui::functions::common::login::LoginResult;
|
||||||
|
use crate::tui::functions::common::register::RegisterResult;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum EventOutcome {
|
pub enum EventOutcome {
|
||||||
@@ -60,10 +59,15 @@ pub struct EventHandler {
|
|||||||
pub ideal_cursor_column: usize,
|
pub ideal_cursor_column: usize,
|
||||||
pub key_sequence_tracker: KeySequenceTracker,
|
pub key_sequence_tracker: KeySequenceTracker,
|
||||||
pub auth_client: AuthClient,
|
pub auth_client: AuthClient,
|
||||||
|
pub login_result_sender: mpsc::Sender<LoginResult>,
|
||||||
|
pub register_result_sender: mpsc::Sender<RegisterResult>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventHandler {
|
impl EventHandler {
|
||||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub async fn new(
|
||||||
|
login_result_sender: mpsc::Sender<LoginResult>,
|
||||||
|
register_result_sender: mpsc::Sender<RegisterResult>,
|
||||||
|
) -> Result<Self> {
|
||||||
Ok(EventHandler {
|
Ok(EventHandler {
|
||||||
command_mode: false,
|
command_mode: false,
|
||||||
command_input: String::new(),
|
command_input: String::new(),
|
||||||
@@ -74,6 +78,8 @@ impl EventHandler {
|
|||||||
ideal_cursor_column: 0,
|
ideal_cursor_column: 0,
|
||||||
key_sequence_tracker: KeySequenceTracker::new(800),
|
key_sequence_tracker: KeySequenceTracker::new(800),
|
||||||
auth_client: AuthClient::new().await?,
|
auth_client: AuthClient::new().await?,
|
||||||
|
login_result_sender,
|
||||||
|
register_result_sender,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +100,7 @@ impl EventHandler {
|
|||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome> {
|
||||||
let current_mode = ModeManager::derive_mode(app_state, self);
|
let current_mode = ModeManager::derive_mode(app_state, self);
|
||||||
app_state.update_mode(current_mode);
|
app_state.update_mode(current_mode);
|
||||||
|
|
||||||
@@ -115,7 +121,13 @@ impl EventHandler {
|
|||||||
|
|
||||||
if app_state.ui.dialog.dialog_show {
|
if app_state.ui.dialog.dialog_show {
|
||||||
if let Some(dialog_result) = dialog::handle_dialog_event(
|
if let Some(dialog_result) = dialog::handle_dialog_event(
|
||||||
&event, config, app_state, auth_state, login_state, register_state, buffer_state
|
&event,
|
||||||
|
config,
|
||||||
|
app_state,
|
||||||
|
login_state,
|
||||||
|
register_state,
|
||||||
|
buffer_state,
|
||||||
|
admin_state,
|
||||||
).await {
|
).await {
|
||||||
return dialog_result;
|
return dialog_result;
|
||||||
}
|
}
|
||||||
@@ -177,17 +189,15 @@ impl EventHandler {
|
|||||||
}
|
}
|
||||||
// --- Add Table Page Navigation ---
|
// --- Add Table Page Navigation ---
|
||||||
if app_state.ui.show_add_table {
|
if app_state.ui.show_add_table {
|
||||||
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
if add_table_nav::handle_add_table_navigation(
|
||||||
if add_table_nav::handle_add_table_navigation(
|
key,
|
||||||
key,
|
config,
|
||||||
config,
|
app_state,
|
||||||
app_state,
|
&mut admin_state.add_table_state,
|
||||||
&mut admin_state.add_table_state,
|
&mut self.command_message,
|
||||||
&mut self.command_message,
|
|
||||||
|
|
||||||
) {
|
) {
|
||||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,8 +216,7 @@ impl EventHandler {
|
|||||||
).await;
|
).await;
|
||||||
match nav_outcome {
|
match nav_outcome {
|
||||||
Ok(EventOutcome::ButtonSelected { context, index }) => {
|
Ok(EventOutcome::ButtonSelected { context, index }) => {
|
||||||
let mut message = String::from("Selected");
|
let message = match context {
|
||||||
match context {
|
|
||||||
UiContext::Intro => {
|
UiContext::Intro => {
|
||||||
intro::handle_intro_selection(app_state, buffer_state, index);
|
intro::handle_intro_selection(app_state, buffer_state, index);
|
||||||
if app_state.ui.show_admin {
|
if app_state.ui.show_admin {
|
||||||
@@ -215,30 +224,36 @@ impl EventHandler {
|
|||||||
admin_state.profile_list_state.select(Some(0));
|
admin_state.profile_list_state.select(Some(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
message = format!("Intro Option {} selected", index);
|
format!("Intro Option {} selected", index)
|
||||||
}
|
}
|
||||||
UiContext::Login => {
|
UiContext::Login => {
|
||||||
message = match index {
|
let login_action_message = match index {
|
||||||
0 => login::save(auth_state, login_state, &mut self.auth_client, app_state).await?,
|
0 => {
|
||||||
|
login::initiate_login(login_state, app_state, self.login_result_sender.clone())
|
||||||
|
},
|
||||||
1 => login::back_to_main(login_state, app_state, buffer_state).await,
|
1 => login::back_to_main(login_state, app_state, buffer_state).await,
|
||||||
_ => "Invalid Login Option".to_string(),
|
_ => "Invalid Login Option".to_string(),
|
||||||
};
|
};
|
||||||
|
login_action_message
|
||||||
}
|
}
|
||||||
UiContext::Register => {
|
UiContext::Register => {
|
||||||
message = match index {
|
let register_action_message = match index {
|
||||||
0 => register::save(register_state, &mut self.auth_client, app_state).await?,
|
0 => {
|
||||||
|
register::initiate_registration(register_state, app_state, self.register_result_sender.clone())
|
||||||
|
},
|
||||||
1 => register::back_to_login(register_state, app_state, buffer_state).await,
|
1 => register::back_to_login(register_state, app_state, buffer_state).await,
|
||||||
_ => "Invalid Login Option".to_string(),
|
_ => "Invalid Login Option".to_string(),
|
||||||
};
|
};
|
||||||
|
register_action_message
|
||||||
}
|
}
|
||||||
UiContext::Admin => {
|
UiContext::Admin => {
|
||||||
admin::handle_admin_selection(app_state, admin_state);
|
admin::handle_admin_selection(app_state, admin_state);
|
||||||
message = format!("Admin Option {} selected", index);
|
format!("Admin Option {} selected", index)
|
||||||
}
|
}
|
||||||
UiContext::Dialog => {
|
UiContext::Dialog => {
|
||||||
message = "Internal error: Unexpected dialog state".to_string();
|
"Internal error: Unexpected dialog state".to_string()
|
||||||
}
|
}
|
||||||
}
|
}; // Semicolon added here
|
||||||
return Ok(EventOutcome::Ok(message));
|
return Ok(EventOutcome::Ok(message));
|
||||||
}
|
}
|
||||||
other => return other,
|
other => return other,
|
||||||
@@ -273,7 +288,7 @@ impl EventHandler {
|
|||||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
}
|
}
|
||||||
// Check for entering edit mode (before cursor)
|
// Check for entering edit mode (before cursor)
|
||||||
else if config.get_read_only_action_for_key(key_code, modifiers) == Some("enter_edit_mode_before")
|
else if config.get_read_only_action_for_key(key_code, modifiers).as_deref() == Some("enter_edit_mode_before")
|
||||||
&& ModeManager::can_enter_edit_mode(current_mode) {
|
&& ModeManager::can_enter_edit_mode(current_mode) {
|
||||||
self.is_edit_mode = true;
|
self.is_edit_mode = true;
|
||||||
self.edit_mode_cooldown = true;
|
self.edit_mode_cooldown = true;
|
||||||
@@ -282,7 +297,7 @@ impl EventHandler {
|
|||||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
}
|
}
|
||||||
// Check for entering edit mode (after cursor)
|
// Check for entering edit mode (after cursor)
|
||||||
else if config.get_read_only_action_for_key(key_code, modifiers) == Some("enter_edit_mode_after")
|
else if config.get_read_only_action_for_key(key_code, modifiers).as_deref() == Some("enter_edit_mode_after")
|
||||||
&& ModeManager::can_enter_edit_mode(current_mode) {
|
&& ModeManager::can_enter_edit_mode(current_mode) {
|
||||||
let current_input = if app_state.ui.show_login || app_state.ui.show_register{
|
let current_input = if app_state.ui.show_login || app_state.ui.show_register{
|
||||||
login_state.get_current_input()
|
login_state.get_current_input()
|
||||||
@@ -306,6 +321,7 @@ impl EventHandler {
|
|||||||
}
|
}
|
||||||
self.is_edit_mode = true;
|
self.is_edit_mode = true;
|
||||||
self.edit_mode_cooldown = true;
|
self.edit_mode_cooldown = true;
|
||||||
|
app_state.ui.focus_outside_canvas = false;
|
||||||
self.command_message = "Edit mode (after cursor)".to_string();
|
self.command_message = "Edit mode (after cursor)".to_string();
|
||||||
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
|
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
|
||||||
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
return Ok(EventOutcome::Ok(self.command_message.clone()));
|
||||||
@@ -349,6 +365,7 @@ impl EventHandler {
|
|||||||
form_state,
|
form_state,
|
||||||
login_state,
|
login_state,
|
||||||
register_state,
|
register_state,
|
||||||
|
&mut admin_state.add_table_state,
|
||||||
&mut self.key_sequence_tracker,
|
&mut self.key_sequence_tracker,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
@@ -383,7 +400,7 @@ impl EventHandler {
|
|||||||
|
|
||||||
let (_should_exit, message) = read_only::handle_read_only_event(
|
let (_should_exit, message) = read_only::handle_read_only_event(
|
||||||
app_state, key, config, form_state, login_state,
|
app_state, key, config, form_state, login_state,
|
||||||
register_state, &mut self.key_sequence_tracker,
|
register_state, &mut admin_state.add_table_state, &mut self.key_sequence_tracker,
|
||||||
current_position, total_count, grpc_client,
|
current_position, total_count, grpc_client,
|
||||||
&mut self.command_message, &mut self.edit_mode_cooldown,
|
&mut self.command_message, &mut self.edit_mode_cooldown,
|
||||||
&mut self.ideal_cursor_column,
|
&mut self.ideal_cursor_column,
|
||||||
@@ -431,6 +448,7 @@ impl EventHandler {
|
|||||||
form_state,
|
form_state,
|
||||||
login_state,
|
login_state,
|
||||||
register_state,
|
register_state,
|
||||||
|
&mut admin_state.add_table_state,
|
||||||
&mut self.ideal_cursor_column,
|
&mut self.ideal_cursor_column,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
@@ -477,7 +495,7 @@ impl EventHandler {
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// Handle error from the edit handler
|
// Handle error from the edit handler
|
||||||
return Err(e);
|
return Err(e.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, // End AppMode::Edit
|
}, // End AppMode::Edit
|
||||||
|
|||||||
@@ -25,21 +25,24 @@ impl ModeManager {
|
|||||||
return AppMode::Highlight;
|
return AppMode::Highlight;
|
||||||
}
|
}
|
||||||
|
|
||||||
if app_state.ui.focus_outside_canvas || app_state.ui.show_add_table{
|
if app_state.ui.focus_outside_canvas {
|
||||||
return AppMode::General;
|
return AppMode::General;
|
||||||
}
|
}
|
||||||
|
|
||||||
if app_state.ui.show_login || app_state.ui.show_register {
|
let is_canvas_view = app_state.ui.show_login
|
||||||
if event_handler.is_edit_mode {
|
|| app_state.ui.show_register
|
||||||
AppMode::Edit
|
|| app_state.ui.show_form
|
||||||
|
|| app_state.ui.show_add_table;
|
||||||
|
|
||||||
|
if is_canvas_view {
|
||||||
|
if app_state.ui.focus_outside_canvas {
|
||||||
|
AppMode::General
|
||||||
} else {
|
} else {
|
||||||
AppMode::ReadOnly
|
if event_handler.is_edit_mode {
|
||||||
}
|
AppMode::Edit
|
||||||
} else if app_state.ui.show_form {
|
} else {
|
||||||
if event_handler.is_edit_mode {
|
AppMode::ReadOnly
|
||||||
AppMode::Edit
|
}
|
||||||
} else {
|
|
||||||
AppMode::ReadOnly
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
AppMode::General
|
AppMode::General
|
||||||
|
|||||||
@@ -6,10 +6,12 @@ use crate::config::binds::key_sequences::KeySequenceTracker;
|
|||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use crate::state::pages::auth::{LoginState, RegisterState};
|
use crate::state::pages::auth::{LoginState, RegisterState};
|
||||||
|
use crate::state::pages::add_table::AddTableState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
use crate::modes::read_only; // Import the ReadOnly handler
|
use crate::modes::read_only;
|
||||||
use crossterm::event::KeyEvent;
|
use crossterm::event::KeyEvent;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
/// Handles events when in Highlight mode.
|
/// Handles events when in Highlight mode.
|
||||||
/// Currently, it mostly delegates to the read_only handler for movement.
|
/// Currently, it mostly delegates to the read_only handler for movement.
|
||||||
@@ -21,6 +23,7 @@ pub async fn handle_highlight_event(
|
|||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
register_state: &mut RegisterState,
|
register_state: &mut RegisterState,
|
||||||
|
add_table_state: &mut AddTableState,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
@@ -28,7 +31,7 @@ pub async fn handle_highlight_event(
|
|||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
edit_mode_cooldown: &mut bool,
|
edit_mode_cooldown: &mut bool,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
|
) -> Result<EventOutcome> {
|
||||||
// Delegate movement and other actions to the read_only handler
|
// Delegate movement and other actions to the read_only handler
|
||||||
// The rendering logic will use the highlight_anchor to draw the selection
|
// The rendering logic will use the highlight_anchor to draw the selection
|
||||||
let (should_exit, message) = read_only::handle_read_only_event(
|
let (should_exit, message) = read_only::handle_read_only_event(
|
||||||
@@ -38,6 +41,7 @@ pub async fn handle_highlight_event(
|
|||||||
form_state,
|
form_state,
|
||||||
login_state,
|
login_state,
|
||||||
register_state,
|
register_state,
|
||||||
|
add_table_state,
|
||||||
key_sequence_tracker,
|
key_sequence_tracker,
|
||||||
current_position,
|
current_position,
|
||||||
total_count,
|
total_count,
|
||||||
|
|||||||
@@ -9,4 +9,3 @@ pub use handlers::*;
|
|||||||
pub use canvas::*;
|
pub use canvas::*;
|
||||||
pub use general::*;
|
pub use general::*;
|
||||||
pub use common::*;
|
pub use common::*;
|
||||||
pub use highlight::*;
|
|
||||||
|
|||||||
@@ -5,19 +5,22 @@ use common::proto::multieko2::auth::{
|
|||||||
LoginRequest, LoginResponse,
|
LoginRequest, LoginResponse,
|
||||||
RegisterRequest, AuthResponse,
|
RegisterRequest, AuthResponse,
|
||||||
};
|
};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
pub struct AuthClient {
|
pub struct AuthClient {
|
||||||
client: AuthServiceClient<Channel>,
|
client: AuthServiceClient<Channel>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthClient {
|
impl AuthClient {
|
||||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub async fn new() -> Result<Self> {
|
||||||
let client = AuthServiceClient::connect("http://[::1]:50051").await?;
|
let client = AuthServiceClient::connect("http://[::1]:50051")
|
||||||
|
.await
|
||||||
|
.context("Failed to connect to auth service")?;
|
||||||
Ok(Self { client })
|
Ok(Self { client })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Login user via gRPC.
|
/// Login user via gRPC.
|
||||||
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
|
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse> {
|
||||||
let request = tonic::Request::new(LoginRequest { identifier, password });
|
let request = tonic::Request::new(LoginRequest { identifier, password });
|
||||||
let response = self.client.login(request).await?.into_inner();
|
let response = self.client.login(request).await?.into_inner();
|
||||||
Ok(response)
|
Ok(response)
|
||||||
@@ -31,7 +34,7 @@ impl AuthClient {
|
|||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
password_confirmation: Option<String>,
|
password_confirmation: Option<String>,
|
||||||
role: Option<String>,
|
role: Option<String>,
|
||||||
) -> Result<AuthResponse, Box<dyn std::error::Error>> {
|
) -> Result<AuthResponse> {
|
||||||
let request = tonic::Request::new(RegisterRequest {
|
let request = tonic::Request::new(RegisterRequest {
|
||||||
username,
|
username,
|
||||||
email,
|
email,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use common::proto::multieko2::table_definition::{
|
|||||||
table_definition_client::TableDefinitionClient,
|
table_definition_client::TableDefinitionClient,
|
||||||
ProfileTreeResponse
|
ProfileTreeResponse
|
||||||
};
|
};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GrpcClient {
|
pub struct GrpcClient {
|
||||||
@@ -19,7 +20,7 @@ pub struct GrpcClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GrpcClient {
|
impl GrpcClient {
|
||||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub async fn new() -> Result<Self> {
|
||||||
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
|
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
|
||||||
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
|
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
|
||||||
let table_definition_client = TableDefinitionClient::connect("http://[::1]:50051").await?;
|
let table_definition_client = TableDefinitionClient::connect("http://[::1]:50051").await?;
|
||||||
@@ -31,37 +32,37 @@ impl GrpcClient {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_adresar_count(&mut self) -> Result<u64, Box<dyn std::error::Error>> {
|
pub async fn get_adresar_count(&mut self) -> Result<u64> {
|
||||||
let request = tonic::Request::new(Empty::default());
|
let request = tonic::Request::new(Empty::default());
|
||||||
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
|
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
|
||||||
Ok(response.count as u64)
|
Ok(response.count as u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse, Box<dyn std::error::Error>> {
|
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse> {
|
||||||
let request = tonic::Request::new(PositionRequest { position: position as i64 });
|
let request = tonic::Request::new(PositionRequest { position: position as i64 });
|
||||||
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
|
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
|
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
||||||
let request = tonic::Request::new(request);
|
let request = tonic::Request::new(request);
|
||||||
let response = self.adresar_client.post_adresar(request).await?;
|
let response = self.adresar_client.post_adresar(request).await?;
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
|
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
||||||
let request = tonic::Request::new(request);
|
let request = tonic::Request::new(request);
|
||||||
let response = self.adresar_client.put_adresar(request).await?;
|
let response = self.adresar_client.put_adresar(request).await?;
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse, Box<dyn std::error::Error>> {
|
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse> {
|
||||||
let request = tonic::Request::new(Empty::default());
|
let request = tonic::Request::new(Empty::default());
|
||||||
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
|
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse, Box<dyn std::error::Error>> {
|
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse> {
|
||||||
let request = tonic::Request::new(Empty::default());
|
let request = tonic::Request::new(Empty::default());
|
||||||
let response = self.table_definition_client.get_profile_tree(request).await?;
|
let response = self.table_definition_client.get_profile_tree(request).await?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use crate::services::grpc_client::GrpcClient;
|
|||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::tui::functions::common::form::SaveOutcome;
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
pub struct UiService;
|
pub struct UiService;
|
||||||
|
|
||||||
@@ -11,9 +12,9 @@ impl UiService {
|
|||||||
pub async fn initialize_app_state(
|
pub async fn initialize_app_state(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
) -> Result<Vec<String>> {
|
||||||
// Fetch profile tree
|
// Fetch profile tree
|
||||||
let profile_tree = grpc_client.get_profile_tree().await?;
|
let profile_tree = grpc_client.get_profile_tree().await.context("Failed to get profile tree")?;
|
||||||
app_state.profile_tree = profile_tree;
|
app_state.profile_tree = profile_tree;
|
||||||
|
|
||||||
// Fetch table structure
|
// Fetch table structure
|
||||||
@@ -32,8 +33,8 @@ impl UiService {
|
|||||||
pub async fn initialize_adresar_count(
|
pub async fn initialize_adresar_count(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<()> {
|
||||||
let total_count = grpc_client.get_adresar_count().await?;
|
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar count")?;
|
||||||
app_state.update_total_count(total_count);
|
app_state.update_total_count(total_count);
|
||||||
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -42,18 +43,18 @@ impl UiService {
|
|||||||
pub async fn update_adresar_count(
|
pub async fn update_adresar_count(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<()> {
|
||||||
let total_count = grpc_client.get_adresar_count().await?;
|
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar by position")?;
|
||||||
app_state.update_total_count(total_count);
|
app_state.update_total_count(total_count);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn load_adresar_by_position(
|
pub async fn load_adresar_by_position(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
_app_state: &mut AppState,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
position: u64,
|
position: u64,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String> {
|
||||||
match grpc_client.get_adresar_by_position(position).await {
|
match grpc_client.get_adresar_by_position(position).await {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
// Set the ID properly
|
// Set the ID properly
|
||||||
@@ -92,8 +93,8 @@ impl UiService {
|
|||||||
save_outcome: SaveOutcome,
|
save_outcome: SaveOutcome,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
form_state: &mut FormState, // Needed to potentially update position/ID
|
form_state: &mut FormState,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<()> {
|
||||||
match save_outcome {
|
match save_outcome {
|
||||||
SaveOutcome::CreatedNew(new_id) => {
|
SaveOutcome::CreatedNew(new_id) => {
|
||||||
// A new record was created, update the count!
|
// A new record was created, update the count!
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use std::env;
|
|||||||
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||||
use crate::modes::handlers::mode_manager::AppMode;
|
use crate::modes::handlers::mode_manager::AppMode;
|
||||||
use crate::ui::handlers::context::DialogPurpose;
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub struct DialogState {
|
pub struct DialogState {
|
||||||
pub dialog_show: bool,
|
pub dialog_show: bool,
|
||||||
@@ -12,6 +13,7 @@ pub struct DialogState {
|
|||||||
pub dialog_buttons: Vec<String>,
|
pub dialog_buttons: Vec<String>,
|
||||||
pub dialog_active_button_index: usize,
|
pub dialog_active_button_index: usize,
|
||||||
pub purpose: Option<DialogPurpose>,
|
pub purpose: Option<DialogPurpose>,
|
||||||
|
pub is_loading: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct UiState {
|
pub struct UiState {
|
||||||
@@ -42,7 +44,7 @@ pub struct AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub fn new() -> Result<Self> {
|
||||||
let current_dir = env::current_dir()?
|
let current_dir = env::current_dir()?
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.to_string();
|
.to_string();
|
||||||
@@ -86,10 +88,41 @@ impl AppState {
|
|||||||
self.ui.dialog.dialog_buttons = buttons;
|
self.ui.dialog.dialog_buttons = buttons;
|
||||||
self.ui.dialog.dialog_active_button_index = 0;
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
self.ui.dialog.purpose = Some(purpose);
|
self.ui.dialog.purpose = Some(purpose);
|
||||||
|
self.ui.dialog.is_loading = false;
|
||||||
self.ui.dialog.dialog_show = true;
|
self.ui.dialog.dialog_show = true;
|
||||||
self.ui.focus_outside_canvas = true;
|
self.ui.focus_outside_canvas = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows a dialog specifically for loading states.
|
||||||
|
pub fn show_loading_dialog(&mut self, title: &str, message: &str) {
|
||||||
|
self.ui.dialog.dialog_title = title.to_string();
|
||||||
|
self.ui.dialog.dialog_message = message.to_string();
|
||||||
|
self.ui.dialog.dialog_buttons.clear(); // No buttons during loading
|
||||||
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
|
self.ui.dialog.purpose = None; // Purpose is set when loading finishes
|
||||||
|
self.ui.dialog.is_loading = true;
|
||||||
|
self.ui.dialog.dialog_show = true;
|
||||||
|
self.ui.focus_outside_canvas = true; // Keep focus management consistent
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the content of an existing dialog, typically after loading.
|
||||||
|
pub fn update_dialog_content(
|
||||||
|
&mut self,
|
||||||
|
message: &str,
|
||||||
|
buttons: Vec<String>,
|
||||||
|
purpose: DialogPurpose,
|
||||||
|
) {
|
||||||
|
if self.ui.dialog.dialog_show {
|
||||||
|
self.ui.dialog.dialog_message = message.to_string();
|
||||||
|
self.ui.dialog.dialog_buttons = buttons;
|
||||||
|
self.ui.dialog.dialog_active_button_index = 0; // Reset focus
|
||||||
|
self.ui.dialog.purpose = Some(purpose);
|
||||||
|
self.ui.dialog.is_loading = false; // Loading finished
|
||||||
|
// Keep dialog_show = true
|
||||||
|
// Keep focus_outside_canvas = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Hides the dialog and clears its content.
|
/// Hides the dialog and clears its content.
|
||||||
pub fn hide_dialog(&mut self) {
|
pub fn hide_dialog(&mut self) {
|
||||||
self.ui.dialog.dialog_show = false;
|
self.ui.dialog.dialog_show = false;
|
||||||
@@ -156,6 +189,7 @@ impl Default for DialogState {
|
|||||||
dialog_buttons: Vec::new(),
|
dialog_buttons: Vec::new(),
|
||||||
dialog_active_button_index: 0,
|
dialog_active_button_index: 0,
|
||||||
purpose: None,
|
purpose: None,
|
||||||
|
is_loading: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ use ratatui::widgets::TableState;
|
|||||||
pub struct ColumnDefinition {
|
pub struct ColumnDefinition {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub data_type: String,
|
pub data_type: String,
|
||||||
|
pub selected: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct LinkDefinition {
|
pub struct LinkDefinition {
|
||||||
pub linked_table_name: String,
|
pub linked_table_name: String,
|
||||||
pub is_required: bool,
|
pub is_required: bool,
|
||||||
|
pub selected: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
@@ -25,8 +27,13 @@ pub enum AddTableFocus {
|
|||||||
ColumnsTable,
|
ColumnsTable,
|
||||||
IndexesTable,
|
IndexesTable,
|
||||||
LinksTable,
|
LinksTable,
|
||||||
|
// Inside Tables (Scrolling Focus)
|
||||||
|
InsideColumnsTable,
|
||||||
|
InsideIndexesTable,
|
||||||
|
InsideLinksTable,
|
||||||
// Buttons
|
// Buttons
|
||||||
SaveButton,
|
SaveButton,
|
||||||
|
DeleteSelectedButton,
|
||||||
CancelButton,
|
CancelButton,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +41,7 @@ pub enum AddTableFocus {
|
|||||||
pub struct AddTableState {
|
pub struct AddTableState {
|
||||||
pub profile_name: String,
|
pub profile_name: String,
|
||||||
pub table_name: String,
|
pub table_name: String,
|
||||||
|
pub table_name_input: String,
|
||||||
pub column_name_input: String,
|
pub column_name_input: String,
|
||||||
pub column_type_input: String,
|
pub column_type_input: String,
|
||||||
pub columns: Vec<ColumnDefinition>,
|
pub columns: Vec<ColumnDefinition>,
|
||||||
@@ -53,23 +61,18 @@ impl Default for AddTableState {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
// Initialize with some dummy data for demonstration
|
// Initialize with some dummy data for demonstration
|
||||||
AddTableState {
|
AddTableState {
|
||||||
profile_name: "default".to_string(), // Should be set dynamically
|
profile_name: "default".to_string(),
|
||||||
table_name: String::new(), // Start empty
|
table_name: String::new(),
|
||||||
|
table_name_input: String::new(),
|
||||||
column_name_input: String::new(),
|
column_name_input: String::new(),
|
||||||
column_type_input: String::new(),
|
column_type_input: String::new(),
|
||||||
columns: vec![
|
columns: Vec::new(),
|
||||||
ColumnDefinition { name: "id".to_string(), data_type: "INTEGER".to_string() },
|
indexes: Vec::new(),
|
||||||
ColumnDefinition { name: "name".to_string(), data_type: "TEXT".to_string() },
|
links: Vec::new(),
|
||||||
],
|
|
||||||
indexes: vec!["id".to_string()],
|
|
||||||
links: vec![
|
|
||||||
LinkDefinition { linked_table_name: "related_table".to_string(), is_required: true },
|
|
||||||
LinkDefinition { linked_table_name: "another_table".to_string(), is_required: false },
|
|
||||||
],
|
|
||||||
current_focus: AddTableFocus::InputTableName,
|
current_focus: AddTableFocus::InputTableName,
|
||||||
column_table_state: TableState::default().with_selected(0),
|
column_table_state: TableState::default(),
|
||||||
index_table_state: TableState::default().with_selected(0),
|
index_table_state: TableState::default(),
|
||||||
link_table_state: TableState::default().with_selected(0),
|
link_table_state: TableState::default(),
|
||||||
table_name_cursor_pos: 0,
|
table_name_cursor_pos: 0,
|
||||||
column_name_cursor_pos: 0,
|
column_name_cursor_pos: 0,
|
||||||
column_type_cursor_pos: 0,
|
column_type_cursor_pos: 0,
|
||||||
@@ -79,7 +82,7 @@ impl Default for AddTableState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AddTableState {
|
impl AddTableState {
|
||||||
const INPUT_FIELD_COUNT: usize = 3;
|
pub const INPUT_FIELD_COUNT: usize = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implement CanvasState for the input fields
|
// Implement CanvasState for the input fields
|
||||||
@@ -108,12 +111,12 @@ impl CanvasState for AddTableState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn inputs(&self) -> Vec<&String> {
|
fn inputs(&self) -> Vec<&String> {
|
||||||
vec![&self.table_name, &self.column_name_input, &self.column_type_input]
|
vec![&self.table_name_input, &self.column_name_input, &self.column_type_input]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_current_input(&self) -> &str {
|
fn get_current_input(&self) -> &str {
|
||||||
match self.current_focus {
|
match self.current_focus {
|
||||||
AddTableFocus::InputTableName => &self.table_name,
|
AddTableFocus::InputTableName => &self.table_name_input,
|
||||||
AddTableFocus::InputColumnName => &self.column_name_input,
|
AddTableFocus::InputColumnName => &self.column_name_input,
|
||||||
AddTableFocus::InputColumnType => &self.column_type_input,
|
AddTableFocus::InputColumnType => &self.column_type_input,
|
||||||
_ => "", // Should not happen if called correctly
|
_ => "", // Should not happen if called correctly
|
||||||
@@ -122,14 +125,10 @@ impl CanvasState for AddTableState {
|
|||||||
|
|
||||||
fn get_current_input_mut(&mut self) -> &mut String {
|
fn get_current_input_mut(&mut self) -> &mut String {
|
||||||
match self.current_focus {
|
match self.current_focus {
|
||||||
AddTableFocus::InputTableName => &mut self.table_name,
|
AddTableFocus::InputTableName => &mut self.table_name_input,
|
||||||
AddTableFocus::InputColumnName => &mut self.column_name_input,
|
AddTableFocus::InputColumnName => &mut self.column_name_input,
|
||||||
AddTableFocus::InputColumnType => &mut self.column_type_input,
|
AddTableFocus::InputColumnType => &mut self.column_type_input,
|
||||||
// This case needs careful handling. If focus isn't on an input,
|
_ => &mut self.table_name_input,
|
||||||
// which mutable string should we return? Returning the first one
|
|
||||||
// might be unexpected. Consider panicking or returning Option if this state is invalid.
|
|
||||||
// For now, returning the first field to avoid panics during rendering.
|
|
||||||
_ => &mut self.table_name,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ pub struct LoginState {
|
|||||||
pub current_field: usize,
|
pub current_field: usize,
|
||||||
pub current_cursor_pos: usize,
|
pub current_cursor_pos: usize,
|
||||||
pub has_unsaved_changes: bool,
|
pub has_unsaved_changes: bool,
|
||||||
|
pub login_request_pending: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents the state of the Registration form UI
|
/// Represents the state of the Registration form UI
|
||||||
@@ -71,6 +72,7 @@ impl LoginState {
|
|||||||
current_field: 0,
|
current_field: 0,
|
||||||
current_cursor_pos: 0,
|
current_cursor_pos: 0,
|
||||||
has_unsaved_changes: false,
|
has_unsaved_changes: false,
|
||||||
|
login_request_pending: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,3 +3,4 @@
|
|||||||
pub mod form;
|
pub mod form;
|
||||||
pub mod login;
|
pub mod login;
|
||||||
pub mod register;
|
pub mod register;
|
||||||
|
pub mod add_table;
|
||||||
|
|||||||
100
client/src/tui/functions/common/add_table.rs
Normal file
100
client/src/tui/functions/common/add_table.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
// src/tui/functions/common/add_table.rs
|
||||||
|
use crate::state::pages::add_table::{
|
||||||
|
AddTableFocus, AddTableState, ColumnDefinition,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Handles the logic for adding a column when the "Add" button is activated.
|
||||||
|
///
|
||||||
|
/// Takes the mutable state and command message string.
|
||||||
|
/// Returns `Some(AddTableFocus)` indicating the desired focus state after a successful add,
|
||||||
|
/// or `None` if the action failed (e.g., validation error).
|
||||||
|
pub fn handle_add_column_action(
|
||||||
|
add_table_state: &mut AddTableState,
|
||||||
|
command_message: &mut String,
|
||||||
|
) -> Option<AddTableFocus> {
|
||||||
|
|
||||||
|
// Trim and create owned Strings from inputs
|
||||||
|
let table_name_in = add_table_state.table_name_input.trim();
|
||||||
|
let column_name_in = add_table_state.column_name_input.trim();
|
||||||
|
let column_type_in = add_table_state.column_type_input.trim();
|
||||||
|
|
||||||
|
// Validate all inputs needed for this combined action
|
||||||
|
let has_table_name = !table_name_in.is_empty();
|
||||||
|
let has_column_name = !column_name_in.is_empty();
|
||||||
|
let has_column_type = !column_type_in.is_empty();
|
||||||
|
|
||||||
|
match (has_table_name, has_column_name, has_column_type) {
|
||||||
|
// Case 1: Both column fields have input (Table name is optional here)
|
||||||
|
(_, true, true) => {
|
||||||
|
let mut msg = String::new();
|
||||||
|
// Optionally update table name if provided
|
||||||
|
if has_table_name {
|
||||||
|
add_table_state.table_name = table_name_in.to_string();
|
||||||
|
msg.push_str(&format!("Table name set to '{}'. ", add_table_state.table_name));
|
||||||
|
}
|
||||||
|
// Add the column
|
||||||
|
let new_column = ColumnDefinition {
|
||||||
|
name: column_name_in.to_string(),
|
||||||
|
data_type: column_type_in.to_string(),
|
||||||
|
selected: false,
|
||||||
|
};
|
||||||
|
add_table_state.columns.push(new_column.clone()); // Clone for msg
|
||||||
|
msg.push_str(&format!("Column '{}' added.", new_column.name));
|
||||||
|
*command_message = msg;
|
||||||
|
|
||||||
|
// Clear all inputs and reset cursors
|
||||||
|
add_table_state.table_name_input.clear();
|
||||||
|
add_table_state.column_name_input.clear();
|
||||||
|
add_table_state.column_type_input.clear();
|
||||||
|
add_table_state.table_name_cursor_pos = 0;
|
||||||
|
add_table_state.column_name_cursor_pos = 0;
|
||||||
|
add_table_state.column_type_cursor_pos = 0;
|
||||||
|
add_table_state.has_unsaved_changes = true;
|
||||||
|
Some(AddTableFocus::InputColumnName) // Focus for next column
|
||||||
|
}
|
||||||
|
// Case 2: Only one column field has input (Error)
|
||||||
|
(_, true, false) | (_, false, true) => {
|
||||||
|
*command_message = "Both Column Name and Type are required to add a column.".to_string();
|
||||||
|
None // Indicate validation failure
|
||||||
|
}
|
||||||
|
// Case 3: Only Table name has input (No column input)
|
||||||
|
(true, false, false) => {
|
||||||
|
add_table_state.table_name = table_name_in.to_string();
|
||||||
|
*command_message = format!("Table name set to '{}'.", add_table_state.table_name);
|
||||||
|
// Clear only table name input
|
||||||
|
add_table_state.table_name_input.clear();
|
||||||
|
add_table_state.table_name_cursor_pos = 0;
|
||||||
|
add_table_state.has_unsaved_changes = true;
|
||||||
|
Some(AddTableFocus::InputTableName) // Keep focus here
|
||||||
|
}
|
||||||
|
// Case 4: All fields are empty
|
||||||
|
(false, false, false) => {
|
||||||
|
*command_message = "No input provided.".to_string();
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles deleting columns marked as selected in the AddTableState.
|
||||||
|
pub fn handle_delete_selected_columns(
|
||||||
|
add_table_state: &mut AddTableState,
|
||||||
|
) -> String {
|
||||||
|
let initial_count = add_table_state.columns.len();
|
||||||
|
// Keep only the columns that are NOT selected
|
||||||
|
add_table_state.columns.retain(|col| !col.selected);
|
||||||
|
let deleted_count = initial_count - add_table_state.columns.len();
|
||||||
|
|
||||||
|
if deleted_count > 0 {
|
||||||
|
add_table_state.has_unsaved_changes = true;
|
||||||
|
// Reset selection highlight as indices have changed
|
||||||
|
add_table_state.column_table_state.select(None);
|
||||||
|
// Optionally, select the first item if the list is not empty
|
||||||
|
// if !add_table_state.columns.is_empty() {
|
||||||
|
// add_table_state.column_table_state.select(Some(0));
|
||||||
|
// }
|
||||||
|
format!("Deleted {} selected column(s).", deleted_count)
|
||||||
|
} else {
|
||||||
|
"No columns marked for deletion.".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum SaveOutcome {
|
pub enum SaveOutcome {
|
||||||
@@ -17,7 +18,7 @@ pub async fn save(
|
|||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<SaveOutcome, Box<dyn std::error::Error>> { // <-- Return SaveOutcome
|
) -> Result<SaveOutcome> { // <-- Return SaveOutcome
|
||||||
if !form_state.has_unsaved_changes {
|
if !form_state.has_unsaved_changes {
|
||||||
return Ok(SaveOutcome::NoChange); // Early exit if no changes
|
return Ok(SaveOutcome::NoChange); // Early exit if no changes
|
||||||
}
|
}
|
||||||
@@ -78,7 +79,7 @@ pub async fn revert(
|
|||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String> {
|
||||||
let is_new = *current_position == total_count + 1;
|
let is_new = *current_position == total_count + 1;
|
||||||
|
|
||||||
if is_new {
|
if is_new {
|
||||||
|
|||||||
@@ -7,6 +7,18 @@ use crate::state::app::state::AppState;
|
|||||||
use crate::state::app::buffer::{AppView, BufferState};
|
use crate::state::app::buffer::{AppView, BufferState};
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::ui::handlers::context::DialogPurpose;
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
|
use common::proto::multieko2::auth::LoginResponse;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use tokio::spawn;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tracing::{info, error};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum LoginResult {
|
||||||
|
Success(LoginResponse),
|
||||||
|
Failure(String),
|
||||||
|
ConnectionError(String),
|
||||||
|
}
|
||||||
|
|
||||||
/// Attempts to log the user in using the provided credentials via gRPC.
|
/// Attempts to log the user in using the provided credentials via gRPC.
|
||||||
/// Updates AuthState and AppState on success or failure.
|
/// Updates AuthState and AppState on success or failure.
|
||||||
@@ -15,30 +27,47 @@ pub async fn save(
|
|||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
auth_client: &mut AuthClient,
|
auth_client: &mut AuthClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String> {
|
||||||
let identifier = login_state.username.clone();
|
let identifier = login_state.username.clone();
|
||||||
let password = login_state.password.clone();
|
let password = login_state.password.clone();
|
||||||
|
|
||||||
|
// --- Client-side validation ---
|
||||||
|
// Prevent login attempt if the identifier field is empty or whitespace.
|
||||||
|
if identifier.trim().is_empty() {
|
||||||
|
let error_message = "Username/Email cannot be empty.".to_string();
|
||||||
|
app_state.show_dialog(
|
||||||
|
"Login Failed",
|
||||||
|
&error_message,
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::LoginFailed,
|
||||||
|
);
|
||||||
|
login_state.error_message = Some(error_message.clone());
|
||||||
|
return Err(anyhow::anyhow!(error_message));
|
||||||
|
}
|
||||||
|
|
||||||
// Clear previous error/dialog state before attempting
|
// Clear previous error/dialog state before attempting
|
||||||
login_state.error_message = None;
|
login_state.error_message = None;
|
||||||
// Use the helper to ensure dialog is hidden and cleared properly
|
app_state.hide_dialog(); // Hide any previous dialog
|
||||||
app_state.hide_dialog();
|
|
||||||
|
|
||||||
// Call the gRPC login method
|
// Call the gRPC login method
|
||||||
match auth_client.login(identifier, password).await {
|
match auth_client.login(identifier.clone(), password).await
|
||||||
|
.with_context(|| format!("gRPC login attempt failed for identifier: {}", identifier))
|
||||||
|
{
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
// Store authentication details on success
|
// Store authentication details using correct field names
|
||||||
auth_state.auth_token = Some(response.access_token.clone());
|
auth_state.auth_token = Some(response.access_token.clone());
|
||||||
auth_state.user_id = Some(response.user_id.clone());
|
auth_state.user_id = Some(response.user_id.clone());
|
||||||
auth_state.role = Some(response.role.clone());
|
auth_state.role = Some(response.role.clone());
|
||||||
auth_state.decoded_username = Some(response.username.clone());
|
auth_state.decoded_username = Some(response.username.clone());
|
||||||
login_state.set_has_unsaved_changes(false);
|
login_state.set_has_unsaved_changes(false);
|
||||||
|
login_state.error_message = None;
|
||||||
|
|
||||||
|
// Format the success message using response data
|
||||||
let success_message = format!(
|
let success_message = format!(
|
||||||
"Login Successful!\n\n\
|
"Login Successful!\n\n\
|
||||||
Username: {}\n\
|
Username: {}\n\
|
||||||
User ID: {}\n\
|
User ID: {}\n\
|
||||||
Role: {}",
|
Role: {}",
|
||||||
response.username,
|
response.username,
|
||||||
response.user_id,
|
response.user_id,
|
||||||
response.role
|
response.role
|
||||||
@@ -50,23 +79,24 @@ pub async fn save(
|
|||||||
vec!["Menu".to_string(), "Exit".to_string()],
|
vec!["Menu".to_string(), "Exit".to_string()],
|
||||||
DialogPurpose::LoginSuccess,
|
DialogPurpose::LoginSuccess,
|
||||||
);
|
);
|
||||||
|
login_state.password.clear();
|
||||||
|
login_state.username.clear();
|
||||||
|
login_state.current_cursor_pos = 0;
|
||||||
Ok("Login successful, details shown in dialog.".to_string())
|
Ok("Login successful, details shown in dialog.".to_string())
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let error_message = format!("{}", e);
|
let error_message = format!("{}", e);
|
||||||
|
|
||||||
// Use the helper method to configure and show the dialog
|
|
||||||
app_state.show_dialog(
|
app_state.show_dialog(
|
||||||
"Login Failed",
|
"Login Failed",
|
||||||
&error_message,
|
&error_message,
|
||||||
vec!["OK".to_string()],
|
vec!["OK".to_string()],
|
||||||
DialogPurpose::LoginFailed,
|
DialogPurpose::LoginFailed,
|
||||||
);
|
);
|
||||||
|
login_state.error_message = Some(error_message.clone());
|
||||||
login_state.set_has_unsaved_changes(true);
|
login_state.set_has_unsaved_changes(true);
|
||||||
|
login_state.username.clear();
|
||||||
Ok(format!("Login failed: {}", error_message))
|
login_state.password.clear();
|
||||||
|
Err(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,13 +104,14 @@ pub async fn save(
|
|||||||
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
|
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
|
||||||
pub async fn revert(
|
pub async fn revert(
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
app_state: &mut AppState,
|
_app_state: &mut AppState, // Keep signature consistent if needed elsewhere
|
||||||
) -> String {
|
) -> String {
|
||||||
// Clear the input fields
|
// Clear the input fields
|
||||||
login_state.username.clear();
|
login_state.username.clear();
|
||||||
login_state.password.clear();
|
login_state.password.clear();
|
||||||
login_state.error_message = None;
|
login_state.error_message = None;
|
||||||
login_state.set_has_unsaved_changes(false);
|
login_state.set_has_unsaved_changes(false);
|
||||||
|
login_state.login_request_pending = false; // Ensure flag is reset on revert
|
||||||
|
|
||||||
"Login reverted".to_string()
|
"Login reverted".to_string()
|
||||||
}
|
}
|
||||||
@@ -95,9 +126,10 @@ pub async fn back_to_main(
|
|||||||
login_state.password.clear();
|
login_state.password.clear();
|
||||||
login_state.error_message = None;
|
login_state.error_message = None;
|
||||||
login_state.set_has_unsaved_changes(false);
|
login_state.set_has_unsaved_changes(false);
|
||||||
|
login_state.login_request_pending = false; // Ensure flag is reset
|
||||||
|
|
||||||
// Ensure dialog is hidden if revert is called
|
// Ensure dialog is hidden if revert is called
|
||||||
app_state.hide_dialog(); // Uncomment if needed
|
app_state.hide_dialog();
|
||||||
|
|
||||||
// Navigation logic
|
// Navigation logic
|
||||||
buffer_state.close_active_buffer();
|
buffer_state.close_active_buffer();
|
||||||
@@ -109,3 +141,88 @@ pub async fn back_to_main(
|
|||||||
|
|
||||||
"Returned to main menu".to_string()
|
"Returned to main menu".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates input, shows loading, and spawns the login task.
|
||||||
|
pub fn initiate_login(
|
||||||
|
login_state: &LoginState,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
sender: mpsc::Sender<LoginResult>,
|
||||||
|
) -> String {
|
||||||
|
let username = login_state.username.clone();
|
||||||
|
let password = login_state.password.clone();
|
||||||
|
|
||||||
|
// 1. Client-side validation
|
||||||
|
if username.trim().is_empty() {
|
||||||
|
app_state.show_dialog(
|
||||||
|
"Login Failed",
|
||||||
|
"Username/Email cannot be empty.",
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::LoginFailed,
|
||||||
|
);
|
||||||
|
"Username cannot be empty.".to_string()
|
||||||
|
} else {
|
||||||
|
// 2. Show Loading Dialog
|
||||||
|
app_state.show_loading_dialog("Logging In", "Please wait...");
|
||||||
|
|
||||||
|
// 3. Spawn the login task
|
||||||
|
spawn(async move {
|
||||||
|
let login_outcome = match AuthClient::new().await {
|
||||||
|
Ok(mut auth_client) => {
|
||||||
|
match auth_client.login(username.clone(), password).await
|
||||||
|
.with_context(|| format!("Spawned login task failed for identifier: {}", username))
|
||||||
|
{
|
||||||
|
Ok(response) => LoginResult::Success(response),
|
||||||
|
Err(e) => LoginResult::Failure(format!("{}", e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => LoginResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
|
||||||
|
};
|
||||||
|
// Send result back to the main UI thread
|
||||||
|
if let Err(e) = sender.send(login_outcome).await {
|
||||||
|
error!("Failed to send login result: {}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. Return immediately
|
||||||
|
"Login initiated.".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles the result received from the login task.
|
||||||
|
/// Returns true if a redraw is needed.
|
||||||
|
pub fn handle_login_result(
|
||||||
|
result: LoginResult,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
auth_state: &mut AuthState,
|
||||||
|
login_state: &mut LoginState,
|
||||||
|
) -> bool {
|
||||||
|
match result {
|
||||||
|
LoginResult::Success(response) => {
|
||||||
|
auth_state.auth_token = Some(response.access_token.clone());
|
||||||
|
auth_state.user_id = Some(response.user_id.clone());
|
||||||
|
auth_state.role = Some(response.role.clone());
|
||||||
|
auth_state.decoded_username = Some(response.username.clone());
|
||||||
|
|
||||||
|
let success_message = format!(
|
||||||
|
"Login Successful!\n\nUsername: {}\nUser ID: {}\nRole: {}",
|
||||||
|
response.username, response.user_id, response.role
|
||||||
|
);
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&success_message,
|
||||||
|
vec!["Menu".to_string(), "Exit".to_string()],
|
||||||
|
DialogPurpose::LoginSuccess,
|
||||||
|
);
|
||||||
|
info!(message = %success_message, "Login successful");
|
||||||
|
}
|
||||||
|
LoginResult::Failure(err_msg) | LoginResult::ConnectionError(err_msg) => {
|
||||||
|
app_state.update_dialog_content(&err_msg, vec!["OK".to_string()], DialogPurpose::LoginFailed);
|
||||||
|
login_state.error_message = Some(err_msg.clone());
|
||||||
|
error!(error = %err_msg, "Login failed/connection error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
login_state.username.clear();
|
||||||
|
login_state.password.clear();
|
||||||
|
login_state.set_has_unsaved_changes(false);
|
||||||
|
login_state.current_cursor_pos = 0;
|
||||||
|
true // Request redraw as dialog content changed
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,108 +8,17 @@ use crate::state::{
|
|||||||
};
|
};
|
||||||
use crate::ui::handlers::context::DialogPurpose;
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
use crate::state::app::buffer::{AppView, BufferState};
|
use crate::state::app::buffer::{AppView, BufferState};
|
||||||
|
use common::proto::multieko2::auth::AuthResponse;
|
||||||
|
use anyhow::Context;
|
||||||
|
use tokio::spawn;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tracing::{info, error};
|
||||||
|
|
||||||
/// Attempts to register the user using the provided details via gRPC.
|
#[derive(Debug)]
|
||||||
/// Updates RegisterState and AppState on success or failure.
|
pub enum RegisterResult {
|
||||||
pub async fn save(
|
Success(AuthResponse),
|
||||||
register_state: &mut RegisterState,
|
Failure(String),
|
||||||
auth_client: &mut AuthClient,
|
ConnectionError(String),
|
||||||
app_state: &mut AppState,
|
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
let username = register_state.username.clone();
|
|
||||||
let email = register_state.email.clone();
|
|
||||||
// Handle optional passwords: send None if empty, Some(value) otherwise
|
|
||||||
let password = if register_state.password.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(register_state.password.clone())
|
|
||||||
};
|
|
||||||
let password_confirmation = if register_state.password_confirmation.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(register_state.password_confirmation.clone())
|
|
||||||
};
|
|
||||||
let role = if register_state.role.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(register_state.role.clone())
|
|
||||||
};
|
|
||||||
|
|
||||||
// Basic client-side validation (example)
|
|
||||||
if username.is_empty() {
|
|
||||||
app_state.show_dialog(
|
|
||||||
"Registration Failed",
|
|
||||||
"Username cannot be empty.",
|
|
||||||
vec!["OK".to_string()],
|
|
||||||
DialogPurpose::RegisterFailed,
|
|
||||||
);
|
|
||||||
register_state.error_message = Some("Username cannot be empty.".to_string());
|
|
||||||
return Ok("Registration failed: Username cannot be empty.".to_string());
|
|
||||||
}
|
|
||||||
if password.is_some() && password != password_confirmation {
|
|
||||||
app_state.show_dialog(
|
|
||||||
"Registration Failed",
|
|
||||||
"Passwords do not match.",
|
|
||||||
vec!["OK".to_string()],
|
|
||||||
DialogPurpose::RegisterFailed,
|
|
||||||
);
|
|
||||||
register_state.error_message = Some("Passwords do not match.".to_string());
|
|
||||||
return Ok("Registration failed: Passwords do not match.".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Clear previous error/dialog state before attempting
|
|
||||||
register_state.error_message = None;
|
|
||||||
app_state.hide_dialog();
|
|
||||||
|
|
||||||
// Call the gRPC register method
|
|
||||||
match auth_client.register(username, email, password, password_confirmation, role).await {
|
|
||||||
Ok(response) => {
|
|
||||||
// Clear fields on success? Optional, maybe wait for dialog confirmation.
|
|
||||||
// register_state.username.clear();
|
|
||||||
// register_state.email.clear();
|
|
||||||
// register_state.password.clear();
|
|
||||||
// register_state.password_confirmation.clear();
|
|
||||||
register_state.set_has_unsaved_changes(false);
|
|
||||||
|
|
||||||
let success_message = format!(
|
|
||||||
"Registration Successful!\n\n\
|
|
||||||
User ID: {}\n\
|
|
||||||
Username: {}\n\
|
|
||||||
Email: {}\n\
|
|
||||||
Role: {}",
|
|
||||||
response.id,
|
|
||||||
response.username,
|
|
||||||
response.email,
|
|
||||||
response.role
|
|
||||||
);
|
|
||||||
|
|
||||||
// Show success dialog
|
|
||||||
app_state.show_dialog(
|
|
||||||
"Registration Success",
|
|
||||||
&success_message,
|
|
||||||
vec!["OK".to_string()], // Simple OK for now
|
|
||||||
DialogPurpose::RegisterSuccess,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok("Registration successful, details shown in dialog.".to_string())
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
let error_message = format!("{}", e);
|
|
||||||
register_state.error_message = Some(error_message.clone());
|
|
||||||
register_state.set_has_unsaved_changes(true); // Keep changes on error
|
|
||||||
|
|
||||||
// Show error dialog
|
|
||||||
app_state.show_dialog(
|
|
||||||
"Registration Failed",
|
|
||||||
&error_message,
|
|
||||||
vec!["OK".to_string()],
|
|
||||||
DialogPurpose::RegisterFailed,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(format!("Registration failed: {}", error_message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Clears the registration form fields.
|
/// Clears the registration form fields.
|
||||||
@@ -152,3 +61,89 @@ pub async fn back_to_login(
|
|||||||
"Returned to main menu".to_string()
|
"Returned to main menu".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates input, shows loading, and spawns the registration task.
|
||||||
|
pub fn initiate_registration(
|
||||||
|
register_state: &RegisterState,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
sender: mpsc::Sender<RegisterResult>,
|
||||||
|
) -> String {
|
||||||
|
// Clone necessary data
|
||||||
|
let username = register_state.username.clone();
|
||||||
|
let email = register_state.email.clone();
|
||||||
|
let password = register_state.password.clone();
|
||||||
|
let password_confirmation = register_state.password_confirmation.clone();
|
||||||
|
let role = register_state.role.clone();
|
||||||
|
|
||||||
|
// 1. Client-side validation
|
||||||
|
if username.trim().is_empty() {
|
||||||
|
app_state.show_dialog("Registration Failed", "Username cannot be empty.", vec!["OK".to_string()], DialogPurpose::RegisterFailed);
|
||||||
|
"Username cannot be empty.".to_string()
|
||||||
|
} else if !password.is_empty() && password != password_confirmation {
|
||||||
|
app_state.show_dialog("Registration Failed", "Passwords do not match.", vec!["OK".to_string()], DialogPurpose::RegisterFailed);
|
||||||
|
"Passwords do not match.".to_string()
|
||||||
|
} else {
|
||||||
|
// 2. Show Loading Dialog
|
||||||
|
app_state.show_loading_dialog("Registering", "Please wait...");
|
||||||
|
|
||||||
|
// 3. Spawn the registration task
|
||||||
|
spawn(async move {
|
||||||
|
let register_outcome = match AuthClient::new().await {
|
||||||
|
Ok(mut auth_client) => {
|
||||||
|
// Handle optional fields correctly for the gRPC call
|
||||||
|
let password_opt = if password.is_empty() { None } else { Some(password) };
|
||||||
|
let password_conf_opt = if password_confirmation.is_empty() { None } else { Some(password_confirmation) };
|
||||||
|
let role_opt = if role.is_empty() { None } else { Some(role) };
|
||||||
|
|
||||||
|
match auth_client.register(username.clone(), email, password_opt, password_conf_opt, role_opt).await
|
||||||
|
.with_context(|| format!("Spawned register task failed for username: {}", username))
|
||||||
|
{
|
||||||
|
Ok(response) => RegisterResult::Success(response),
|
||||||
|
Err(e) => RegisterResult::Failure(format!("{}", e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => RegisterResult::ConnectionError(format!("Failed to create AuthClient: {}", e)),
|
||||||
|
};
|
||||||
|
// Send result back to the main UI thread
|
||||||
|
if let Err(e) = sender.send(register_outcome).await {
|
||||||
|
error!("Failed to send registration result: {}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. Return immediately
|
||||||
|
"Registration initiated.".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles the result received from the registration task.
|
||||||
|
/// Returns true if a redraw is needed.
|
||||||
|
pub fn handle_registration_result(
|
||||||
|
result: RegisterResult,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
register_state: &mut RegisterState,
|
||||||
|
) -> bool {
|
||||||
|
match result {
|
||||||
|
RegisterResult::Success(response) => {
|
||||||
|
let success_message = format!(
|
||||||
|
"Registration Successful!\n\nUser ID: {}\nUsername: {}\nEmail: {}\nRole: {}",
|
||||||
|
response.id, response.username, response.email, response.role
|
||||||
|
);
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&success_message,
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::RegisterSuccess,
|
||||||
|
);
|
||||||
|
info!(message = %success_message, "Registration successful");
|
||||||
|
}
|
||||||
|
RegisterResult::Failure(err_msg) | RegisterResult::ConnectionError(err_msg) => {
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&err_msg,
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::RegisterFailed,
|
||||||
|
);
|
||||||
|
register_state.error_message = Some(err_msg.clone());
|
||||||
|
error!(error = %err_msg, "Registration failed/connection error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
register_state.set_has_unsaved_changes(false); // Clear flag after processing
|
||||||
|
true // Request redraw as dialog content changed
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
|
||||||
pub async fn handle_action(
|
pub async fn handle_action(
|
||||||
action: &str,
|
action: &str,
|
||||||
@@ -10,7 +11,7 @@ pub async fn handle_action(
|
|||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
) -> Result<String, Box<dyn std::error::Error>> {
|
) -> Result<String> {
|
||||||
// TODO store unsaved changes without deleting form state values
|
// TODO store unsaved changes without deleting form state values
|
||||||
// First check for unsaved changes in both cases
|
// First check for unsaved changes in both cases
|
||||||
if form_state.has_unsaved_changes() {
|
if form_state.has_unsaved_changes() {
|
||||||
@@ -84,6 +85,7 @@ pub async fn handle_action(
|
|||||||
Ok("Already at last entry".into())
|
Ok("Already at last entry".into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Err("Unknown form action".into())
|
_ => Err(anyhow!("Unknown form action: {}", action))
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// src/tui/functions/login.rs
|
// src/tui/functions/login.rs
|
||||||
|
|
||||||
pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::Error>> {
|
use anyhow::{anyhow, Result};
|
||||||
|
|
||||||
|
pub async fn handle_action(action: &str,) -> Result<String> {
|
||||||
match action {
|
match action {
|
||||||
"previous_entry" => {
|
"previous_entry" => {
|
||||||
Ok("Previous entry at tui/functions/login.rs not implemented".into())
|
Ok("Previous entry at tui/functions/login.rs not implemented".into())
|
||||||
@@ -8,6 +10,6 @@ pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::
|
|||||||
"next_entry" => {
|
"next_entry" => {
|
||||||
Ok("Next entry at tui/functions/login.rs not implemented".into())
|
Ok("Next entry at tui/functions/login.rs not implemented".into())
|
||||||
}
|
}
|
||||||
_ => Err("Unknown login action".into())
|
_ => Err(anyhow!("Unknown login action: {}", action))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,14 @@ use crossterm::{
|
|||||||
};
|
};
|
||||||
use ratatui::{backend::CrosstermBackend, Terminal};
|
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||||
use std::io::{self, stdout, Write};
|
use std::io::{self, stdout, Write};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub struct TerminalCore {
|
pub struct TerminalCore {
|
||||||
terminal: Terminal<CrosstermBackend<io::Stdout>>,
|
terminal: Terminal<CrosstermBackend<io::Stdout>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TerminalCore {
|
impl TerminalCore {
|
||||||
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub fn new() -> Result<Self> {
|
||||||
enable_raw_mode()?;
|
enable_raw_mode()?;
|
||||||
let mut stdout = stdout();
|
let mut stdout = stdout();
|
||||||
execute!(
|
execute!(
|
||||||
@@ -27,7 +28,7 @@ impl TerminalCore {
|
|||||||
Ok(Self { terminal })
|
Ok(Self { terminal })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn draw<F>(&mut self, f: F) -> Result<(), Box<dyn std::error::Error>>
|
pub fn draw<F>(&mut self, f: F) -> Result<()>
|
||||||
where
|
where
|
||||||
F: FnOnce(&mut ratatui::Frame),
|
F: FnOnce(&mut ratatui::Frame),
|
||||||
{
|
{
|
||||||
@@ -35,7 +36,7 @@ impl TerminalCore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cleanup(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
pub fn cleanup(&mut self) -> Result<()> {
|
||||||
let backend = self.terminal.backend_mut();
|
let backend = self.terminal.backend_mut();
|
||||||
execute!(
|
execute!(
|
||||||
backend,
|
backend,
|
||||||
@@ -56,7 +57,7 @@ impl TerminalCore {
|
|||||||
pub fn set_cursor_style(
|
pub fn set_cursor_style(
|
||||||
&mut self,
|
&mut self,
|
||||||
style: SetCursorStyle,
|
style: SetCursorStyle,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<()> {
|
||||||
execute!(
|
execute!(
|
||||||
self.terminal.backend_mut(),
|
self.terminal.backend_mut(),
|
||||||
style,
|
style,
|
||||||
@@ -65,7 +66,7 @@ impl TerminalCore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn show_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
pub fn show_cursor(&mut self) -> Result<()> {
|
||||||
execute!(
|
execute!(
|
||||||
self.terminal.backend_mut(),
|
self.terminal.backend_mut(),
|
||||||
Show
|
Show
|
||||||
@@ -73,7 +74,7 @@ impl TerminalCore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hide_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
|
pub fn hide_cursor(&mut self) -> Result<()> {
|
||||||
execute!(
|
execute!(
|
||||||
self.terminal.backend_mut(),
|
self.terminal.backend_mut(),
|
||||||
Hide
|
Hide
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// src/tui/terminal/event_reader.rs
|
// src/tui/terminal/event_reader.rs
|
||||||
|
|
||||||
use crossterm::event::{self, Event};
|
use crossterm::event::{self, Event};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
pub struct EventReader;
|
pub struct EventReader;
|
||||||
|
|
||||||
@@ -9,7 +10,7 @@ impl EventReader {
|
|||||||
Self
|
Self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_event(&self) -> Result<Event, Box<dyn std::error::Error>> {
|
pub fn read_event(&self) -> Result<Event> {
|
||||||
Ok(event::read()?)
|
Ok(event::read()?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
34
client/src/ui/docs/ui_redraws.md
Normal file
34
client/src/ui/docs/ui_redraws.md
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# UI Redraw Logic (`needs_redraw` Flag)
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
The main UI loop in `client/src/ui/handlers/ui.rs` uses `crossterm_event::poll` with a short timeout to remain responsive to both user input and asynchronous operations (like login results arriving via channels). However, calling `terminal.draw()` unconditionally in every loop iteration caused constant UI refreshes and high CPU usage, even when idle.
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
A boolean flag, `needs_redraw`, was introduced in the main loop scope to control when the UI is actually redrawn.
|
||||||
|
|
||||||
|
## Mechanism
|
||||||
|
|
||||||
|
1. **Initialization:** `needs_redraw` is initialized to `true` before the loop starts to ensure the initial UI state is drawn.
|
||||||
|
2. **Conditional Drawing:** The `terminal.draw(...)` call is wrapped in an `if needs_redraw { ... }` block.
|
||||||
|
3. **Flag Reset:** Immediately after a successful `terminal.draw(...)` call, `needs_redraw` is set back to `false`.
|
||||||
|
4. **Triggering Redraws:** The `needs_redraw` flag is explicitly set to `true` only when a redraw is actually required.
|
||||||
|
|
||||||
|
## When `needs_redraw` Must Be Set to `true`
|
||||||
|
|
||||||
|
To ensure the UI stays up-to-date without unnecessary refreshes, `needs_redraw = true;` **must** be set in the following situations:
|
||||||
|
|
||||||
|
1. **After Handling User Input:** When `crossterm_event::poll` returns `true`, indicating a keyboard/mouse event was received and processed by `event_handler.handle_event`.
|
||||||
|
2. **During Active Loading States:** If an asynchronous operation is in progress and a visual indicator (like a loading dialog) is active (e.g., checking `if app_state.ui.dialog.is_loading`). This keeps the loading state visible while waiting for the result.
|
||||||
|
3. **After Processing Async Results:** When the result of an asynchronous operation (e.g., received from an `mpsc::channel` like `login_result_receiver`) is processed and the application state is updated (e.g., dialog content changed, data updated).
|
||||||
|
4. **After Internal State Changes:** If any logic *outside* the direct event handling block modifies state that needs to be visually reflected (e.g., the position change logic loading new data into the form).
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
This approach balances UI responsiveness for asynchronous tasks and user input with CPU efficiency by avoiding redraws when the application state is static.
|
||||||
|
|
||||||
|
## Maintenance Note
|
||||||
|
|
||||||
|
When adding new asynchronous operations or internal logic that modifies UI-relevant state outside the main event handler, developers **must remember** to set `needs_redraw = true` at the appropriate point after the state change to ensure the UI updates correctly. Failure to do so can result in a stale UI.
|
||||||
|
|
||||||
@@ -15,6 +15,7 @@ pub enum DialogPurpose {
|
|||||||
LoginFailed,
|
LoginFailed,
|
||||||
RegisterSuccess,
|
RegisterSuccess,
|
||||||
RegisterFailed,
|
RegisterFailed,
|
||||||
|
ConfirmDeleteColumns, // add_table delete selected Columns
|
||||||
// TODO in the future:
|
// TODO in the future:
|
||||||
// ConfirmQuit,
|
// ConfirmQuit,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,20 +17,35 @@ use crate::state::pages::intro::IntroState;
|
|||||||
use crate::state::app::buffer::BufferState;
|
use crate::state::app::buffer::BufferState;
|
||||||
use crate::state::app::buffer::AppView;
|
use crate::state::app::buffer::AppView;
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
// Import SaveOutcome
|
|
||||||
use crate::tui::terminal::{EventReader, TerminalCore};
|
use crate::tui::terminal::{EventReader, TerminalCore};
|
||||||
use crate::ui::handlers::render::render_ui;
|
use crate::ui::handlers::render::render_ui;
|
||||||
|
use crate::tui::functions::common::login::LoginResult;
|
||||||
|
use crate::tui::functions::common::register::RegisterResult;
|
||||||
|
use crate::tui::functions::common::login;
|
||||||
|
use crate::tui::functions::common::register;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
use crossterm::cursor::SetCursorStyle;
|
use crossterm::cursor::SetCursorStyle;
|
||||||
|
use crossterm::event as crossterm_event;
|
||||||
|
use tracing::error;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
pub async fn run_ui() -> Result<()> {
|
||||||
let config = Config::load()?;
|
let config = Config::load().context("Failed to load configuration")?;
|
||||||
let theme = Theme::from_str(&config.colors.theme);
|
let theme = Theme::from_str(&config.colors.theme);
|
||||||
let mut terminal = TerminalCore::new()?;
|
let mut terminal = TerminalCore::new().context("Failed to initialize terminal")?;
|
||||||
let mut grpc_client = GrpcClient::new().await?;
|
let mut grpc_client = GrpcClient::new().await?;
|
||||||
let mut command_handler = CommandHandler::new();
|
let mut command_handler = CommandHandler::new();
|
||||||
|
|
||||||
let mut event_handler = EventHandler::new().await?;
|
// --- Channel for Login Results ---
|
||||||
|
let (login_result_sender, mut login_result_receiver) =
|
||||||
|
mpsc::channel::<LoginResult>(1);
|
||||||
|
let (register_result_sender, mut register_result_receiver) =
|
||||||
|
mpsc::channel::<RegisterResult>(1);
|
||||||
|
let mut event_handler = EventHandler::new(
|
||||||
|
login_result_sender.clone(),
|
||||||
|
register_result_sender.clone(),
|
||||||
|
).await.context("Failed to create event handler")?;
|
||||||
let event_reader = EventReader::new();
|
let event_reader = EventReader::new();
|
||||||
|
|
||||||
let mut auth_state = AuthState::default();
|
let mut auth_state = AuthState::default();
|
||||||
@@ -39,27 +54,24 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let mut intro_state = IntroState::default();
|
let mut intro_state = IntroState::default();
|
||||||
let mut admin_state = AdminState::default();
|
let mut admin_state = AdminState::default();
|
||||||
let mut buffer_state = BufferState::default();
|
let mut buffer_state = BufferState::default();
|
||||||
let mut app_state = AppState::new()?;
|
let mut app_state = AppState::new().context("Failed to create initial app state")?;
|
||||||
|
|
||||||
// Initialize app state with profile tree and table structure
|
// Initialize app state with profile tree and table structure
|
||||||
let column_names =
|
let column_names =
|
||||||
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
||||||
.await?;
|
.await.context("Failed to initialize app state from UI service")?;
|
||||||
let mut form_state = FormState::new(column_names);
|
let mut form_state = FormState::new(column_names);
|
||||||
|
|
||||||
// Fetch the total count of Adresar entries
|
// Fetch the total count of Adresar entries
|
||||||
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state)
|
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
|
||||||
.await?;
|
|
||||||
form_state.reset_to_empty();
|
form_state.reset_to_empty();
|
||||||
|
|
||||||
// --- FPS Calculation State ---
|
// --- FPS Calculation State ---
|
||||||
let mut last_frame_time = Instant::now();
|
let mut last_frame_time = Instant::now();
|
||||||
let mut current_fps = 0.0;
|
let mut current_fps = 0.0;
|
||||||
|
let mut needs_redraw = true;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
// Determine edit mode based on EventHandler state
|
|
||||||
let is_edit_mode = event_handler.is_edit_mode;
|
|
||||||
|
|
||||||
// --- Synchronize UI View from Active Buffer ---
|
// --- Synchronize UI View from Active Buffer ---
|
||||||
if let Some(active_view) = buffer_state.get_active_view() {
|
if let Some(active_view) = buffer_state.get_active_view() {
|
||||||
// Reset all flags first
|
// Reset all flags first
|
||||||
@@ -87,102 +99,132 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
// --- End Synchronization ---
|
// --- End Synchronization ---
|
||||||
|
|
||||||
terminal.draw(|f| {
|
// --- 3. Draw UI ---
|
||||||
render_ui(
|
// Draw the current state *first*. This ensures the loading dialog
|
||||||
f,
|
// set in the *previous* iteration gets rendered before the pending
|
||||||
&mut form_state,
|
// action check below.
|
||||||
&mut auth_state,
|
if needs_redraw {
|
||||||
&login_state,
|
terminal.draw(|f| {
|
||||||
®ister_state,
|
render_ui(
|
||||||
&intro_state,
|
f,
|
||||||
&mut admin_state,
|
&mut form_state,
|
||||||
&buffer_state,
|
&mut auth_state,
|
||||||
&theme,
|
&login_state,
|
||||||
is_edit_mode,
|
®ister_state,
|
||||||
&event_handler.highlight_state,
|
&intro_state,
|
||||||
app_state.total_count,
|
&mut admin_state,
|
||||||
app_state.current_position,
|
&buffer_state,
|
||||||
&app_state.current_dir,
|
&theme,
|
||||||
&event_handler.command_input,
|
event_handler.is_edit_mode, // Use event_handler's state
|
||||||
event_handler.command_mode,
|
&event_handler.highlight_state,
|
||||||
&event_handler.command_message,
|
app_state.total_count,
|
||||||
current_fps,
|
app_state.current_position,
|
||||||
&app_state,
|
&app_state.current_dir,
|
||||||
);
|
&event_handler.command_input,
|
||||||
})?;
|
event_handler.command_mode,
|
||||||
|
&event_handler.command_message,
|
||||||
|
current_fps,
|
||||||
|
&app_state,
|
||||||
|
);
|
||||||
|
}).context("Terminal draw call failed")?;
|
||||||
|
needs_redraw = false;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Cursor Visibility Logic ---
|
// --- Cursor Visibility Logic ---
|
||||||
|
// (Keep existing cursor logic here - depends on state drawn above)
|
||||||
let current_mode = ModeManager::derive_mode(&app_state, &event_handler);
|
let current_mode = ModeManager::derive_mode(&app_state, &event_handler);
|
||||||
match current_mode {
|
match current_mode {
|
||||||
AppMode::Edit => {
|
AppMode::Edit => { terminal.show_cursor()?; }
|
||||||
terminal.show_cursor()?;
|
AppMode::Highlight => { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.show_cursor()?; }
|
||||||
}
|
|
||||||
AppMode::Highlight => {
|
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
|
|
||||||
terminal.show_cursor()?;
|
|
||||||
}
|
|
||||||
AppMode::ReadOnly => {
|
AppMode::ReadOnly => {
|
||||||
if !app_state.ui.focus_outside_canvas {
|
if !app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; }
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
|
else { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; }
|
||||||
} else {
|
terminal.show_cursor().context("Failed to show cursor in ReadOnly mode")?;
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
|
||||||
}
|
|
||||||
terminal.show_cursor()?;
|
|
||||||
}
|
}
|
||||||
AppMode::General => {
|
AppMode::General => {
|
||||||
if app_state.ui.focus_outside_canvas {
|
if app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor()?; }
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
else { terminal.hide_cursor()?; }
|
||||||
terminal.show_cursor()?;
|
|
||||||
} else {
|
|
||||||
terminal.hide_cursor()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AppMode::Command => {
|
|
||||||
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
|
|
||||||
terminal.show_cursor()?;
|
|
||||||
}
|
}
|
||||||
|
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor().context("Failed to show cursor in Command mode")?; }
|
||||||
}
|
}
|
||||||
// --- End Cursor Visibility Logic ---
|
// --- End Cursor Visibility Logic ---
|
||||||
|
|
||||||
let total_count = app_state.total_count; // Keep track for save logic
|
let total_count = app_state.total_count;
|
||||||
let mut current_position = app_state.current_position;
|
let mut current_position = app_state.current_position;
|
||||||
let position_before_event = current_position;
|
let position_before_event = current_position;
|
||||||
|
// --- Determine if redraw is needed based on active login ---
|
||||||
|
// Always redraw if the loading dialog is currently showing.
|
||||||
|
if app_state.ui.dialog.is_loading {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
let event = event_reader.read_event()?;
|
// --- 1. Handle Terminal Events ---
|
||||||
|
let mut event_outcome_result = Ok(EventOutcome::Ok(String::new()));
|
||||||
// Get the outcome from the event handler
|
// Poll for events *after* drawing and checking pending actions
|
||||||
let event_outcome_result = event_handler
|
if crossterm_event::poll(std::time::Duration::from_millis(1))? {
|
||||||
.handle_event(
|
let event = event_reader.read_event().context("Failed to read terminal event")?;
|
||||||
event,
|
event_outcome_result = event_handler
|
||||||
&config,
|
.handle_event(
|
||||||
&mut terminal,
|
event,
|
||||||
&mut grpc_client,
|
&config,
|
||||||
&mut command_handler,
|
&mut terminal,
|
||||||
&mut form_state,
|
&mut grpc_client,
|
||||||
&mut auth_state,
|
&mut command_handler,
|
||||||
&mut login_state,
|
&mut form_state,
|
||||||
&mut register_state,
|
&mut auth_state,
|
||||||
&mut intro_state,
|
&mut login_state,
|
||||||
&mut admin_state,
|
&mut register_state,
|
||||||
&mut buffer_state,
|
&mut intro_state,
|
||||||
&mut app_state,
|
&mut admin_state,
|
||||||
total_count,
|
&mut buffer_state,
|
||||||
&mut current_position,
|
&mut app_state,
|
||||||
)
|
total_count,
|
||||||
.await;
|
&mut current_position,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Update position based on handler's modification
|
// Update position based on handler's modification
|
||||||
|
// This happens *after* the event is handled
|
||||||
app_state.current_position = current_position;
|
app_state.current_position = current_position;
|
||||||
|
|
||||||
|
// --- Check for Login Results from Channel ---
|
||||||
|
match login_result_receiver.try_recv() {
|
||||||
|
Ok(result) => {
|
||||||
|
if login::handle_login_result(result, &mut app_state, &mut auth_state, &mut login_state) {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Login result channel disconnected unexpectedly.");
|
||||||
|
// Optionally show an error dialog here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Check for Register Results from Channel ---
|
||||||
|
match register_result_receiver.try_recv() {
|
||||||
|
Ok(result) => {
|
||||||
|
if register::handle_registration_result(result, &mut app_state, &mut register_state) {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Register result channel disconnected unexpectedly.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- Centralized Consequence Handling ---
|
// --- Centralized Consequence Handling ---
|
||||||
let mut should_exit = false;
|
let mut should_exit = false;
|
||||||
match event_outcome_result {
|
match event_outcome_result {
|
||||||
// Handle the Result first
|
|
||||||
Ok(outcome) => match outcome {
|
Ok(outcome) => match outcome {
|
||||||
// Handle the Ok variant containing EventOutcome
|
|
||||||
EventOutcome::Ok(message) => {
|
EventOutcome::Ok(message) => {
|
||||||
if !message.is_empty() {
|
if !message.is_empty() {
|
||||||
event_handler.command_message = message;
|
// Update command message only if event handling produced one
|
||||||
|
// Avoid overwriting messages potentially set by pending actions
|
||||||
|
// event_handler.command_message = message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EventOutcome::Exit(message) => {
|
EventOutcome::Exit(message) => {
|
||||||
@@ -191,8 +233,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
EventOutcome::DataSaved(save_outcome, message) => {
|
EventOutcome::DataSaved(save_outcome, message) => {
|
||||||
event_handler.command_message = message; // Show save status
|
event_handler.command_message = message; // Show save status
|
||||||
|
|
||||||
// *** Delegate outcome handling to UiService ***
|
|
||||||
if let Err(e) = UiService::handle_save_outcome(
|
if let Err(e) = UiService::handle_save_outcome(
|
||||||
save_outcome,
|
save_outcome,
|
||||||
&mut grpc_client,
|
&mut grpc_client,
|
||||||
@@ -201,30 +241,27 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
// Handle potential errors from the outcome handler itself
|
|
||||||
event_handler.command_message =
|
event_handler.command_message =
|
||||||
format!("Error handling save outcome: {}", e);
|
format!("Error handling save outcome: {}", e);
|
||||||
}
|
}
|
||||||
// No count update needed for UpdatedExisting or NoChange
|
|
||||||
}
|
}
|
||||||
EventOutcome::ButtonSelected { context, index } => {
|
EventOutcome::ButtonSelected { context: _, index: _ } => {
|
||||||
event_handler.command_message = "Internal error: Unexpected button state".to_string();
|
// This case should ideally be fully handled within handle_event
|
||||||
|
// If initiate_login was called, it returned early.
|
||||||
|
// If not, the message was set and returned via Ok(message).
|
||||||
|
// Log if necessary, but likely no action needed here.
|
||||||
|
// log::warn!("ButtonSelected outcome reached main loop unexpectedly.");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// Handle errors from handle_event, e.g., log or display
|
|
||||||
event_handler.command_message = format!("Error: {}", e);
|
event_handler.command_message = format!("Error: {}", e);
|
||||||
// Decide if the error is fatal, maybe set should_exit = true;
|
|
||||||
}
|
}
|
||||||
}
|
} // --- End Consequence Handling ---
|
||||||
|
|
||||||
// --- Position Change Handling (after outcome processing) ---
|
// --- Position Change Handling (after outcome processing and pending actions) ---
|
||||||
let position_changed =
|
let position_changed = app_state.current_position != position_before_event;
|
||||||
app_state.current_position != position_before_event; // Calculate after potential update
|
|
||||||
// Recalculate total_count *after* potential update
|
|
||||||
let current_total_count = app_state.total_count;
|
let current_total_count = app_state.total_count;
|
||||||
|
let mut position_logic_needs_redraw = false;
|
||||||
// Handle position changes and update form state (Only when form is shown)
|
|
||||||
if app_state.ui.show_form {
|
if app_state.ui.show_form {
|
||||||
if position_changed && !event_handler.is_edit_mode {
|
if position_changed && !event_handler.is_edit_mode {
|
||||||
let current_input = form_state.get_current_input();
|
let current_input = form_state.get_current_input();
|
||||||
@@ -235,6 +272,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
};
|
};
|
||||||
form_state.current_cursor_pos =
|
form_state.current_cursor_pos =
|
||||||
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
|
position_logic_needs_redraw = true;
|
||||||
|
|
||||||
// Ensure position never exceeds total_count + 1
|
// Ensure position never exceeds total_count + 1
|
||||||
if app_state.current_position > current_total_count + 1 {
|
if app_state.current_position > current_total_count + 1 {
|
||||||
@@ -255,7 +293,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
&mut form_state,
|
&mut form_state,
|
||||||
current_position_to_load,
|
current_position_to_load,
|
||||||
)
|
)
|
||||||
.await?;
|
.await.with_context(|| format!("Failed to load adresar by position: {}", current_position_to_load))?;
|
||||||
|
|
||||||
let current_input = form_state.get_current_input();
|
let current_input = form_state.get_current_input();
|
||||||
let max_cursor_pos = if !event_handler.is_edit_mode
|
let max_cursor_pos = if !event_handler.is_edit_mode
|
||||||
@@ -295,7 +333,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
}
|
}
|
||||||
} else if app_state.ui.show_register {
|
} else if app_state.ui.show_register {
|
||||||
if !event_handler.is_edit_mode {
|
if !event_handler.is_edit_mode {
|
||||||
let current_input = register_state.get_current_input();
|
let current_input = register_state.get_current_input();
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
current_input.len() - 1
|
current_input.len() - 1
|
||||||
@@ -305,7 +343,7 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
}
|
}
|
||||||
} else if app_state.ui.show_login {
|
} else if app_state.ui.show_login {
|
||||||
if !event_handler.is_edit_mode {
|
if !event_handler.is_edit_mode {
|
||||||
let current_input = login_state.get_current_input();
|
let current_input = login_state.get_current_input();
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
let max_cursor_pos = if !current_input.is_empty() {
|
||||||
current_input.len() - 1
|
current_input.len() - 1
|
||||||
@@ -315,10 +353,13 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if position_logic_needs_redraw {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
// --- End Position Change Handling ---
|
||||||
|
|
||||||
// Check exit condition *after* processing outcome
|
// Check exit condition *after* all processing for the iteration
|
||||||
if should_exit {
|
if should_exit {
|
||||||
// terminal.cleanup()?; // Optional: Drop handles this
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +370,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
if frame_duration.as_secs_f64() > 1e-6 {
|
if frame_duration.as_secs_f64() > 1e-6 {
|
||||||
current_fps = 1.0 / frame_duration.as_secs_f64();
|
current_fps = 1.0 / frame_duration.as_secs_f64();
|
||||||
}
|
}
|
||||||
}
|
} // End main loop
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user