Compare commits

...

20 Commits

Author SHA1 Message Date
filipriec
d1d33b5752 project redesign 2025-03-23 13:50:47 +01:00
filipriec
c6c6c5ed81 restored rendering 2025-03-23 12:59:36 +01:00
filipriec
4ddcb34205 nothing 2025-03-23 12:56:27 +01:00
filipriec
83393a20e2 fix of the error 2025-03-23 12:44:33 +01:00
filipriec
13d501e6d7 not working 2025-03-23 12:30:00 +01:00
filipriec
993febd204 admin panel keyindings 2025-03-23 11:28:39 +01:00
filipriec
49fe2aa793 edit mode is now perfectly working 2025-03-23 10:55:05 +01:00
filipriec
87a572783a i think its a step in the right direction, needs to export other functions now 2025-03-23 10:03:59 +01:00
filipriec
ca8dea53fd VERY SUSPICIOUS BREAKING FUNCTIONALITY CHECK LATER 2025-03-23 00:49:19 +01:00
filipriec
fef2f12c9a :disabled in the edit mode, cant type it tho, needs fix 2025-03-23 00:28:51 +01:00
filipriec
1a529a70bf gamechanging, commands works only on their windows properly well 2025-03-22 23:32:33 +01:00
filipriec
8da29376ab moved key sequences also 2025-03-22 23:03:13 +01:00
filipriec
8ad5fedcea config was moved successfully 2025-03-22 22:58:58 +01:00
filipriec
16a7fa0bcc working change of the themes 2025-03-22 22:55:43 +01:00
filipriec
5f6858251c moved themes out of the config 2025-03-22 22:51:53 +01:00
filipriec
73567ae5cf moved everything up 2025-03-22 22:40:38 +01:00
filipriec
fe2d1e4684 working perfectly well, needs bug fixes to proper shortcuts to proper windows 2025-03-22 20:10:39 +01:00
filipriec
7d4b043d63 still one error missing 2025-03-22 20:05:13 +01:00
filipriec
04b4220c76 needs bug fixing 2025-03-22 19:37:41 +01:00
filipriec
841418759b last changes 2025-03-22 16:26:38 +01:00
28 changed files with 558 additions and 271 deletions

View File

@@ -1,6 +1,17 @@
# config.toml
[keybindings]
enter_command_mode = [":", "ctrl+;"]
[keybindings.intro]
next_option = ["j", "Right"]
previous_option = ["k", "Left"]
select = ["Enter"]
[keybindings.admin]
move_up = ["k"]
move_down = ["j"]
[keybindings.common]
save = ["ctrl+s"]
quit = ["ctrl+q"]
@@ -33,7 +44,6 @@ move_line_start = ["0"]
move_line_end = ["$"]
move_first_line = ["gg"]
move_last_line = ["x"]
enter_command_mode = [":", "ctrl+;"]
[keybindings.edit]
exit_edit_mode = ["esc","ctrl+e"]

View File

