Skip to main content

fresh/view/ui/
file_browser.rs

1//! File browser popup renderer for the Open File dialog
2//!
3//! Renders a structured popup above the prompt with:
4//! - Navigation shortcuts (parent, root, home)
5//! - Sortable column headers (name, size, modified)
6//! - File list with metadata
7//! - Scrollbar for long lists
8
9use super::scrollbar::{render_scrollbar, ScrollbarColors, ScrollbarState};
10use super::status_bar::truncate_path;
11use crate::app::file_open::{
12    format_modified, format_size, FileOpenSection, FileOpenState, SortMode,
13};
14use crate::primitives::display_width::str_width;
15use ratatui::layout::Rect;
16use ratatui::style::{Modifier, Style};
17use ratatui::text::{Line, Span};
18use ratatui::widgets::{Block, Borders, Clear, Paragraph};
19use ratatui::Frame;
20use rust_i18n::t;
21
22/// Renderer for the file browser popup
23pub struct FileBrowserRenderer;
24
25impl FileBrowserRenderer {
26    /// Render the file browser popup
27    ///
28    /// # Arguments
29    /// * `frame` - The ratatui frame to render to
30    /// * `area` - The rectangular area for the popup (above the prompt)
31    /// * `state` - The file open dialog state
32    /// * `theme` - The active theme for colors
33    /// * `hover_target` - Current mouse hover target (for highlighting)
34    /// * `keybindings` - Optional keybinding resolver for displaying shortcuts
35    ///
36    /// # Returns
37    /// Information for mouse hit testing (scrollbar area, thumb positions, etc.)
38    pub fn render(
39        frame: &mut Frame,
40        area: Rect,
41        state: &FileOpenState,
42        theme: &crate::view::theme::Theme,
43        hover_target: &Option<crate::app::HoverTarget>,
44        keybindings: Option<&crate::input::keybindings::KeybindingResolver>,
45    ) -> Option<FileBrowserLayout> {
46        if area.height < 5 || area.width < 20 {
47            return None;
48        }
49
50        // Clear the area behind the popup
51        frame.render_widget(Clear, area);
52
53        // Truncate path for title if needed (leave space for borders and padding)
54        let max_title_len = (area.width as usize).saturating_sub(4); // 2 for borders, 2 for padding
55        let truncated_path = truncate_path(&state.current_dir, max_title_len);
56        let title = format!(" {} ", truncated_path.to_string_plain());
57
58        // Create styled title with highlighted [...] if truncated
59        let title_line = if truncated_path.truncated {
60            Line::from(vec![
61                Span::raw(" "),
62                Span::styled(
63                    truncated_path.prefix.clone(),
64                    Style::default().fg(theme.popup_border_fg),
65                ),
66                Span::styled("/[...]", Style::default().fg(theme.menu_highlight_fg)),
67                Span::styled(
68                    truncated_path.suffix.clone(),
69                    Style::default().fg(theme.popup_border_fg),
70                ),
71                Span::raw(" "),
72            ])
73        } else {
74            Line::from(title)
75        };
76
77        // Create the popup block with border
78        let block = Block::default()
79            .borders(Borders::ALL)
80            .border_style(Style::default().fg(theme.popup_border_fg))
81            .style(Style::default().bg(theme.popup_bg))
82            .title(title_line);
83
84        let inner_area = block.inner(area);
85        frame.render_widget(block, area);
86
87        if inner_area.height < 3 || inner_area.width < 10 {
88            return None;
89        }
90
91        // Layout: Navigation (2-3 rows) | Header (1 row) | File list (remaining) | Scrollbar (1 col)
92        let nav_height = 2u16; // Navigation shortcuts section
93        let header_height = 1u16;
94        let scrollbar_width = 1u16;
95
96        let content_width = inner_area.width.saturating_sub(scrollbar_width);
97        let list_height = inner_area.height.saturating_sub(nav_height + header_height);
98
99        // Navigation area
100        let nav_area = Rect::new(inner_area.x, inner_area.y, content_width, nav_height);
101
102        // Header area
103        let header_area = Rect::new(
104            inner_area.x,
105            inner_area.y + nav_height,
106            content_width,
107            header_height,
108        );
109
110        // File list area
111        let list_area = Rect::new(
112            inner_area.x,
113            inner_area.y + nav_height + header_height,
114            content_width,
115            list_height,
116        );
117
118        // Scrollbar area
119        let scrollbar_area = Rect::new(
120            inner_area.x + content_width,
121            inner_area.y + nav_height + header_height,
122            scrollbar_width,
123            list_height,
124        );
125
126        // Render each section with hover state
127        Self::render_navigation(frame, nav_area, state, theme, hover_target, keybindings);
128        Self::render_header(frame, header_area, state, theme, hover_target);
129        let visible_rows = Self::render_file_list(frame, list_area, state, theme, hover_target);
130
131        // Render scrollbar with theme colors (hover-aware)
132        let scrollbar_state =
133            ScrollbarState::new(state.entries.len(), visible_rows, state.scroll_offset);
134        let is_scrollbar_hovered = matches!(
135            hover_target,
136            Some(crate::app::HoverTarget::FileBrowserScrollbar)
137        );
138        let colors = if is_scrollbar_hovered {
139            ScrollbarColors::from_theme_hover(theme)
140        } else {
141            ScrollbarColors::from_theme(theme)
142        };
143        let (thumb_start, thumb_end) =
144            render_scrollbar(frame, scrollbar_area, &scrollbar_state, &colors);
145
146        Some(FileBrowserLayout {
147            popup_area: area,
148            nav_area,
149            header_area,
150            list_area,
151            scrollbar_area,
152            thumb_start,
153            thumb_end,
154            visible_rows,
155            content_width,
156        })
157    }
158
159    /// Render navigation shortcuts section with checkboxes on first row
160    fn render_navigation(
161        frame: &mut Frame,
162        area: Rect,
163        state: &FileOpenState,
164        theme: &crate::view::theme::Theme,
165        hover_target: &Option<crate::app::HoverTarget>,
166        keybindings: Option<&crate::input::keybindings::KeybindingResolver>,
167    ) {
168        use crate::app::HoverTarget;
169
170        // Look up keybindings for toggle actions
171        let hidden_shortcut = keybindings
172            .and_then(|kb| {
173                kb.get_keybinding_for_action(
174                    &crate::input::keybindings::Action::FileBrowserToggleHidden,
175                    crate::input::keybindings::KeyContext::Prompt,
176                )
177            })
178            .unwrap_or_default();
179
180        let encoding_shortcut = keybindings
181            .and_then(|kb| {
182                kb.get_keybinding_for_action(
183                    &crate::input::keybindings::Action::FileBrowserToggleDetectEncoding,
184                    crate::input::keybindings::KeyContext::Prompt,
185                )
186            })
187            .unwrap_or_default();
188
189        // First line: "Show Hidden" and "Detect Encoding" checkboxes
190        let mut checkbox_spans = Vec::new();
191
192        // Show Hidden checkbox
193        let hidden_icon = if state.show_hidden { "☑" } else { "☐" };
194        let hidden_label = format!("{} {}", hidden_icon, t!("file_browser.show_hidden"));
195        let hidden_shortcut_text = if hidden_shortcut.is_empty() {
196            String::new()
197        } else {
198            format!(" ({})", hidden_shortcut)
199        };
200
201        let is_hidden_hovered = matches!(
202            hover_target,
203            Some(HoverTarget::FileBrowserShowHiddenCheckbox)
204        );
205        let hidden_style = if is_hidden_hovered {
206            Style::default()
207                .fg(theme.menu_hover_fg)
208                .bg(theme.menu_hover_bg)
209        } else if state.show_hidden {
210            Style::default()
211                .fg(theme.menu_highlight_fg)
212                .bg(theme.popup_bg)
213        } else {
214            Style::default().fg(theme.help_key_fg).bg(theme.popup_bg)
215        };
216        let hidden_shortcut_style = if is_hidden_hovered {
217            Style::default()
218                .fg(theme.menu_hover_fg)
219                .bg(theme.menu_hover_bg)
220        } else {
221            Style::default()
222                .fg(theme.help_separator_fg)
223                .bg(theme.popup_bg)
224        };
225
226        checkbox_spans.push(Span::styled(format!(" {}", hidden_label), hidden_style));
227        if !hidden_shortcut_text.is_empty() {
228            checkbox_spans.push(Span::styled(hidden_shortcut_text, hidden_shortcut_style));
229        }
230
231        // Separator between checkboxes
232        checkbox_spans.push(Span::styled(
233            " │ ",
234            Style::default()
235                .fg(theme.help_separator_fg)
236                .bg(theme.popup_bg),
237        ));
238
239        // Detect Encoding checkbox with underlined E
240        let encoding_icon = if state.detect_encoding { "☑" } else { "☐" };
241        let is_encoding_hovered = matches!(
242            hover_target,
243            Some(HoverTarget::FileBrowserDetectEncodingCheckbox)
244        );
245        let encoding_style = if is_encoding_hovered {
246            Style::default()
247                .fg(theme.menu_hover_fg)
248                .bg(theme.menu_hover_bg)
249        } else if state.detect_encoding {
250            Style::default()
251                .fg(theme.menu_highlight_fg)
252                .bg(theme.popup_bg)
253        } else {
254            Style::default().fg(theme.help_key_fg).bg(theme.popup_bg)
255        };
256        let encoding_underline_style = if is_encoding_hovered {
257            Style::default()
258                .fg(theme.menu_hover_fg)
259                .bg(theme.menu_hover_bg)
260                .add_modifier(Modifier::UNDERLINED)
261        } else if state.detect_encoding {
262            Style::default()
263                .fg(theme.menu_highlight_fg)
264                .bg(theme.popup_bg)
265                .add_modifier(Modifier::UNDERLINED)
266        } else {
267            Style::default()
268                .fg(theme.help_key_fg)
269                .bg(theme.popup_bg)
270                .add_modifier(Modifier::UNDERLINED)
271        };
272        let encoding_shortcut_style = if is_encoding_hovered {
273            Style::default()
274                .fg(theme.menu_hover_fg)
275                .bg(theme.menu_hover_bg)
276        } else {
277            Style::default()
278                .fg(theme.help_separator_fg)
279                .bg(theme.popup_bg)
280        };
281
282        // "☐ Detect " + "E" (underlined) + "ncoding"
283        checkbox_spans.push(Span::styled(
284            format!("{} Detect ", encoding_icon),
285            encoding_style,
286        ));
287        checkbox_spans.push(Span::styled("E", encoding_underline_style));
288        checkbox_spans.push(Span::styled("ncoding", encoding_style));
289
290        if !encoding_shortcut.is_empty() {
291            checkbox_spans.push(Span::styled(
292                format!(" ({})", encoding_shortcut),
293                encoding_shortcut_style,
294            ));
295        }
296
297        // Fill rest of row with background
298        let checkbox_line_width: usize = checkbox_spans.iter().map(|s| str_width(&s.content)).sum();
299        let remaining = (area.width as usize).saturating_sub(checkbox_line_width);
300        if remaining > 0 {
301            checkbox_spans.push(Span::styled(
302                " ".repeat(remaining),
303                Style::default().bg(theme.popup_bg),
304            ));
305        }
306        let checkbox_line = Line::from(checkbox_spans);
307
308        // Second line: Navigation shortcuts
309        let is_nav_active = state.active_section == FileOpenSection::Navigation;
310
311        let mut nav_spans = Vec::new();
312        nav_spans.push(Span::styled(
313            format!(" {}", t!("file_browser.navigation")),
314            Style::default()
315                .fg(theme.help_separator_fg)
316                .bg(theme.popup_bg),
317        ));
318
319        for (idx, shortcut) in state.shortcuts.iter().enumerate() {
320            let is_selected = is_nav_active && idx == state.selected_shortcut;
321            let is_hovered =
322                matches!(hover_target, Some(HoverTarget::FileBrowserNavShortcut(i)) if *i == idx);
323
324            let style = if is_selected {
325                Style::default()
326                    .fg(theme.popup_text_fg)
327                    .bg(theme.suggestion_selected_bg)
328                    .add_modifier(Modifier::BOLD)
329            } else if is_hovered {
330                Style::default()
331                    .fg(theme.menu_hover_fg)
332                    .bg(theme.menu_hover_bg)
333            } else {
334                Style::default().fg(theme.help_key_fg).bg(theme.popup_bg)
335            };
336
337            nav_spans.push(Span::styled(format!(" {} ", shortcut.label), style));
338
339            if idx < state.shortcuts.len() - 1 {
340                nav_spans.push(Span::styled(
341                    " │ ",
342                    Style::default()
343                        .fg(theme.help_separator_fg)
344                        .bg(theme.popup_bg),
345                ));
346            }
347        }
348
349        // Fill rest of navigation row with background
350        let nav_line_width: usize = nav_spans.iter().map(|s| str_width(&s.content)).sum();
351        let nav_remaining = (area.width as usize).saturating_sub(nav_line_width);
352        if nav_remaining > 0 {
353            nav_spans.push(Span::styled(
354                " ".repeat(nav_remaining),
355                Style::default().bg(theme.popup_bg),
356            ));
357        }
358        let nav_line = Line::from(nav_spans);
359
360        let paragraph = Paragraph::new(vec![checkbox_line, nav_line]);
361        frame.render_widget(paragraph, area);
362    }
363
364    /// Render sortable column headers
365    fn render_header(
366        frame: &mut Frame,
367        area: Rect,
368        state: &FileOpenState,
369        theme: &crate::view::theme::Theme,
370        hover_target: &Option<crate::app::HoverTarget>,
371    ) {
372        use crate::app::HoverTarget;
373
374        let width = area.width as usize;
375
376        // Column widths
377        let size_col_width = 10;
378        let date_col_width = 14;
379        let name_col_width = width.saturating_sub(size_col_width + date_col_width + 4);
380
381        let header_style = Style::default()
382            .fg(theme.help_key_fg)
383            .bg(theme.menu_dropdown_bg)
384            .add_modifier(Modifier::BOLD);
385
386        let active_header_style = Style::default()
387            .fg(theme.menu_highlight_fg)
388            .bg(theme.menu_dropdown_bg)
389            .add_modifier(Modifier::BOLD);
390
391        let hover_header_style = Style::default()
392            .fg(theme.menu_hover_fg)
393            .bg(theme.menu_hover_bg)
394            .add_modifier(Modifier::BOLD);
395
396        // Sort indicator
397        let sort_arrow = if state.sort_ascending { "▲" } else { "▼" };
398
399        let mut spans = Vec::new();
400
401        // Name column
402        let name_header = format!(
403            " {}{}",
404            t!("file_browser.name"),
405            if state.sort_mode == SortMode::Name {
406                sort_arrow
407            } else {
408                " "
409            }
410        );
411        let is_name_hovered = matches!(
412            hover_target,
413            Some(HoverTarget::FileBrowserHeader(SortMode::Name))
414        );
415        let name_style = if state.sort_mode == SortMode::Name {
416            active_header_style
417        } else if is_name_hovered {
418            hover_header_style
419        } else {
420            header_style
421        };
422        let name_display = if name_header.len() < name_col_width {
423            format!("{:<width$}", name_header, width = name_col_width)
424        } else {
425            name_header[..name_col_width].to_string()
426        };
427        spans.push(Span::styled(name_display, name_style));
428
429        // Size column
430        let size_header = format!(
431            "{:>width$}",
432            format!(
433                "{}{}",
434                t!("file_browser.size"),
435                if state.sort_mode == SortMode::Size {
436                    sort_arrow
437                } else {
438                    " "
439                }
440            ),
441            width = size_col_width
442        );
443        let is_size_hovered = matches!(
444            hover_target,
445            Some(HoverTarget::FileBrowserHeader(SortMode::Size))
446        );
447        let size_style = if state.sort_mode == SortMode::Size {
448            active_header_style
449        } else if is_size_hovered {
450            hover_header_style
451        } else {
452            header_style
453        };
454        spans.push(Span::styled(size_header, size_style));
455
456        // Separator
457        spans.push(Span::styled("  ", header_style));
458
459        // Modified column
460        let modified_header = format!(
461            "{:>width$}",
462            format!(
463                "{}{}",
464                t!("file_browser.modified"),
465                if state.sort_mode == SortMode::Modified {
466                    sort_arrow
467                } else {
468                    " "
469                }
470            ),
471            width = date_col_width
472        );
473        let is_modified_hovered = matches!(
474            hover_target,
475            Some(HoverTarget::FileBrowserHeader(SortMode::Modified))
476        );
477        let modified_style = if state.sort_mode == SortMode::Modified {
478            active_header_style
479        } else if is_modified_hovered {
480            hover_header_style
481        } else {
482            header_style
483        };
484        spans.push(Span::styled(modified_header, modified_style));
485
486        let line = Line::from(spans);
487        let paragraph = Paragraph::new(vec![line]);
488        frame.render_widget(paragraph, area);
489    }
490
491    /// Render the file list with metadata columns
492    ///
493    /// Returns the number of visible rows
494    fn render_file_list(
495        frame: &mut Frame,
496        area: Rect,
497        state: &FileOpenState,
498        theme: &crate::view::theme::Theme,
499        hover_target: &Option<crate::app::HoverTarget>,
500    ) -> usize {
501        use crate::app::HoverTarget;
502
503        let visible_rows = area.height as usize;
504        let width = area.width as usize;
505
506        // Column widths (matching header)
507        let size_col_width = 10;
508        let date_col_width = 14;
509        let name_col_width = width.saturating_sub(size_col_width + date_col_width + 4);
510
511        let is_files_active = state.active_section == FileOpenSection::Files;
512
513        // Loading state
514        if state.loading {
515            let loading_line = Line::from(Span::styled(
516                t!("file_browser.loading").to_string(),
517                Style::default()
518                    .fg(theme.help_separator_fg)
519                    .bg(theme.popup_bg),
520            ));
521            let paragraph = Paragraph::new(vec![loading_line]);
522            frame.render_widget(paragraph, area);
523            return visible_rows;
524        }
525
526        // Error state
527        if let Some(error) = &state.error {
528            let error_line = Line::from(Span::styled(
529                t!("file_browser.error", error = error).to_string(),
530                Style::default()
531                    .fg(theme.diagnostic_error_fg)
532                    .bg(theme.popup_bg),
533            ));
534            let paragraph = Paragraph::new(vec![error_line]);
535            frame.render_widget(paragraph, area);
536            return visible_rows;
537        }
538
539        // Empty state
540        if state.entries.is_empty() {
541            let empty_line = Line::from(Span::styled(
542                format!(" {}", t!("file_browser.empty")),
543                Style::default()
544                    .fg(theme.help_separator_fg)
545                    .bg(theme.popup_bg),
546            ));
547            let paragraph = Paragraph::new(vec![empty_line]);
548            frame.render_widget(paragraph, area);
549            return visible_rows;
550        }
551
552        let mut lines = Vec::new();
553        let visible_entries = state.visible_entries(visible_rows);
554
555        for (view_idx, entry) in visible_entries.iter().enumerate() {
556            let actual_idx = state.scroll_offset + view_idx;
557            let is_selected = is_files_active && state.selected_index == Some(actual_idx);
558            let is_hovered =
559                matches!(hover_target, Some(HoverTarget::FileBrowserEntry(i)) if *i == actual_idx);
560
561            // Base style based on selection, hover, and filter match
562            let base_style = if is_selected {
563                Style::default()
564                    .fg(theme.popup_text_fg)
565                    .bg(theme.suggestion_selected_bg)
566            } else if is_hovered && entry.matches_filter {
567                Style::default()
568                    .fg(theme.menu_hover_fg)
569                    .bg(theme.menu_hover_bg)
570            } else if !entry.matches_filter {
571                // Non-matching items are dimmed using the separator color
572                Style::default()
573                    .fg(theme.help_separator_fg)
574                    .bg(theme.popup_bg)
575                    .add_modifier(Modifier::DIM)
576            } else {
577                Style::default().fg(theme.popup_text_fg).bg(theme.popup_bg)
578            };
579
580            let mut spans = Vec::new();
581
582            // Name column with trailing type indicator (dirs get /, symlinks get @)
583            let name_with_indicator = if entry.fs_entry.is_dir() {
584                format!("{}/", entry.fs_entry.name)
585            } else if entry.fs_entry.is_symlink() {
586                format!("{}@", entry.fs_entry.name)
587            } else {
588                entry.fs_entry.name.clone()
589            };
590            let name_display = if name_with_indicator.len() < name_col_width {
591                format!("{:<width$}", name_with_indicator, width = name_col_width)
592            } else {
593                // Truncate with ellipsis
594                let truncated: String = name_with_indicator
595                    .chars()
596                    .take(name_col_width - 3)
597                    .collect();
598                format!("{}...", truncated)
599            };
600
601            // Color directories differently
602            let name_style = if entry.fs_entry.is_dir() && !is_selected {
603                base_style.fg(theme.help_key_fg)
604            } else {
605                base_style
606            };
607            spans.push(Span::styled(name_display, name_style));
608
609            // Size column
610            let size_display = if entry.fs_entry.is_dir() {
611                format!("{:>width$}", "--", width = size_col_width)
612            } else {
613                let size = entry
614                    .fs_entry
615                    .metadata
616                    .as_ref()
617                    .map(|m| format_size(m.size))
618                    .unwrap_or_else(|| "--".to_string());
619                format!("{:>width$}", size, width = size_col_width)
620            };
621            spans.push(Span::styled(size_display, base_style));
622
623            // Separator
624            spans.push(Span::styled("  ", base_style));
625
626            // Modified column
627            let modified_display = entry
628                .fs_entry
629                .metadata
630                .as_ref()
631                .and_then(|m| m.modified)
632                .map(format_modified)
633                .unwrap_or_else(|| "--".to_string());
634            let modified_formatted =
635                format!("{:>width$}", modified_display, width = date_col_width);
636            spans.push(Span::styled(modified_formatted, base_style));
637
638            lines.push(Line::from(spans));
639        }
640
641        // Fill remaining rows with empty lines
642        while lines.len() < visible_rows {
643            lines.push(Line::from(Span::styled(
644                " ".repeat(width),
645                Style::default().bg(theme.popup_bg),
646            )));
647        }
648
649        let paragraph = Paragraph::new(lines);
650        frame.render_widget(paragraph, area);
651
652        visible_rows
653    }
654}
655
656/// Layout information for mouse hit testing
657#[derive(Debug, Clone)]
658pub struct FileBrowserLayout {
659    /// The overall popup area (including borders)
660    pub popup_area: Rect,
661    /// Navigation shortcuts area
662    pub nav_area: Rect,
663    /// Column headers area
664    pub header_area: Rect,
665    /// File list area
666    pub list_area: Rect,
667    /// Scrollbar area
668    pub scrollbar_area: Rect,
669    /// Scrollbar thumb start position
670    pub thumb_start: usize,
671    /// Scrollbar thumb end position
672    pub thumb_end: usize,
673    /// Number of visible rows in the file list
674    pub visible_rows: usize,
675    /// Width of the content area (for checkbox position calculation)
676    pub content_width: u16,
677}
678
679impl FileBrowserLayout {
680    /// Check if a position is within the overall popup area (including borders)
681    pub fn contains(&self, x: u16, y: u16) -> bool {
682        x >= self.popup_area.x
683            && x < self.popup_area.x + self.popup_area.width
684            && y >= self.popup_area.y
685            && y < self.popup_area.y + self.popup_area.height
686    }
687
688    /// Check if a position is within the file list area
689    pub fn is_in_list(&self, x: u16, y: u16) -> bool {
690        x >= self.list_area.x
691            && x < self.list_area.x + self.list_area.width
692            && y >= self.list_area.y
693            && y < self.list_area.y + self.list_area.height
694    }
695
696    /// Convert a click in the list area to an entry index
697    pub fn click_to_index(&self, y: u16, scroll_offset: usize) -> Option<usize> {
698        if y < self.list_area.y || y >= self.list_area.y + self.list_area.height {
699            return None;
700        }
701        let row = (y - self.list_area.y) as usize;
702        Some(scroll_offset + row)
703    }
704
705    /// Check if a position is in the navigation area
706    pub fn is_in_nav(&self, x: u16, y: u16) -> bool {
707        x >= self.nav_area.x
708            && x < self.nav_area.x + self.nav_area.width
709            && y >= self.nav_area.y
710            && y < self.nav_area.y + self.nav_area.height
711    }
712
713    /// Determine which navigation shortcut was clicked based on x position
714    /// The layout is: " Navigation: " (13 chars) then for each shortcut: " {label} " + " │ " separator
715    /// Navigation shortcuts are on the second row (y == nav_area.y + 1)
716    pub fn nav_shortcut_at(&self, x: u16, y: u16, shortcut_labels: &[&str]) -> Option<usize> {
717        // Navigation shortcuts are on the second row of the nav area
718        if y != self.nav_area.y + 1 {
719            return None;
720        }
721
722        let rel_x = x.saturating_sub(self.nav_area.x) as usize;
723
724        // Skip " Navigation: " prefix
725        let prefix_len = 13;
726        if rel_x < prefix_len {
727            return None;
728        }
729
730        let mut current_x = prefix_len;
731        for (idx, label) in shortcut_labels.iter().enumerate() {
732            // Each shortcut: " {label} " = visual width + 2 spaces
733            let shortcut_width = str_width(label) + 2;
734
735            if rel_x >= current_x && rel_x < current_x + shortcut_width {
736                return Some(idx);
737            }
738            current_x += shortcut_width;
739
740            // Separator: " │ " = 3 chars
741            if idx < shortcut_labels.len() - 1 {
742                current_x += 3;
743            }
744        }
745
746        None
747    }
748
749    /// Check if a position is in the header area (for sorting)
750    pub fn is_in_header(&self, x: u16, y: u16) -> bool {
751        x >= self.header_area.x
752            && x < self.header_area.x + self.header_area.width
753            && y >= self.header_area.y
754            && y < self.header_area.y + self.header_area.height
755    }
756
757    /// Determine which column header was clicked
758    pub fn header_column_at(&self, x: u16) -> Option<SortMode> {
759        let rel_x = x.saturating_sub(self.header_area.x) as usize;
760        let width = self.header_area.width as usize;
761
762        let size_col_width = 10;
763        let date_col_width = 14;
764        let name_col_width = width.saturating_sub(size_col_width + date_col_width + 4);
765
766        if rel_x < name_col_width {
767            Some(SortMode::Name)
768        } else if rel_x < name_col_width + size_col_width {
769            Some(SortMode::Size)
770        } else {
771            Some(SortMode::Modified)
772        }
773    }
774
775    /// Check if a position is in the scrollbar area
776    pub fn is_in_scrollbar(&self, x: u16, y: u16) -> bool {
777        x >= self.scrollbar_area.x
778            && x < self.scrollbar_area.x + self.scrollbar_area.width
779            && y >= self.scrollbar_area.y
780            && y < self.scrollbar_area.y + self.scrollbar_area.height
781    }
782
783    /// Check if a position is in the scrollbar thumb
784    pub fn is_in_thumb(&self, y: u16) -> bool {
785        let rel_y = y.saturating_sub(self.scrollbar_area.y) as usize;
786        rel_y >= self.thumb_start && rel_y < self.thumb_end
787    }
788
789    /// Check if a position is on the "Show Hidden" checkbox
790    /// The checkbox is on the first row of navigation area
791    /// Format: " ☐ Show Hidden (Alt+.) │ ☐ Detect Encoding (Alt+E)"
792    pub fn is_on_show_hidden_checkbox(&self, x: u16, y: u16) -> bool {
793        // Must be on the first row of navigation area (checkbox row)
794        if y != self.nav_area.y {
795            return false;
796        }
797
798        // Must be within the x bounds of the navigation area
799        if x < self.nav_area.x || x >= self.nav_area.x + self.nav_area.width {
800            return false;
801        }
802
803        // Show Hidden checkbox spans the left portion of the row
804        // " ☐ Show Hidden (Alt+.)" is approximately 24 characters
805        let show_hidden_width = 24u16;
806        x < self.nav_area.x + show_hidden_width
807    }
808
809    /// Check if a position is on the "Detect Encoding" checkbox
810    /// The checkbox is on the first row of navigation area, after Show Hidden
811    /// Format: " ☐ Show Hidden (Alt+.) │ ☐ Detect Encoding (Alt+E)"
812    pub fn is_on_detect_encoding_checkbox(&self, x: u16, y: u16) -> bool {
813        // Must be on the first row of navigation area (checkbox row)
814        if y != self.nav_area.y {
815            return false;
816        }
817
818        // Must be within the x bounds of the navigation area
819        if x < self.nav_area.x || x >= self.nav_area.x + self.nav_area.width {
820            return false;
821        }
822
823        // Show Hidden + separator takes about 27 characters
824        // " ☐ Show Hidden (Alt+.)" (24) + " │ " (3) = 27
825        let detect_encoding_start = self.nav_area.x + 27;
826        // Detect Encoding checkbox is about 28 characters
827        // "☐ Detect Encoding (Alt+E)" (25+)
828        let detect_encoding_end = detect_encoding_start + 28;
829
830        x >= detect_encoding_start && x < detect_encoding_end
831    }
832}