Skip to main content

rgx/ui/
mod.rs

1pub mod explanation;
2pub mod match_display;
3pub mod regex_input;
4pub mod replace_input;
5pub mod status_bar;
6pub mod syntax_highlight;
7pub mod test_input;
8pub mod theme;
9
10use ratatui::{
11    layout::{Constraint, Direction, Layout, Rect},
12    style::{Modifier, Style},
13    text::{Line, Span},
14    widgets::{Block, Borders, Clear, Paragraph, Wrap},
15    Frame,
16};
17
18use crate::app::App;
19use crate::engine::EngineKind;
20use explanation::ExplanationPanel;
21use match_display::MatchDisplay;
22use regex_input::RegexInput;
23use replace_input::ReplaceInput;
24use status_bar::StatusBar;
25use test_input::TestInput;
26
27/// Panel layout rectangles for mouse hit-testing.
28pub struct PanelLayout {
29    pub regex_input: Rect,
30    pub test_input: Rect,
31    pub replace_input: Rect,
32    pub match_display: Rect,
33    pub explanation: Rect,
34    pub status_bar: Rect,
35}
36
37pub fn compute_layout(size: Rect) -> PanelLayout {
38    let main_chunks = Layout::default()
39        .direction(Direction::Vertical)
40        .constraints([
41            Constraint::Length(3), // regex input
42            Constraint::Length(8), // test string input
43            Constraint::Length(3), // replacement input
44            Constraint::Min(5),    // results area
45            Constraint::Length(1), // status bar
46        ])
47        .split(size);
48
49    let results_chunks = if main_chunks[3].width > 80 {
50        Layout::default()
51            .direction(Direction::Horizontal)
52            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
53            .split(main_chunks[3])
54    } else {
55        Layout::default()
56            .direction(Direction::Vertical)
57            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
58            .split(main_chunks[3])
59    };
60
61    PanelLayout {
62        regex_input: main_chunks[0],
63        test_input: main_chunks[1],
64        replace_input: main_chunks[2],
65        match_display: results_chunks[0],
66        explanation: results_chunks[1],
67        status_bar: main_chunks[4],
68    }
69}
70
71pub fn render(frame: &mut Frame, app: &App) {
72    let size = frame.area();
73    let layout = compute_layout(size);
74
75    // Help overlay
76    if app.show_help {
77        render_help_overlay(frame, size, app.engine_kind, app.help_page);
78        return;
79    }
80
81    let error_str = app.error.as_deref();
82
83    // Regex input
84    frame.render_widget(
85        RegexInput {
86            editor: &app.regex_editor,
87            focused: app.focused_panel == 0,
88            error: error_str,
89        },
90        layout.regex_input,
91    );
92
93    // Test string input
94    frame.render_widget(
95        TestInput {
96            editor: &app.test_editor,
97            focused: app.focused_panel == 1,
98            matches: &app.matches,
99        },
100        layout.test_input,
101    );
102
103    // Replacement input
104    frame.render_widget(
105        ReplaceInput {
106            editor: &app.replace_editor,
107            focused: app.focused_panel == 2,
108        },
109        layout.replace_input,
110    );
111
112    // Match display
113    frame.render_widget(
114        MatchDisplay {
115            matches: &app.matches,
116            replace_result: app.replace_result.as_ref(),
117            scroll: app.match_scroll,
118            focused: app.focused_panel == 3,
119            selected_match: app.selected_match,
120            selected_capture: app.selected_capture,
121            clipboard_status: app.clipboard_status.as_deref(),
122        },
123        layout.match_display,
124    );
125
126    // Explanation panel
127    frame.render_widget(
128        ExplanationPanel {
129            nodes: &app.explanation,
130            error: error_str,
131            scroll: app.explain_scroll,
132            focused: app.focused_panel == 4,
133        },
134        layout.explanation,
135    );
136
137    // Status bar
138    frame.render_widget(
139        StatusBar {
140            engine: app.engine_kind,
141            match_count: app.matches.len(),
142            flags: app.flags.clone(),
143        },
144        layout.status_bar,
145    );
146}
147
148pub const HELP_PAGE_COUNT: usize = 3;
149
150fn build_help_pages(engine: EngineKind) -> Vec<(String, Vec<Line<'static>>)> {
151    let shortcut = |key: &'static str, desc: &'static str| -> Line<'static> {
152        Line::from(vec![
153            Span::styled(format!("{key:<14}"), Style::default().fg(theme::GREEN)),
154            Span::styled(desc, Style::default().fg(theme::TEXT)),
155        ])
156    };
157
158    // Page 0: Keyboard shortcuts
159    let page0 = vec![
160        shortcut("Tab", "Cycle focus: pattern/test/replace/matches/explain"),
161        shortcut("Up/Down", "Scroll panel / move cursor / select match"),
162        shortcut("Enter", "Insert newline (test string)"),
163        shortcut("Ctrl+E", "Cycle regex engine"),
164        shortcut("Ctrl+Z", "Undo"),
165        shortcut("Ctrl+Shift+Z", "Redo"),
166        shortcut("Ctrl+Y", "Copy selected match to clipboard"),
167        shortcut("Alt+Up/Down", "Browse pattern history"),
168        shortcut("Alt+i", "Toggle case-insensitive"),
169        shortcut("Alt+m", "Toggle multi-line"),
170        shortcut("Alt+s", "Toggle dot-matches-newline"),
171        shortcut("Alt+u", "Toggle unicode mode"),
172        shortcut("Alt+x", "Toggle extended mode"),
173        shortcut("F1", "Show/hide help (Left/Right to page)"),
174        shortcut("Esc", "Quit"),
175        Line::from(""),
176        Line::from(Span::styled(
177            "Mouse: click to focus/position, scroll to navigate",
178            Style::default().fg(theme::SUBTEXT),
179        )),
180    ];
181
182    // Page 1: Common regex syntax
183    let page1 = vec![
184        shortcut(".", "Any character (except newline by default)"),
185        shortcut("\\d  \\D", "Digit / non-digit"),
186        shortcut("\\w  \\W", "Word char / non-word char"),
187        shortcut("\\s  \\S", "Whitespace / non-whitespace"),
188        shortcut("\\b  \\B", "Word boundary / non-boundary"),
189        shortcut("^  $", "Start / end of line"),
190        shortcut("[abc]", "Character class"),
191        shortcut("[^abc]", "Negated character class"),
192        shortcut("[a-z]", "Character range"),
193        shortcut("(group)", "Capturing group"),
194        shortcut("(?:group)", "Non-capturing group"),
195        shortcut("(?P<n>...)", "Named capturing group"),
196        shortcut("a|b", "Alternation (a or b)"),
197        shortcut("*  +  ?", "0+, 1+, 0 or 1 (greedy)"),
198        shortcut("*?  +?  ??", "Lazy quantifiers"),
199        shortcut("{n}  {n,m}", "Exact / range repetition"),
200        Line::from(""),
201        Line::from(Span::styled(
202            "Replacement: $1, ${name}, $0/$&, $$ for literal $",
203            Style::default().fg(theme::SUBTEXT),
204        )),
205    ];
206
207    // Page 2: Engine-specific
208    let engine_name = format!("{engine}");
209    let page2 = match engine {
210        EngineKind::RustRegex => vec![
211            Line::from(Span::styled(
212                "Rust regex engine — linear time guarantee",
213                Style::default().fg(theme::BLUE),
214            )),
215            Line::from(""),
216            shortcut("Unicode", "Full Unicode support by default"),
217            shortcut("No lookbehind", "Use fancy-regex or PCRE2 for lookaround"),
218            shortcut("No backrefs", "Use fancy-regex or PCRE2 for backrefs"),
219            shortcut("\\p{Letter}", "Unicode category"),
220            shortcut("(?i)", "Inline case-insensitive flag"),
221            shortcut("(?m)", "Inline multi-line flag"),
222            shortcut("(?s)", "Inline dot-matches-newline flag"),
223            shortcut("(?x)", "Inline extended/verbose flag"),
224        ],
225        EngineKind::FancyRegex => vec![
226            Line::from(Span::styled(
227                "fancy-regex engine — lookaround + backreferences",
228                Style::default().fg(theme::BLUE),
229            )),
230            Line::from(""),
231            shortcut("(?=...)", "Positive lookahead"),
232            shortcut("(?!...)", "Negative lookahead"),
233            shortcut("(?<=...)", "Positive lookbehind"),
234            shortcut("(?<!...)", "Negative lookbehind"),
235            shortcut("\\1  \\2", "Backreferences"),
236            shortcut("(?>...)", "Atomic group"),
237            Line::from(""),
238            Line::from(Span::styled(
239                "Delegates to Rust regex for non-fancy patterns",
240                Style::default().fg(theme::SUBTEXT),
241            )),
242        ],
243        #[cfg(feature = "pcre2-engine")]
244        EngineKind::Pcre2 => vec![
245            Line::from(Span::styled(
246                "PCRE2 engine — full-featured",
247                Style::default().fg(theme::BLUE),
248            )),
249            Line::from(""),
250            shortcut("(?=...)(?!...)", "Lookahead"),
251            shortcut("(?<=...)(?<!..)", "Lookbehind"),
252            shortcut("\\1  \\2", "Backreferences"),
253            shortcut("(?>...)", "Atomic group"),
254            shortcut("(*SKIP)(*FAIL)", "Backtracking control verbs"),
255            shortcut("(?R)  (?1)", "Recursion / subroutine calls"),
256            shortcut("(?(cond)y|n)", "Conditional patterns"),
257            shortcut("\\K", "Reset match start"),
258            shortcut("(*UTF)", "Force UTF-8 mode"),
259        ],
260    };
261
262    vec![
263        ("Keyboard Shortcuts".to_string(), page0),
264        ("Common Regex Syntax".to_string(), page1),
265        (format!("Engine: {engine_name}"), page2),
266    ]
267}
268
269fn render_help_overlay(frame: &mut Frame, area: Rect, engine: EngineKind, page: usize) {
270    let help_width = 64.min(area.width.saturating_sub(4));
271    let help_height = 24.min(area.height.saturating_sub(4));
272    let x = (area.width.saturating_sub(help_width)) / 2;
273    let y = (area.height.saturating_sub(help_height)) / 2;
274    let help_area = Rect::new(x, y, help_width, help_height);
275
276    frame.render_widget(Clear, help_area);
277
278    let pages = build_help_pages(engine);
279    let current = page.min(pages.len() - 1);
280    let (title, content) = &pages[current];
281
282    let mut lines: Vec<Line<'static>> = vec![
283        Line::from(Span::styled(
284            title.clone(),
285            Style::default()
286                .fg(theme::BLUE)
287                .add_modifier(Modifier::BOLD),
288        )),
289        Line::from(""),
290    ];
291    lines.extend(content.iter().cloned());
292    lines.push(Line::from(""));
293    lines.push(Line::from(vec![
294        Span::styled(
295            format!(" Page {}/{} ", current + 1, pages.len()),
296            Style::default().fg(theme::BASE).bg(theme::BLUE),
297        ),
298        Span::styled(
299            " Left/Right: page | Any other key: close ",
300            Style::default().fg(theme::SUBTEXT),
301        ),
302    ]));
303
304    let block = Block::default()
305        .borders(Borders::ALL)
306        .border_style(Style::default().fg(theme::BLUE))
307        .title(Span::styled(" Help ", Style::default().fg(theme::TEXT)))
308        .style(Style::default().bg(theme::BASE));
309
310    let paragraph = Paragraph::new(lines)
311        .block(block)
312        .wrap(Wrap { trim: false });
313
314    frame.render_widget(paragraph, help_area);
315}