use ratatui::{
layout::{Rect, Position}, widgets::{Block, Borders, Paragraph},
Frame, };
use crossterm::event::KeyCode;
use crate::ui::theme;
#[derive(Clone)]
pub struct InputWidget {
input_str: String,
cursor_position: usize,
title: String, }
impl InputWidget {
pub fn new(title: String) -> Self { InputWidget {
input_str: String::new(),
cursor_position: 0,
title, }
}
pub fn get_input(&self) -> String {
self.input_str.clone()
}
pub fn set_input(&mut self, s: String) {
self.input_str = s;
self.cursor_position = self.input_str.len();
}
pub fn reset(&mut self) {
self.input_str.clear();
self.cursor_position = 0;
}
pub fn handle_key(&mut self, key: KeyCode) {
match key {
KeyCode::Char(c) => {
self.input_str.insert(self.cursor_position, c);
self.cursor_position += 1;
}
KeyCode::Backspace => {
if self.cursor_position > 0 {
self.cursor_position -= 1;
self.input_str.remove(self.cursor_position);
}
}
KeyCode::Delete => {
if self.cursor_position < self.input_str.len() {
self.input_str.remove(self.cursor_position);
}
}
KeyCode::Left => {
self.cursor_position = self.cursor_position.saturating_sub(1);
}
KeyCode::Right => {
self.cursor_position = (self.cursor_position + 1).min(self.input_str.len());
}
KeyCode::Home => {
self.cursor_position = 0;
}
KeyCode::End => {
self.cursor_position = self.input_str.len();
}
_ => {}
}
}
pub fn render(&self, f: &mut Frame, area: Rect, is_focused: bool) {
let border_style = if is_focused { theme::HIGHLIGHT_STYLE } else { theme::BORDER_STYLE };
let input_block = Block::default()
.borders(Borders::ALL)
.title(self.title.clone()) .border_style(border_style);
let paragraph = Paragraph::new(self.input_str.as_str()).block(input_block);
f.render_widget(paragraph, area);
if is_focused {
f.set_cursor_position( Position::new(area.x + self.cursor_position as u16 + 1, area.y + 1) );
}
}
}