clide/src/tui/component.rs

103 lines
2.3 KiB
Rust
Raw Normal View History

2026-01-19 09:23:12 -05:00
#![allow(dead_code, unused_variables)]
use anyhow::Result;
use ratatui::crossterm::event::{Event, KeyEvent, MouseEvent};
2026-01-17 17:09:42 -05:00
pub enum Action {
/// Exit the application.
2026-01-17 17:09:42 -05:00
Quit,
/// The input was checked by the Component and had no effect.
Noop,
/// Pass input to another component or external handler.
/// Similar to Noop with the added context that externally handled input may have had an impact.
Pass,
/// Save the current file.
Save,
/// The input was handled by a Component and should not be passed to the next component.
Handled,
OpenTab,
2026-01-17 17:09:42 -05:00
}
2026-01-19 09:23:12 -05:00
pub trait Component {
fn handle_event(&mut self, event: Event) -> Result<Action> {
match event {
Event::Key(key_event) => self.handle_key_events(key_event),
_ => Ok(Action::Noop),
}
}
fn handle_key_events(&mut self, key: KeyEvent) -> Result<Action> {
Ok(Action::Noop)
2026-01-17 17:09:42 -05:00
}
fn handle_mouse_events(&mut self, mouse: MouseEvent) -> Result<Action> {
Ok(Action::Noop)
2026-01-17 17:09:42 -05:00
}
fn update(&mut self, action: Action) -> Result<Action> {
Ok(Action::Noop)
2026-01-17 17:09:42 -05:00
}
/// Override this method for creating components that conditionally handle input.
fn is_active(&self) -> bool {
true
}
}
#[derive(Debug, Clone, Default)]
pub struct ComponentState {
pub(crate) focus: Focus,
pub(crate) help_text: String,
}
impl ComponentState {
fn new() -> Self {
Self {
focus: Focus::Active,
help_text: String::new(),
}
}
pub(crate) fn with_help_text(mut self, help_text: &str) -> Self {
self.help_text = help_text.into();
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum Focus {
Active,
#[default]
Inactive,
}
pub trait FocusState {
fn with_focus(self, focus: Focus) -> Self;
fn set_focus(&mut self, focus: Focus);
fn toggle_focus(&mut self);
}
impl FocusState for ComponentState {
fn with_focus(self, focus: Focus) -> Self {
Self {
focus,
help_text: self.help_text,
}
}
fn set_focus(&mut self, focus: Focus) {
self.focus = focus;
}
fn toggle_focus(&mut self) {
match self.focus {
Focus::Active => self.set_focus(Focus::Inactive),
Focus::Inactive => self.set_focus(Focus::Active),
}
}
2026-01-17 17:09:42 -05:00
}