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
27pub 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), Constraint::Length(8), Constraint::Length(3), Constraint::Min(5), Constraint::Length(1), ])
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 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 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 frame.render_widget(
95 TestInput {
96 editor: &app.test_editor,
97 focused: app.focused_panel == 1,
98 matches: &app.matches,
99 show_whitespace: app.show_whitespace,
100 },
101 layout.test_input,
102 );
103
104 frame.render_widget(
106 ReplaceInput {
107 editor: &app.replace_editor,
108 focused: app.focused_panel == 2,
109 },
110 layout.replace_input,
111 );
112
113 frame.render_widget(
115 MatchDisplay {
116 matches: &app.matches,
117 replace_result: app.replace_result.as_ref(),
118 scroll: app.match_scroll,
119 focused: app.focused_panel == 3,
120 selected_match: app.selected_match,
121 selected_capture: app.selected_capture,
122 clipboard_status: app.clipboard_status.as_deref(),
123 },
124 layout.match_display,
125 );
126
127 frame.render_widget(
129 ExplanationPanel {
130 nodes: &app.explanation,
131 error: error_str,
132 scroll: app.explain_scroll,
133 focused: app.focused_panel == 4,
134 },
135 layout.explanation,
136 );
137
138 frame.render_widget(
140 StatusBar {
141 engine: app.engine_kind,
142 match_count: app.matches.len(),
143 flags: app.flags.clone(),
144 show_whitespace: app.show_whitespace,
145 },
146 layout.status_bar,
147 );
148}
149
150pub const HELP_PAGE_COUNT: usize = 3;
151
152fn build_help_pages(engine: EngineKind) -> Vec<(String, Vec<Line<'static>>)> {
153 let shortcut = |key: &'static str, desc: &'static str| -> Line<'static> {
154 Line::from(vec![
155 Span::styled(format!("{key:<14}"), Style::default().fg(theme::GREEN)),
156 Span::styled(desc, Style::default().fg(theme::TEXT)),
157 ])
158 };
159
160 let page0 = vec![
162 shortcut("Tab", "Cycle focus: pattern/test/replace/matches/explain"),
163 shortcut("Up/Down", "Scroll panel / move cursor / select match"),
164 shortcut("Enter", "Insert newline (test string)"),
165 shortcut("Ctrl+E", "Cycle regex engine"),
166 shortcut("Ctrl+Z", "Undo"),
167 shortcut("Ctrl+Shift+Z", "Redo"),
168 shortcut("Ctrl+Y", "Copy selected match to clipboard"),
169 shortcut("Ctrl+W", "Toggle whitespace visualization"),
170 shortcut("Ctrl+Left/Right", "Move cursor by word"),
171 shortcut("Alt+Up/Down", "Browse pattern history"),
172 shortcut("Alt+i", "Toggle case-insensitive"),
173 shortcut("Alt+m", "Toggle multi-line"),
174 shortcut("Alt+s", "Toggle dot-matches-newline"),
175 shortcut("Alt+u", "Toggle unicode mode"),
176 shortcut("Alt+x", "Toggle extended mode"),
177 shortcut("F1", "Show/hide help (Left/Right to page)"),
178 shortcut("Esc", "Quit"),
179 Line::from(""),
180 Line::from(Span::styled(
181 "Mouse: click to focus/position, scroll to navigate",
182 Style::default().fg(theme::SUBTEXT),
183 )),
184 ];
185
186 let page1 = vec![
188 shortcut(".", "Any character (except newline by default)"),
189 shortcut("\\d \\D", "Digit / non-digit"),
190 shortcut("\\w \\W", "Word char / non-word char"),
191 shortcut("\\s \\S", "Whitespace / non-whitespace"),
192 shortcut("\\b \\B", "Word boundary / non-boundary"),
193 shortcut("^ $", "Start / end of line"),
194 shortcut("[abc]", "Character class"),
195 shortcut("[^abc]", "Negated character class"),
196 shortcut("[a-z]", "Character range"),
197 shortcut("(group)", "Capturing group"),
198 shortcut("(?:group)", "Non-capturing group"),
199 shortcut("(?P<n>...)", "Named capturing group"),
200 shortcut("a|b", "Alternation (a or b)"),
201 shortcut("* + ?", "0+, 1+, 0 or 1 (greedy)"),
202 shortcut("*? +? ??", "Lazy quantifiers"),
203 shortcut("{n} {n,m}", "Exact / range repetition"),
204 Line::from(""),
205 Line::from(Span::styled(
206 "Replacement: $1, ${name}, $0/$&, $$ for literal $",
207 Style::default().fg(theme::SUBTEXT),
208 )),
209 ];
210
211 let engine_name = format!("{engine}");
213 let page2 = match engine {
214 EngineKind::RustRegex => vec![
215 Line::from(Span::styled(
216 "Rust regex engine — linear time guarantee",
217 Style::default().fg(theme::BLUE),
218 )),
219 Line::from(""),
220 shortcut("Unicode", "Full Unicode support by default"),
221 shortcut("No lookbehind", "Use fancy-regex or PCRE2 for lookaround"),
222 shortcut("No backrefs", "Use fancy-regex or PCRE2 for backrefs"),
223 shortcut("\\p{Letter}", "Unicode category"),
224 shortcut("(?i)", "Inline case-insensitive flag"),
225 shortcut("(?m)", "Inline multi-line flag"),
226 shortcut("(?s)", "Inline dot-matches-newline flag"),
227 shortcut("(?x)", "Inline extended/verbose flag"),
228 ],
229 EngineKind::FancyRegex => vec![
230 Line::from(Span::styled(
231 "fancy-regex engine — lookaround + backreferences",
232 Style::default().fg(theme::BLUE),
233 )),
234 Line::from(""),
235 shortcut("(?=...)", "Positive lookahead"),
236 shortcut("(?!...)", "Negative lookahead"),
237 shortcut("(?<=...)", "Positive lookbehind"),
238 shortcut("(?<!...)", "Negative lookbehind"),
239 shortcut("\\1 \\2", "Backreferences"),
240 shortcut("(?>...)", "Atomic group"),
241 Line::from(""),
242 Line::from(Span::styled(
243 "Delegates to Rust regex for non-fancy patterns",
244 Style::default().fg(theme::SUBTEXT),
245 )),
246 ],
247 #[cfg(feature = "pcre2-engine")]
248 EngineKind::Pcre2 => vec![
249 Line::from(Span::styled(
250 "PCRE2 engine — full-featured",
251 Style::default().fg(theme::BLUE),
252 )),
253 Line::from(""),
254 shortcut("(?=...)(?!...)", "Lookahead"),
255 shortcut("(?<=...)(?<!..)", "Lookbehind"),
256 shortcut("\\1 \\2", "Backreferences"),
257 shortcut("(?>...)", "Atomic group"),
258 shortcut("(*SKIP)(*FAIL)", "Backtracking control verbs"),
259 shortcut("(?R) (?1)", "Recursion / subroutine calls"),
260 shortcut("(?(cond)y|n)", "Conditional patterns"),
261 shortcut("\\K", "Reset match start"),
262 shortcut("(*UTF)", "Force UTF-8 mode"),
263 ],
264 };
265
266 vec![
267 ("Keyboard Shortcuts".to_string(), page0),
268 ("Common Regex Syntax".to_string(), page1),
269 (format!("Engine: {engine_name}"), page2),
270 ]
271}
272
273fn render_help_overlay(frame: &mut Frame, area: Rect, engine: EngineKind, page: usize) {
274 let help_width = 64.min(area.width.saturating_sub(4));
275 let help_height = 24.min(area.height.saturating_sub(4));
276 let x = (area.width.saturating_sub(help_width)) / 2;
277 let y = (area.height.saturating_sub(help_height)) / 2;
278 let help_area = Rect::new(x, y, help_width, help_height);
279
280 frame.render_widget(Clear, help_area);
281
282 let pages = build_help_pages(engine);
283 let current = page.min(pages.len() - 1);
284 let (title, content) = &pages[current];
285
286 let mut lines: Vec<Line<'static>> = vec![
287 Line::from(Span::styled(
288 title.clone(),
289 Style::default()
290 .fg(theme::BLUE)
291 .add_modifier(Modifier::BOLD),
292 )),
293 Line::from(""),
294 ];
295 lines.extend(content.iter().cloned());
296 lines.push(Line::from(""));
297 lines.push(Line::from(vec![
298 Span::styled(
299 format!(" Page {}/{} ", current + 1, pages.len()),
300 Style::default().fg(theme::BASE).bg(theme::BLUE),
301 ),
302 Span::styled(
303 " Left/Right: page | Any other key: close ",
304 Style::default().fg(theme::SUBTEXT),
305 ),
306 ]));
307
308 let block = Block::default()
309 .borders(Borders::ALL)
310 .border_style(Style::default().fg(theme::BLUE))
311 .title(Span::styled(" Help ", Style::default().fg(theme::TEXT)))
312 .style(Style::default().bg(theme::BASE));
313
314 let paragraph = Paragraph::new(lines)
315 .block(block)
316 .wrap(Wrap { trim: false });
317
318 frame.render_widget(paragraph, help_area);
319}