@@ -1,21 +1,49 @@
// src/components/admin/admin_panel.rs
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
style::Style,
text::{Line, Span},
widgets::{Block, BorderType, Borders, Paragraph},
text::{Line, Span, Text},
layout::{Alignment, Constraint, Direction, Layout, Rect},
Frame,
};
use crate::config::colors::Theme;
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::config::colors::themes::Theme;
pub struct AdminPanelState;
pub struct AdminPanelState {
pub list_state: ListState,
pub profiles: Vec<String>,
}
impl AdminPanelState {
pub fn new() -> Self {
Self
pub fn new(profiles: Vec<String>) -> Self {
let mut list_state = ListState::default();
if !profiles.is_empty() {
list_state.select(Some(0));
}
Self { list_state, profiles }
}
pub fn render(&self, f: &mut Frame, area: Rect, theme: &Theme) {
pub fn next(&mut self) {
let i = self.list_state.selected().map_or(0, |i|
if i >= self.profiles.len() - 1 { 0 } else { i + 1 });
self.list_state.select(Some(i));
}
pub fn previous(&mut self) {
let i = self.list_state.selected().map_or(0, |i|
if i == 0 { self.profiles.len() - 1 } else { i - 1 });
self.list_state.select(Some(i));
}
pub fn render(
&mut self,
f: &mut Frame,
area: Rect,
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
@@ -27,18 +55,64 @@ impl AdminPanelState {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(1), // Content
])
.constraints([Constraint::Length(3), Constraint::Min(1)])
.split(inner_area);
// Title
let title = Line::from(Span::styled("Admin Panel", Style::default().fg(theme.highlight)));
let title_para = Paragraph::new(title)
.alignment(Alignment::Center);
f.render_widget(title_para, chunks[0]);
let title_widget = Paragraph::new(title).alignment(Alignment::Center);
f.render_widget(title_widget, chunks[0]);
let content = Paragraph::new("Admin panel content goes here");
f.render_widget(content, chunks[1]);
// Content
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
.split(chunks[1]);
// Profile list
let items: Vec<ListItem> = self.profiles.iter()
.map(|p| ListItem::new(Line::from(vec![
Span::styled(
if Some(p) == selected_profile.as_ref() { "" } else { " " },
Style::default().fg(theme.accent)
),
Span::styled(p, Style::default().fg(theme.fg)),
])))
.collect();
let list = List::new(items)
.block(Block::default().title("Profiles"))
.highlight_style(Style::default().bg(theme.highlight).fg(theme.bg));
f.render_stateful_widget(list, content_chunks[0], &mut self.list_state);
// Profile details
if let Some(profile) = self.list_state.selected()
.and_then(|i| profile_tree.profiles.get(i))
{
let mut text = Text::default();
text.lines.push(Line::from(vec![
Span::styled("Profile: ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]));
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled("Tables:", Style::default().fg(theme.accent))));
for table in &profile.tables {
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
if !table.depends_on.is_empty() {
line.push(Span::styled(
format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary)
));
}
text.lines.push(Line::from(line));
}
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"));
f.render_widget(details_widget, content_chunks[1]);
}
}
}

View File

@@ -5,7 +5,7 @@ use ratatui::{
style::Style,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
pub fn render_background(f: &mut Frame, area: Rect, theme: &Theme) {
let background = Block::default()

View File

@@ -5,7 +5,7 @@ use ratatui::{
layout::Rect,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
pub fn render_command_line(f: &mut Frame, area: Rect, input: &str, active: bool, theme: &Theme, message: &str) {
let prompt = if active {

View File

@@ -6,7 +6,7 @@ use ratatui::{
Frame,
text::{Line, Span},
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use std::path::Path;
pub fn render_status_line(

View File

@@ -7,7 +7,7 @@ use ratatui::{
Frame,
prelude::Alignment,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use crate::ui::form::FormState;
pub fn render_canvas(

View File

@@ -5,7 +5,7 @@ use ratatui::{
style::Style,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use crate::ui::form::FormState;
use super::canvas::render_canvas; // Changed to canvas

View File

@@ -5,7 +5,7 @@ use ratatui::{
style::Style,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use common::proto::multieko2::table_definition::{ProfileTreeResponse};
use ratatui::text::{Span, Line};
@@ -26,41 +26,51 @@ pub fn calculate_sidebar_layout(show_sidebar: bool, main_content_area: Rect) ->
}
}
pub fn render_sidebar(f: &mut Frame, area: Rect, theme: &Theme, profile_tree: &ProfileTreeResponse) {
let sidebar_block = Block::default()
.style(Style::default().bg(theme.bg));
pub fn render_sidebar(
f: &mut Frame,
area: Rect,
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
let sidebar_block = Block::default().style(Style::default().bg(theme.bg));
let mut items = Vec::new();
for profile in &profile_tree.profiles {
// Profile header
items.push(ListItem::new(Line::from(vec![
Span::styled("📁 ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
])));
// Profile tables
for (table_idx, table) in profile.tables.iter().enumerate() {
let is_last_table = table_idx == profile.tables.len() - 1;
let tree_prefix = if is_last_table { "└─ " } else { "├─ " };
// Table name
if let Some(profile_name) = selected_profile {
if let Some(profile) = profile_tree.profiles.iter()
.find(|p| &p.name == profile_name)
{
// Profile header
items.push(ListItem::new(Line::from(vec![
Span::styled(format!(" {}", tree_prefix), Style::default().fg(theme.fg)),
Span::styled(&table.name, Style::default().fg(theme.fg)),
Span::styled("📁 ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
])));
// Dependencies
if !table.depends_on.is_empty() {
let dep_prefix = if is_last_table { " " } else { "" };
let deps = table.depends_on.join(", ");
// Tables
for (table_idx, table) in profile.tables.iter().enumerate() {
let is_last = table_idx == profile.tables.len() - 1;
let prefix = if is_last { "└─ " } else { "├─ " };
items.push(ListItem::new(Line::from(vec![
Span::styled(format!(" {} └─ ", dep_prefix), Style::default().fg(theme.secondary)),
Span::styled(format!("{}", deps), Style::default().fg(theme.secondary)),
])));
let mut line = vec![
Span::styled(format!(" {}", prefix), Style::default().fg(theme.fg)),
Span::styled(&table.name, Style::default().fg(theme.fg)),
];
if !table.depends_on.is_empty() {
line.push(Span::styled(
format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary)
));
}
items.push(ListItem::new(Line::from(line)));
}
}
} else {
items.push(ListItem::new(Span::styled(
"No profile selected",
Style::default().fg(theme.secondary)
)));
}
let list = List::new(items)

View File

@@ -7,7 +7,7 @@ use ratatui::{
prelude::Margin,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
pub struct IntroState {
pub selected_option: usize,

View File

@@ -0,0 +1,7 @@
// src/config/binds.rs
pub mod config;
pub mod key_sequences;
pub use config::*;
pub use key_sequences::*;

View File

@@ -1,4 +1,4 @@
// client/src/config/config.rs
// src/config/binds/config.rs
use serde::Deserialize;
use std::collections::HashMap;
@@ -25,6 +25,10 @@ pub struct Config {
#[derive(Debug, Deserialize)]
pub struct ModeKeybindings {
#[serde(default)]
pub intro: HashMap<String, Vec<String>>,
#[serde(default)]
pub admin: HashMap<String, Vec<String>>,
#[serde(default)]
pub read_only: HashMap<String, Vec<String>>,
#[serde(default)]
@@ -33,7 +37,6 @@ pub struct ModeKeybindings {
pub command: HashMap<String, Vec<String>>,
#[serde(default)]
pub common: HashMap<String, Vec<String>>,
// Store top-level keybindings that aren't in a specific mode section
#[serde(flatten)]
pub global: HashMap<String, Vec<String>>,
}
@@ -49,6 +52,20 @@ impl Config {
Ok(config)
}
/// Gets an action for a key in Intro mode, only checking intro and global bindings
pub fn get_intro_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.intro, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Gets an action for a key in Admin mode, checking common and global bindings
pub fn get_admin_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.admin, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.common, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.intro, key, modifiers))
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Gets an action for a key in Read-Only mode, also checking common keybindings.
pub fn get_read_only_action_for_key(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.read_only, key, modifiers)
@@ -70,6 +87,25 @@ impl Config {
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Context-aware keybinding resolution
pub fn get_action_for_current_context(
&self,
is_edit_mode: bool,
command_mode: bool,
show_intro: bool,
show_admin: bool,
key: KeyCode,
modifiers: KeyModifiers
) -> Option<&str> {
match (show_intro, show_admin, command_mode, is_edit_mode) {
(true, _, _, _) => self.get_intro_action(key, modifiers),
(_, true, _, _) => self.get_admin_action(key, modifiers),
(_, _, true, _) => self.get_command_action_for_key(key, modifiers),
(_, _, _, true) => self.get_edit_action_for_key(key, modifiers),
_ => self.get_read_only_action_for_key(key, modifiers),
}
}
/// Helper function to get an action for a key in a specific mode.
pub fn get_action_for_key_in_mode<'a>(
&self,
@@ -355,13 +391,13 @@ impl Config {
// Get string representations of the sequence
let sequence_str = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("");
// Add the missing sequence_plus definition
let sequence_plus = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("+");
@@ -414,7 +450,7 @@ impl Config {
// Special case for + format in bindings
if binding.contains('+') {
let normalized_sequence = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>();
let binding_parts: Vec<&str> = binding.split('+').collect();
@@ -442,7 +478,7 @@ impl Config {
// Get string representation of the sequence
let sequence_str = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("");
@@ -491,7 +527,7 @@ impl Config {
if binding.contains('+') {
let binding_parts: Vec<&str> = binding.split('+').collect();
let sequence_parts = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>();
if binding_parts.len() > sequence_parts.len() {

View File

@@ -1,68 +1,4 @@
// src/client/colors.rs
use ratatui::style::Color;
// src/config/colors.rs
pub mod themes;
#[derive(Debug, Clone)]
pub struct Theme {
pub bg: Color,
pub fg: Color,
pub accent: Color,
pub secondary: Color,
pub highlight: Color,
pub warning: Color,
pub border: Color,
}
impl Theme {
pub fn from_str(theme_name: &str) -> Self {
match theme_name.to_lowercase().as_str() {
"dark" => Self::dark(),
"high_contrast" => Self::high_contrast(),
_ => Self::light(),
}
}
// Default light theme
pub fn light() -> Self {
Self {
bg: Color::Rgb(245, 245, 245), // Light gray
fg: Color::Rgb(64, 64, 64), // Dark gray
accent: Color::Rgb(173, 216, 230), // Pastel blue
secondary: Color::Rgb(255, 165, 0), // Orange for secondary
highlight: Color::Rgb(152, 251, 152), // Pastel green
warning: Color::Rgb(255, 182, 193), // Pastel pink
border: Color::Rgb(220, 220, 220), // Light gray border
}
}
// High-contrast dark theme
pub fn dark() -> Self {
Self {
bg: Color::Rgb(30, 30, 30), // Dark background
fg: Color::Rgb(255, 255, 255), // White text
accent: Color::Rgb(0, 191, 255), // Bright blue
secondary: Color::Rgb(255, 215, 0), // Gold for secondary
highlight: Color::Rgb(50, 205, 50), // Bright green
warning: Color::Rgb(255, 99, 71), // Bright red
border: Color::Rgb(100, 100, 100), // Medium gray border
}
}
// High-contrast light theme
pub fn high_contrast() -> Self {
Self {
bg: Color::Rgb(255, 255, 255), // White background
fg: Color::Rgb(0, 0, 0), // Black text
accent: Color::Rgb(0, 0, 255), // Blue
secondary: Color::Rgb(255, 140, 0), // Dark orange for secondary
highlight: Color::Rgb(0, 128, 0), // Green
warning: Color::Rgb(255, 0, 0), // Red
border: Color::Rgb(0, 0, 0), // Black border
}
}
}
impl Default for Theme {
fn default() -> Self {
Self::light() // Default to light theme
}
}
pub use themes::*;

View File

@@ -0,0 +1,68 @@
// src/client/themes/colors.rs
use ratatui::style::Color;
#[derive(Debug, Clone)]
pub struct Theme {
pub bg: Color,
pub fg: Color,
pub accent: Color,
pub secondary: Color,
pub highlight: Color,
pub warning: Color,
pub border: Color,
}
impl Theme {
pub fn from_str(theme_name: &str) -> Self {
match theme_name.to_lowercase().as_str() {
"dark" => Self::dark(),
"high_contrast" => Self::high_contrast(),
_ => Self::light(),
}
}
// Default light theme
pub fn light() -> Self {
Self {
bg: Color::Rgb(245, 245, 245), // Light gray
fg: Color::Rgb(64, 64, 64), // Dark gray
accent: Color::Rgb(173, 216, 230), // Pastel blue
secondary: Color::Rgb(255, 165, 0), // Orange for secondary
highlight: Color::Rgb(152, 251, 152), // Pastel green
warning: Color::Rgb(255, 182, 193), // Pastel pink
border: Color::Rgb(220, 220, 220), // Light gray border
}
}
// High-contrast dark theme
pub fn dark() -> Self {
Self {
bg: Color::Rgb(30, 30, 30), // Dark background
fg: Color::Rgb(255, 255, 255), // White text
accent: Color::Rgb(0, 191, 255), // Bright blue
secondary: Color::Rgb(255, 215, 0), // Gold for secondary
highlight: Color::Rgb(50, 205, 50), // Bright green
warning: Color::Rgb(255, 99, 71), // Bright red
border: Color::Rgb(100, 100, 100), // Medium gray border
}
}
// High-contrast light theme
pub fn high_contrast() -> Self {
Self {
bg: Color::Rgb(255, 255, 255), // White background
fg: Color::Rgb(0, 0, 0), // Black text
accent: Color::Rgb(0, 0, 255), // Blue
secondary: Color::Rgb(255, 140, 0), // Dark orange for secondary
highlight: Color::Rgb(0, 128, 0), // Green
warning: Color::Rgb(255, 0, 0), // Red
border: Color::Rgb(0, 0, 0), // Black border
}
}
}
impl Default for Theme {
fn default() -> Self {
Self::light() // Default to light theme
}
}

View File

@@ -1,4 +1,4 @@
// src/config/mod.rs
pub mod binds;
pub mod colors;
pub mod config;
pub mod key_sequences;

View File

@@ -0,0 +1,4 @@
// src/client/modes/canvas.rs
pub mod edit;
pub mod common;
pub mod read_only;

View File

@@ -1,4 +1,4 @@
// src/modes/handlers/common.rs
// src/modes/canvas/common.rs
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::ui::handlers::form::FormState;

View File

@@ -1,12 +1,12 @@
// src/modes/handlers/edit.rs
// src/modes/canvas/edit.rs
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::{
grpc_client::GrpcClient,
};
use crate::config::config::Config;
use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState;
use super::common;
use crate::modes::canvas::common;
pub async fn handle_edit_event_internal(
key: KeyEvent,
@@ -19,6 +19,24 @@ pub async fn handle_edit_event_internal(
total_count: u64,
grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> {
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(&config.keybindings.global, key.code, key.modifiers) {
// Ignore in edit mode and process as normal input
handle_edit_specific_input(key, form_state, ideal_cursor_column);
return Ok(command_message.clone());
}
// Check common actions first
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.common, key.code, key.modifiers) {
return execute_common_action(
action,
form_state,
grpc_client,
is_saved,
current_position,
total_count,
).await;
}
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
return execute_edit_action(
action,
@@ -40,6 +58,48 @@ pub async fn handle_edit_event_internal(
Ok(command_message.clone())
}
async fn execute_common_action(
action: &str,
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client,
is_saved,
current_position,
total_count,
).await
},
"revert" => {
common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await
},
"move_up" | "move_down" => {
// Reuse edit mode's existing logic
execute_edit_action(
action,
form_state,
&mut 0, // Dummy ideal_cursor_column (not used here)
grpc_client,
is_saved,
current_position,
total_count,
).await
},
_ => Ok(format!("Common action not handled: {}", action)),
}
}
fn handle_edit_specific_input(
key: KeyEvent,
form_state: &mut FormState,

View File

@@ -1,9 +1,9 @@
// src/modes/handlers/read_only.rs
use crossterm::event::{KeyEvent};
use crate::config::config::Config;
use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState;
use crate::config::key_sequences::KeySequenceTracker;
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::tui::terminal::grpc_client::GrpcClient;
#[derive(PartialEq)]

View File

@@ -1,6 +1,3 @@
// src/client/modes/handlers.rs
pub mod event;
pub mod edit;
pub mod common;
pub mod command_mode;
pub mod read_only;

View File

@@ -2,9 +2,11 @@
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::config::config::Config;
use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState;
use super::common;
use crate::modes::{
canvas::{common},
};
pub async fn handle_command_event(
key: KeyEvent,

View File

@@ -1,17 +1,19 @@
// src/modes/handlers/event.rs
use crossterm::event::{Event, KeyCode};
use crossterm::event::Event;
use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::{
core::TerminalCore,
grpc_client::GrpcClient,
commands::CommandHandler,
};
use crate::config::config::Config;
use crate::config::binds::config::Config;
use crate::ui::handlers::form::FormState;
use crate::ui::handlers::rat_state::UiStateHandler;
use crate::modes::handlers::{edit, command_mode, read_only};
use crate::config::key_sequences::KeySequenceTracker;
use super::common;
use crate::modes::{
handlers::{command_mode},
canvas::{edit, read_only, common},
};
use crate::config::binds::key_sequences::KeySequenceTracker;
pub struct EventHandler {
pub command_mode: bool,
@@ -51,130 +53,164 @@ impl EventHandler {
) -> Result<(bool, String), Box<dyn std::error::Error>> {
if app_state.ui.show_intro {
if let Event::Key(key) = event {
match key.code {
KeyCode::Left => intro_state.previous_option(),
KeyCode::Right => intro_state.next_option(),
KeyCode::Enter => {
if intro_state.selected_option == 0 {
app_state.ui.show_intro = false;
} else {
app_state.ui.show_intro = false;
app_state.ui.show_admin = true;
}
return Ok((false, String::new()));
}
_ => {}
let action = config.get_intro_action(key.code, key.modifiers);
match action {
Some("previous_option") => intro_state.previous_option(),
Some("next_option") => intro_state.next_option(),
Some("select") => {
app_state.ui.show_intro = false;
app_state.ui.show_admin = intro_state.selected_option == 1;
},
_ => {} // Ignore all other keys
}
}
return Ok((false, String::new()));
}
if let Event::Key(key) = event {
let key_code = key.code;
let modifiers = key.modifiers;
if let Event::Key(key) = event {
let key_code = key.code;
let modifiers = key.modifiers;
if UiStateHandler::toggle_sidebar(
&mut app_state.ui,
config,
key_code,
modifiers,
) {
return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" => {
let message = common::save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
return Ok((false, message));
},
"force_quit" => {
let (should_exit, message) = command_handler.handle_command("force_quit", terminal).await?;
return Ok((should_exit, message));
},
"save_and_quit" => {
let (should_exit, message) = command_handler.handle_command("save_and_quit", terminal).await?;
return Ok((should_exit, message));
},
"revert" => {
let message = common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
return Ok((false, message));
},
_ => {}
// Handle admin panel mode
if app_state.ui.show_admin {
if let Some(action) = config.get_admin_action(key_code, modifiers) {
match action {
"move_up" => {
// Handle up movement using app_state directly
app_state.admin_selected_item = app_state.admin_selected_item.saturating_sub(1);
}
"move_down" => {
// Handle down movement using app_state
app_state.admin_selected_item = app_state.admin_selected_item.saturating_add(1);
}
_ => {}
}
return Ok((false, format!("Admin: {}", action)));
}
return Ok((false, String::new()));
}
}
if self.command_mode {
let (should_exit, message, exit_command_mode) = command_mode::handle_command_event(
key,
if UiStateHandler::toggle_sidebar(
&mut app_state.ui,
config,
form_state,
&mut self.command_input,
&mut self.command_message,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
if exit_command_mode {
self.command_mode = false;
key_code,
modifiers,
) {
return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
return Ok((should_exit, message));
}
// Handle edit mode first to allow normal character input
if self.is_edit_mode {
if config.is_exit_edit_mode(key_code, modifiers) {
if form_state.has_unsaved_changes {
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
return Ok((false, self.command_message.clone()));
}
self.is_edit_mode = false;
self.edit_mode_cooldown = true;
self.command_message = "Read-only mode".to_string();
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
if self.is_edit_mode {
if config.is_exit_edit_mode(key_code, modifiers) {
if form_state.has_unsaved_changes {
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos >= current_input.len() {
form_state.current_cursor_pos = current_input.len() - 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
}
return Ok((false, self.command_message.clone()));
}
self.is_edit_mode = false;
self.edit_mode_cooldown = true;
self.command_message = "Read-only mode".to_string();
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos >= current_input.len() {
form_state.current_cursor_pos = current_input.len() - 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
}
return Ok((false, self.command_message.clone()));
let result = edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?;
self.key_sequence_tracker.reset();
return Ok((false, result));
}
let result = edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.ui.is_saved,
current_position,
total_count,
grpc_client,
).await?;
// Global command mode activation
let context_action = config.get_action_for_current_context(
self.is_edit_mode,
self.command_mode,
app_state.ui.show_intro,
app_state.ui.show_admin,
key_code,
modifiers
);
if let Some("enter_command_mode") = context_action {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok((false, String::new()));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" => {
let message = common::save(
form_state,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
return Ok((false, message));
},
"force_quit" => {
let (should_exit, message) = command_handler.handle_command("force_quit", terminal).await?;
return Ok((should_exit, message));
},
"save_and_quit" => {
let (should_exit, message) = command_handler.handle_command("save_and_quit", terminal).await?;
return Ok((should_exit, message));
},
"revert" => {
let message = common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
return Ok((false, message));
},
_ => {}
}
}
if self.command_mode {
let (should_exit, message, exit_command_mode) = command_mode::handle_command_event(
key,
config,
form_state,
&mut self.command_input,
&mut self.command_message,
grpc_client,
&mut app_state.ui.is_saved,
current_position,
total_count,
).await?;
if exit_command_mode {
self.command_mode = false;
}
return Ok((should_exit, message));
}
self.key_sequence_tracker.reset();
return Ok((false, result));
} else {
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
if action == "enter_command_mode" {
self.command_mode = true;
@@ -218,7 +254,6 @@ impl EventHandler {
&mut self.ideal_cursor_column,
).await;
}
}
self.edit_mode_cooldown = false;
Ok((false, self.command_message.clone()))

View File

@@ -1,4 +1,6 @@
// src/client/modes/mod.rs
pub mod handlers;
pub mod canvas;
pub use handlers::*;
pub use canvas::*;

View File

@@ -16,6 +16,9 @@ pub struct AppState {
pub total_count: u64,
pub current_position: u64,
pub profile_tree: ProfileTreeResponse,
pub selected_profile: Option<String>,
pub admin_selected_item: usize, // Tracks selection in admin panel
pub admin_profiles: Vec<String>, // Stores admin panel data
// UI preferences
pub ui: UiState,
@@ -31,6 +34,9 @@ impl AppState {
total_count: 0,
current_position: 0,
profile_tree: ProfileTreeResponse::default(),
selected_profile: None,
admin_selected_item: 0,
admin_profiles: Vec::new(),
ui: UiState::default(),
})
}

View File

@@ -1,5 +1,5 @@
// src/client/ui/handlers/form.rs
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use ratatui::layout::Rect;
use ratatui::Frame;

View File

@@ -1,6 +1,6 @@
// src/ui/handlers/rat_state.rs
use crossterm::event::{KeyCode, KeyModifiers};
use crate::config::config::Config;
use crate::config::binds::config::Config;
use crate::state::state::UiState;
pub struct UiStateHandler;

View File

@@ -4,10 +4,11 @@ use crate::components::{
render_background,
render_command_line,
render_status_line,
handlers::{sidebar::{self, calculate_sidebar_layout}, admin_panel::AdminPanelState, form::render_form},
handlers::{sidebar::{self, calculate_sidebar_layout}, form::render_form},
intro::{intro},
admin::{admin_panel::AdminPanelState},
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::Frame;
use super::form::FormState;
@@ -26,7 +27,6 @@ pub fn render_ui(
command_message: &str,
app_state: &AppState,
intro_state: &intro::IntroState,
admin_panel_state: &AdminPanelState,
) {
render_background(f, f.area(), theme);
@@ -43,7 +43,32 @@ pub fn render_ui(
if app_state.ui.show_intro {
intro_state.render(f, main_content_area, theme);
} else if app_state.ui.show_admin {
admin_panel_state.render(f, main_content_area, theme);
// Create temporary AdminPanelState for rendering
let mut admin_state = AdminPanelState::new(
if app_state.admin_profiles.is_empty() {
// Fallback if admin_profiles is empty
app_state.profile_tree.profiles
.iter()
.map(|p| p.name.clone())
.collect()
} else {
app_state.admin_profiles.clone()
}
);
// Set the selected item
if !admin_state.profiles.is_empty() {
let safe_index = app_state.admin_selected_item.min(admin_state.profiles.len() - 1);
admin_state.list_state.select(Some(safe_index));
}
admin_state.render(
f,
main_content_area,
theme,
&app_state.profile_tree,
&app_state.selected_profile,
);
} else {
let (sidebar_area, form_area) = calculate_sidebar_layout(
app_state.ui.show_sidebar,
@@ -51,7 +76,13 @@ pub fn render_ui(
);
if let Some(sidebar_rect) = sidebar_area {
sidebar::render_sidebar(f, sidebar_rect, theme, &app_state.profile_tree);
sidebar::render_sidebar(
f,
sidebar_rect,
theme,
&app_state.profile_tree,
&app_state.selected_profile // Remove trailing comma
);
}
// This change makes the form stay stationary when toggling sidebar

View File

@@ -1,15 +1,15 @@
// src/client/ui/handlers/ui.rs
// src/ui/handlers/ui.rs
use crate::tui::terminal::TerminalCore;
use crate::tui::terminal::GrpcClient;
use crate::tui::terminal::CommandHandler;
use crate::tui::terminal::EventReader;
use crate::config::colors::Theme;
use crate::config::config::Config;
use crate::config::colors::themes::Theme;
use crate::config::binds::config::Config;
use crate::ui::handlers::{form::FormState, render::render_ui};
use crate::modes::handlers::event::EventHandler;
use crate::state::state::AppState;
use crate::components::handlers::{admin_panel::AdminPanelState};
use crate::components::admin::{admin_panel::AdminPanelState};
use crate::components::intro::{intro::IntroState};
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
@@ -19,10 +19,25 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme);
let mut intro_state = IntroState::new();
let admin_panel_state = AdminPanelState::new();
// Initialize app_state first
let mut app_state = AppState::new()?;
// Fetch profile tree and table structure
let profile_tree = grpc_client.get_profile_tree().await?;
app_state.profile_tree = profile_tree;
// Now create admin panel with profiles from app_state
if intro_state.selected_option == 1 {
app_state.ui.show_admin = true;
app_state.admin_profiles = app_state.profile_tree.profiles
.iter()
.map(|p| p.name.clone())
.collect();
app_state.admin_selected_item = 0;
}
// Fetch table structure at startup (one-time)
// TODO: Later, consider implementing a live update for table structure changes.
let table_structure = grpc_client.get_table_structure().await?;
// Extract the column names from the response
@@ -35,13 +50,9 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
// Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names);
// Fetch profile tree and table structure
let profile_tree = grpc_client.get_profile_tree().await?;
// The rest of your UI initialization remains the same
let mut event_handler = EventHandler::new();
let event_reader = EventReader::new();
let mut app_state = AppState::new()?;
app_state.profile_tree = profile_tree;
// Fetch the total count of Adresar entries
let total_count = grpc_client.get_adresar_count().await?;
@@ -67,7 +78,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
&event_handler.command_message,
&app_state,
&intro_state,
&admin_panel_state,
);
})?;
@@ -100,7 +110,6 @@ pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
// Ensure position never exceeds total_count + 1
if app_state.current_position > total_count + 1 {
app_state.current_position = total_count + 1;