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 = fit_header_to_col_width(&name_header, name_col_width);
423        spans.push(Span::styled(name_display, name_style));
424
425        // Size column
426        let size_header = format!(
427            "{:>width$}",
428            format!(
429                "{}{}",
430                t!("file_browser.size"),
431                if state.sort_mode == SortMode::Size {
432                    sort_arrow
433                } else {
434                    " "
435                }
436            ),
437            width = size_col_width
438        );
439        let is_size_hovered = matches!(
440            hover_target,
441            Some(HoverTarget::FileBrowserHeader(SortMode::Size))
442        );
443        let size_style = if state.sort_mode == SortMode::Size {
444            active_header_style
445        } else if is_size_hovered {
446            hover_header_style
447        } else {
448            header_style
449        };
450        spans.push(Span::styled(size_header, size_style));
451
452        // Separator
453        spans.push(Span::styled("  ", header_style));
454
455        // Modified column
456        let modified_header = format!(
457            "{:>width$}",
458            format!(
459                "{}{}",
460                t!("file_browser.modified"),
461                if state.sort_mode == SortMode::Modified {
462                    sort_arrow
463                } else {
464                    " "
465                }
466            ),
467            width = date_col_width
468        );
469        let is_modified_hovered = matches!(
470            hover_target,
471            Some(HoverTarget::FileBrowserHeader(SortMode::Modified))
472        );
473        let modified_style = if state.sort_mode == SortMode::Modified {
474            active_header_style
475        } else if is_modified_hovered {
476            hover_header_style
477        } else {
478            header_style
479        };
480        spans.push(Span::styled(modified_header, modified_style));
481
482        let line = Line::from(spans);
483        let paragraph = Paragraph::new(vec![line]);
484        frame.render_widget(paragraph, area);
485    }
486
487    /// Render the file list with metadata columns
488    ///
489    /// Returns the number of visible rows
490    fn render_file_list(
491        frame: &mut Frame,
492        area: Rect,
493        state: &FileOpenState,
494        theme: &crate::view::theme::Theme,
495        hover_target: &Option<crate::app::HoverTarget>,
496    ) -> usize {
497        use crate::app::HoverTarget;
498
499        let visible_rows = area.height as usize;
500        let width = area.width as usize;
501
502        // Column widths (matching header)
503        let size_col_width = 10;
504        let date_col_width = 14;
505        let name_col_width = width.saturating_sub(size_col_width + date_col_width + 4);
506
507        let is_files_active = state.active_section == FileOpenSection::Files;
508
509        // Loading state
510        if state.loading {
511            let loading_line = Line::from(Span::styled(
512                t!("file_browser.loading").to_string(),
513                Style::default()
514                    .fg(theme.help_separator_fg)
515                    .bg(theme.popup_bg),
516            ));
517            let paragraph = Paragraph::new(vec![loading_line]);
518            frame.render_widget(paragraph, area);
519            return visible_rows;
520        }
521
522        // Error state
523        if let Some(error) = &state.error {
524            let error_line = Line::from(Span::styled(
525                t!("file_browser.error", error = error).to_string(),
526                Style::default()
527                    .fg(theme.diagnostic_error_fg)
528                    .bg(theme.popup_bg),
529            ));
530            let paragraph = Paragraph::new(vec![error_line]);
531            frame.render_widget(paragraph, area);
532            return visible_rows;
533        }
534
535        // Empty state
536        if state.entries.is_empty() {
537            let empty_line = Line::from(Span::styled(
538                format!(" {}", t!("file_browser.empty")),
539                Style::default()
540                    .fg(theme.help_separator_fg)
541                    .bg(theme.popup_bg),
542            ));
543            let paragraph = Paragraph::new(vec![empty_line]);
544            frame.render_widget(paragraph, area);
545            return visible_rows;
546        }
547
548        let mut lines = Vec::new();
549        let visible_entries = state.visible_entries(visible_rows);
550
551        for (view_idx, entry) in visible_entries.iter().enumerate() {
552            let actual_idx = state.scroll_offset + view_idx;
553            let is_selected = is_files_active && state.selected_index == Some(actual_idx);
554            let is_hovered =
555                matches!(hover_target, Some(HoverTarget::FileBrowserEntry(i)) if *i == actual_idx);
556
557            // Base style based on selection, hover, and filter match
558            let base_style = if is_selected {
559                Style::default()
560                    .fg(theme.popup_text_fg)
561                    .bg(theme.suggestion_selected_bg)
562            } else if is_hovered && entry.matches_filter {
563                Style::default()
564                    .fg(theme.menu_hover_fg)
565                    .bg(theme.menu_hover_bg)
566            } else if !entry.matches_filter {
567                // Non-matching items are dimmed using the separator color
568                Style::default()
569                    .fg(theme.help_separator_fg)
570                    .bg(theme.popup_bg)
571                    .add_modifier(Modifier::DIM)
572            } else {
573                Style::default().fg(theme.popup_text_fg).bg(theme.popup_bg)
574            };
575
576            let mut spans = Vec::new();
577
578            // Name column with trailing type indicator (dirs get /, symlinks get @)
579            let name_with_indicator = if entry.fs_entry.is_dir() {
580                format!("{}/", entry.fs_entry.name)
581            } else if entry.fs_entry.is_symlink() {
582                format!("{}@", entry.fs_entry.name)
583            } else {
584                entry.fs_entry.name.clone()
585            };
586            let name_display = if name_with_indicator.len() < name_col_width {
587                format!("{:<width$}", name_with_indicator, width = name_col_width)
588            } else {
589                // Truncate with ellipsis
590                let truncated: String = name_with_indicator
591                    .chars()
592                    .take(name_col_width - 3)
593                    .collect();
594                format!("{}...", truncated)
595            };
596
597            // Color directories differently
598            let name_style = if entry.fs_entry.is_dir() && !is_selected {
599                base_style.fg(theme.help_key_fg)
600            } else {
601                base_style
602            };
603            spans.push(Span::styled(name_display, name_style));
604
605            // Size column
606            let size_display = if entry.fs_entry.is_dir() {
607                format!("{:>width$}", "--", width = size_col_width)
608            } else {
609                let size = entry
610                    .fs_entry
611                    .metadata
612                    .as_ref()
613                    .map(|m| format_size(m.size))
614                    .unwrap_or_else(|| "--".to_string());
615                format!("{:>width$}", size, width = size_col_width)
616            };
617            spans.push(Span::styled(size_display, base_style));
618
619            // Separator
620            spans.push(Span::styled("  ", base_style));
621
622            // Modified column
623            let modified_display = entry
624                .fs_entry
625                .metadata
626                .as_ref()
627                .and_then(|m| m.modified)
628                .map(format_modified)
629                .unwrap_or_else(|| "--".to_string());
630            let modified_formatted =
631                format!("{:>width$}", modified_display, width = date_col_width);
632            spans.push(Span::styled(modified_formatted, base_style));
633
634            lines.push(Line::from(spans));
635        }
636
637        // Fill remaining rows with empty lines
638        while lines.len() < visible_rows {
639            lines.push(Line::from(Span::styled(
640                " ".repeat(width),
641                Style::default().bg(theme.popup_bg),
642            )));
643        }
644
645        let paragraph = Paragraph::new(lines);
646        frame.render_widget(paragraph, area);
647
648        visible_rows
649    }
650}
651
652/// Pad or truncate a header string so it occupies exactly `col_width`
653/// character positions. Counts characters (not bytes) so headers
654/// containing the sort arrow `▲`/`▼` (3 UTF-8 bytes each) or localized
655/// labels from `t!()` don't byte-slice through a multi-byte sequence and
656/// panic — same class as #1718.
657fn fit_header_to_col_width(header: &str, col_width: usize) -> String {
658    let chars = header.chars().count();
659    if chars < col_width {
660        format!("{:<width$}", header, width = col_width)
661    } else {
662        header.chars().take(col_width).collect()
663    }
664}
665
666/// Layout information for mouse hit testing
667#[derive(Debug, Clone)]
668pub struct FileBrowserLayout {
669    /// The overall popup area (including borders)
670    pub popup_area: Rect,
671    /// Navigation shortcuts area
672    pub nav_area: Rect,
673    /// Column headers area
674    pub header_area: Rect,
675    /// File list area
676    pub list_area: Rect,
677    /// Scrollbar area
678    pub scrollbar_area: Rect,
679    /// Scrollbar thumb start position
680    pub thumb_start: usize,
681    /// Scrollbar thumb end position
682    pub thumb_end: usize,
683    /// Number of visible rows in the file list
684    pub visible_rows: usize,
685    /// Width of the content area (for checkbox position calculation)
686    pub content_width: u16,
687}
688
689impl FileBrowserLayout {
690    /// Check if a position is within the overall popup area (including borders)
691    pub fn contains(&self, x: u16, y: u16) -> bool {
692        x >= self.popup_area.x
693            && x < self.popup_area.x + self.popup_area.width
694            && y >= self.popup_area.y
695            && y < self.popup_area.y + self.popup_area.height
696    }
697
698    /// Check if a position is within the file list area
699    pub fn is_in_list(&self, x: u16, y: u16) -> bool {
700        x >= self.list_area.x
701            && x < self.list_area.x + self.list_area.width
702            && y >= self.list_area.y
703            && y < self.list_area.y + self.list_area.height
704    }
705
706    /// Convert a click in the list area to an entry index
707    pub fn click_to_index(&self, y: u16, scroll_offset: usize) -> Option<usize> {
708        if y < self.list_area.y || y >= self.list_area.y + self.list_area.height {
709            return None;
710        }
711        let row = (y - self.list_area.y) as usize;
712        Some(scroll_offset + row)
713    }
714
715    /// Check if a position is in the navigation area
716    pub fn is_in_nav(&self, x: u16, y: u16) -> bool {
717        x >= self.nav_area.x
718            && x < self.nav_area.x + self.nav_area.width
719            && y >= self.nav_area.y
720            && y < self.nav_area.y + self.nav_area.height
721    }
722
723    /// Determine which navigation shortcut was clicked based on x position
724    /// The layout is: " Navigation: " (13 chars) then for each shortcut: " {label} " + " │ " separator
725    /// Navigation shortcuts are on the second row (y == nav_area.y + 1)
726    pub fn nav_shortcut_at(&self, x: u16, y: u16, shortcut_labels: &[&str]) -> Option<usize> {
727        // Navigation shortcuts are on the second row of the nav area
728        if y != self.nav_area.y + 1 {
729            return None;
730        }
731
732        let rel_x = x.saturating_sub(self.nav_area.x) as usize;
733
734        // Skip " Navigation: " prefix
735        let prefix_len = 13;
736        if rel_x < prefix_len {
737            return None;
738        }
739
740        let mut current_x = prefix_len;
741        for (idx, label) in shortcut_labels.iter().enumerate() {
742            // Each shortcut: " {label} " = visual width + 2 spaces
743            let shortcut_width = str_width(label) + 2;
744
745            if rel_x >= current_x && rel_x < current_x + shortcut_width {
746                return Some(idx);
747            }
748            current_x += shortcut_width;
749
750            // Separator: " │ " = 3 chars
751            if idx < shortcut_labels.len() - 1 {
752                current_x += 3;
753            }
754        }
755
756        None
757    }
758
759    /// Check if a position is in the header area (for sorting)
760    pub fn is_in_header(&self, x: u16, y: u16) -> bool {
761        x >= self.header_area.x
762            && x < self.header_area.x + self.header_area.width
763            && y >= self.header_area.y
764            && y < self.header_area.y + self.header_area.height
765    }
766
767    /// Determine which column header was clicked
768    pub fn header_column_at(&self, x: u16) -> Option<SortMode> {
769        let rel_x = x.saturating_sub(self.header_area.x) as usize;
770        let width = self.header_area.width as usize;
771
772        let size_col_width = 10;
773        let date_col_width = 14;
774        let name_col_width = width.saturating_sub(size_col_width + date_col_width + 4);
775
776        if rel_x < name_col_width {
777            Some(SortMode::Name)
778        } else if rel_x < name_col_width + size_col_width {
779            Some(SortMode::Size)
780        } else {
781            Some(SortMode::Modified)
782        }
783    }
784
785    /// Check if a position is in the scrollbar area
786    pub fn is_in_scrollbar(&self, x: u16, y: u16) -> bool {
787        x >= self.scrollbar_area.x
788            && x < self.scrollbar_area.x + self.scrollbar_area.width
789            && y >= self.scrollbar_area.y
790            && y < self.scrollbar_area.y + self.scrollbar_area.height
791    }
792
793    /// Check if a position is in the scrollbar thumb
794    pub fn is_in_thumb(&self, y: u16) -> bool {
795        let rel_y = y.saturating_sub(self.scrollbar_area.y) as usize;
796        rel_y >= self.thumb_start && rel_y < self.thumb_end
797    }
798
799    /// Check if a position is on the "Show Hidden" checkbox
800    /// The checkbox is on the first row of navigation area
801    /// Format: " ☐ Show Hidden (Alt+.) │ ☐ Detect Encoding (Alt+E)"
802    pub fn is_on_show_hidden_checkbox(&self, x: u16, y: u16) -> bool {
803        // Must be on the first row of navigation area (checkbox row)
804        if y != self.nav_area.y {
805            return false;
806        }
807
808        // Must be within the x bounds of the navigation area
809        if x < self.nav_area.x || x >= self.nav_area.x + self.nav_area.width {
810            return false;
811        }
812
813        // Show Hidden checkbox spans the left portion of the row
814        // " ☐ Show Hidden (Alt+.)" is approximately 24 characters
815        let show_hidden_width = 24u16;
816        x < self.nav_area.x + show_hidden_width
817    }
818
819    /// Check if a position is on the "Detect Encoding" checkbox
820    /// The checkbox is on the first row of navigation area, after Show Hidden
821    /// Format: " ☐ Show Hidden (Alt+.) │ ☐ Detect Encoding (Alt+E)"
822    pub fn is_on_detect_encoding_checkbox(&self, x: u16, y: u16) -> bool {
823        // Must be on the first row of navigation area (checkbox row)
824        if y != self.nav_area.y {
825            return false;
826        }
827
828        // Must be within the x bounds of the navigation area
829        if x < self.nav_area.x || x >= self.nav_area.x + self.nav_area.width {
830            return false;
831        }
832
833        // Show Hidden + separator takes about 27 characters
834        // " ☐ Show Hidden (Alt+.)" (24) + " │ " (3) = 27
835        let detect_encoding_start = self.nav_area.x + 27;
836        // Detect Encoding checkbox is about 28 characters
837        // "☐ Detect Encoding (Alt+E)" (25+)
838        let detect_encoding_end = detect_encoding_start + 28;
839
840        x >= detect_encoding_start && x < detect_encoding_end
841    }
842}
843
844#[cfg(test)]
845mod tests {
846    use super::fit_header_to_col_width;
847
848    #[test]
849    fn fit_header_pads_when_short() {
850        assert_eq!(fit_header_to_col_width("Name", 8), "Name    ");
851    }
852
853    #[test]
854    fn fit_header_truncates_ascii() {
855        assert_eq!(fit_header_to_col_width("Filename▲", 4), "File");
856    }
857
858    #[test]
859    fn fit_header_truncates_with_sort_arrow_does_not_panic() {
860        // Regression: header ` Name ▲` is 9 bytes (`▲` = 3 bytes) but
861        // 7 characters. Under the old byte-based code, col_width=7 would
862        // byte-slice at index 7 — inside the 3-byte UTF-8 sequence for
863        // `▲` — and panic the editor (same class as #1718). Now the
864        // header is truncated by character count.
865        let out = fit_header_to_col_width(" Name ▲", 7);
866        assert_eq!(out, " Name ▲");
867        assert_eq!(out.chars().count(), 7);
868    }
869
870    #[test]
871    fn fit_header_truncates_localized_does_not_panic() {
872        // Localized header (e.g. Japanese) where every label char is
873        // 3 UTF-8 bytes. Old byte-based truncation at col_width=4 would
874        // panic mid-character; character-based truncation keeps 4 chars.
875        let out = fit_header_to_col_width(" 名前 ▲", 4);
876        assert!(out.is_char_boundary(out.len()));
877        assert_eq!(out.chars().count(), 4);
878    }
879}