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