Skip to main content

rgx/ui/
regex_input.rs

1use ratatui::{
2    buffer::Buffer,
3    layout::Rect,
4    style::{Modifier, Style},
5    text::{Line, Span},
6    widgets::{Block, Borders, Paragraph, Widget},
7};
8
9use crate::input::editor::Editor;
10use crate::ui::theme;
11
12pub struct RegexInput<'a> {
13    pub editor: &'a Editor,
14    pub focused: bool,
15    pub error: Option<&'a str>,
16}
17
18impl<'a> Widget for RegexInput<'a> {
19    fn render(self, area: Rect, buf: &mut Buffer) {
20        let border_style = if self.focused {
21            Style::default().fg(theme::BLUE)
22        } else {
23            Style::default().fg(theme::OVERLAY)
24        };
25
26        let title = if let Some(err) = self.error {
27            let truncated: String = err.chars().take(area.width as usize - 10).collect();
28            format!(" Pattern (Error: {truncated}) ")
29        } else {
30            " Pattern ".to_string()
31        };
32
33        let title_style = if self.error.is_some() {
34            Style::default().fg(theme::RED)
35        } else {
36            Style::default().fg(theme::TEXT)
37        };
38
39        let block = Block::default()
40            .borders(Borders::ALL)
41            .border_style(border_style)
42            .title(Span::styled(title, title_style));
43
44        let content = self.editor.content();
45        let line = Line::from(vec![Span::styled(
46            content.to_string(),
47            Style::default().fg(theme::TEXT),
48        )]);
49
50        let paragraph = Paragraph::new(line)
51            .block(block)
52            .style(Style::default().bg(theme::BASE));
53
54        paragraph.render(area, buf);
55
56        // Render cursor
57        if self.focused {
58            let cursor_x = area.x + 1 + self.editor.visual_cursor() as u16;
59            let cursor_y = area.y + 1;
60            if cursor_x < area.x + area.width - 1 && cursor_y < area.y + area.height - 1 {
61                if let Some(cell) = buf.cell_mut((cursor_x, cursor_y)) {
62                    cell.set_style(
63                        Style::default()
64                            .fg(theme::BASE)
65                            .bg(theme::TEXT)
66                            .add_modifier(Modifier::BOLD),
67                    );
68                }
69            }
70        }
71    }
72}