dotstate 0.3.4

A modern, secure, and user-friendly dotfile manager built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! File Browser component for selecting files and directories.
//!
//! This component provides a modal file browser with:
//! - Path input field for direct navigation
//! - File/directory list with navigation
//! - Preview pane for selected files
//! - Keyboard navigation between panes

use crate::components::file_preview::FilePreview;
use crate::components::popup::Popup;
use crate::config::Config;
use crate::keymap::Action;
use crate::styles::{theme as ui_theme, LIST_HIGHLIGHT_SYMBOL};
use crate::utils::list_navigation::ListStateExt;
use crate::utils::mouse::MouseRegions;
use crate::utils::style::{focused_border_style, unfocused_border_style};
use crate::utils::text_input::TextInput;
use crate::widgets::text_input::{TextInputWidget, TextInputWidgetExt};
use anyhow::Result;
use crossterm::event::{Event, KeyCode, KeyEventKind, MouseButton, MouseEventKind};
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::widgets::{
    Block, Borders, List, ListItem, ListState, Paragraph, Scrollbar, ScrollbarOrientation,
    ScrollbarState, StatefulWidget,
};
use ratatui::Frame;
use std::path::{Path, PathBuf};
use syntect::highlighting::Theme;
use syntect::parsing::SyntaxSet;

/// Focus area within the file browser
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FileBrowserFocus {
    /// Path input field is focused
    PathInput,
    /// File/directory list is focused
    #[default]
    List,
    /// Preview pane is focused
    Preview,
}

/// Result of file browser interaction
#[derive(Debug, Clone)]
pub enum FileBrowserResult {
    /// No action taken
    None,
    /// User cancelled/closed the browser
    Cancelled,
    /// User selected a file or folder to add
    Selected {
        full_path: PathBuf,
        relative_path: String,
    },
    /// Directory changed, entries need refresh
    RefreshNeeded,
}

/// File browser component state
#[derive(Debug)]
pub struct FileBrowser {
    /// Whether the browser is currently open/active
    pub is_active: bool,
    /// Current directory path
    pub current_path: PathBuf,
    /// Entries in the current directory (files and folders)
    pub entries: Vec<PathBuf>,
    /// List selection state
    pub list_state: ListState,
    /// Scrollbar state for the list
    pub scrollbar_state: ScrollbarState,
    /// Path input field
    pub path_input: TextInput,
    /// Preview pane scroll offset
    pub preview_scroll: usize,
    /// Which pane currently has focus
    pub focus: FileBrowserFocus,
    /// Mouse regions for file list items (value = entry index)
    mouse_regions: MouseRegions<usize>,
    /// Stored list pane area for scroll hit-testing
    list_pane_area: Option<Rect>,
    /// Stored preview pane area for scroll hit-testing
    preview_pane_area: Option<Rect>,
    /// Stored path input area for click-to-focus
    path_input_area: Option<Rect>,
}

impl Default for FileBrowser {
    fn default() -> Self {
        Self::new()
    }
}

impl FileBrowser {
    /// Create a new file browser
    #[must_use]
    pub fn new() -> Self {
        Self {
            is_active: false,
            current_path: dirs::home_dir().unwrap_or_else(|| PathBuf::from("/")),
            entries: Vec::new(),
            list_state: ListState::default(),
            scrollbar_state: ScrollbarState::new(0),
            path_input: TextInput::new(),
            preview_scroll: 0,
            focus: FileBrowserFocus::List,
            mouse_regions: MouseRegions::new(),
            list_pane_area: None,
            preview_pane_area: None,
            path_input_area: None,
        }
    }

    /// Open the file browser at the specified path
    pub fn open(&mut self, path: PathBuf) {
        self.is_active = true;
        self.current_path = path.clone();
        self.path_input.set_text(path.to_string_lossy().to_string());
        self.list_state.select(Some(0));
        self.preview_scroll = 0;
        self.focus = FileBrowserFocus::List;
        self.refresh_entries();
    }

    /// Close the file browser
    pub fn close(&mut self) {
        self.is_active = false;
        self.path_input.clear();
        self.entries.clear();
    }

    /// Check if the browser is currently open
    #[must_use]
    pub fn is_open(&self) -> bool {
        self.is_active
    }

    /// Refresh directory entries for the current path
    pub fn refresh_entries(&mut self) {
        self.entries.clear();

        // Add parent directory entry
        if self.current_path.parent().is_some() {
            self.entries.push(PathBuf::from(".."));
        }

        // Add current directory entry (for selecting the folder itself)
        self.entries.push(PathBuf::from("."));

        // List directory contents
        if let Ok(read_dir) = std::fs::read_dir(&self.current_path) {
            let mut dirs: Vec<PathBuf> = Vec::new();
            let mut files: Vec<PathBuf> = Vec::new();

            for entry in read_dir.flatten() {
                let path = entry.path();

                // Include all files (including dotfiles, since this is a dotfile manager)
                if path.is_dir() {
                    dirs.push(path);
                } else {
                    files.push(path);
                }
            }

            // Sort directories and files
            dirs.sort();
            files.sort();

            // Add directories first, then files
            for dir in dirs {
                self.entries.push(dir);
            }
            for file in files {
                self.entries.push(file);
            }
        }

        // Update scrollbar
        self.scrollbar_state = self.scrollbar_state.content_length(self.entries.len());

        // Ensure selection is valid
        if self.list_state.selected().is_none() && !self.entries.is_empty() {
            self.list_state.select(Some(0));
        }
    }

    /// Check if input field is focused (for blocking global keybindings)
    #[must_use]
    pub fn is_input_focused(&self) -> bool {
        self.is_active && self.focus == FileBrowserFocus::PathInput
    }

    /// Handle events for the file browser
    pub fn handle_event(&mut self, event: Event, config: &Config) -> Result<FileBrowserResult> {
        if !self.is_active {
            return Ok(FileBrowserResult::None);
        }

        match event {
            Event::Key(key) => {
                if key.kind != KeyEventKind::Press {
                    return Ok(FileBrowserResult::None);
                }

                match self.focus {
                    FileBrowserFocus::PathInput => {
                        return self.handle_path_input(key.code, config);
                    }
                    FileBrowserFocus::List => {
                        return self.handle_list_navigation(key.code, config);
                    }
                    FileBrowserFocus::Preview => {
                        return self.handle_preview_navigation(key.code, config);
                    }
                }
            }
            Event::Mouse(mouse) => {
                return self.handle_mouse_event(mouse, config);
            }
            _ => {}
        }

        Ok(FileBrowserResult::None)
    }

    /// Handle path input field events
    fn handle_path_input(
        &mut self,
        key_code: KeyCode,
        _config: &Config,
    ) -> Result<FileBrowserResult> {
        match key_code {
            KeyCode::Char(c) => {
                self.path_input.insert_char(c);
            }
            KeyCode::Left | KeyCode::Right | KeyCode::Home | KeyCode::End => {
                self.path_input.handle_key(key_code);
            }
            KeyCode::Backspace => {
                self.path_input.backspace();
            }
            KeyCode::Delete => {
                self.path_input.delete();
            }
            KeyCode::Enter => {
                // Load path from input
                let path_str = self.path_input.text_trimmed();
                if !path_str.is_empty() {
                    let full_path = crate::utils::expand_path(path_str);

                    if full_path.exists() {
                        if full_path.is_dir() {
                            self.current_path = full_path.clone();
                            self.path_input
                                .set_text(self.current_path.to_string_lossy().to_string());
                            self.list_state.select(Some(0));
                            self.focus = FileBrowserFocus::List;
                            self.refresh_entries();
                            return Ok(FileBrowserResult::RefreshNeeded);
                        } else {
                            // It's a file - select it directly
                            let home_dir = crate::utils::get_home_dir();
                            let relative_path = full_path.strip_prefix(&home_dir).map_or_else(
                                |_| full_path.to_string_lossy().to_string(),
                                |p| p.to_string_lossy().to_string(),
                            );

                            self.close();
                            return Ok(FileBrowserResult::Selected {
                                full_path,
                                relative_path,
                            });
                        }
                    }
                }
            }
            KeyCode::Tab => {
                self.focus = FileBrowserFocus::List;
            }
            KeyCode::Esc => {
                self.close();
                return Ok(FileBrowserResult::Cancelled);
            }
            _ => {}
        }

        Ok(FileBrowserResult::None)
    }

    /// Handle list navigation events
    fn handle_list_navigation(
        &mut self,
        key_code: KeyCode,
        config: &Config,
    ) -> Result<FileBrowserResult> {
        let action = config
            .keymap
            .get_action(key_code, crossterm::event::KeyModifiers::NONE);

        if let Some(action) = action {
            match action {
                Action::MoveUp => {
                    self.list_state.select_previous();
                    self.preview_scroll = 0; // Reset preview scroll on selection change
                }
                Action::MoveDown => {
                    self.list_state.select_next();
                    self.preview_scroll = 0;
                }
                Action::Confirm => {
                    return self.handle_selection(config);
                }
                Action::NextTab => {
                    self.focus = FileBrowserFocus::Preview;
                }
                Action::PageUp => {
                    self.list_state.page_up(10, self.entries.len());
                }
                Action::PageDown => {
                    self.list_state.page_down(10, self.entries.len());
                }
                Action::GoToTop => {
                    self.list_state.select_first();
                }
                Action::GoToEnd => {
                    self.list_state.select_last();
                }
                Action::Cancel | Action::Quit => {
                    self.close();
                    return Ok(FileBrowserResult::Cancelled);
                }
                _ => {}
            }
        }

        // Update scrollbar position
        if let Some(selected) = self.list_state.selected() {
            self.scrollbar_state = self.scrollbar_state.position(selected);
        }

        Ok(FileBrowserResult::None)
    }

    /// Handle selection/confirmation in the list
    fn handle_selection(&mut self, config: &Config) -> Result<FileBrowserResult> {
        if let Some(idx) = self.list_state.selected() {
            if idx < self.entries.len() {
                let entry = self.entries[idx].clone();

                // Handle special entries
                if entry == Path::new("..") {
                    // Go to parent directory
                    if let Some(parent) = self.current_path.parent() {
                        self.current_path = parent.to_path_buf();
                        self.path_input
                            .set_text(self.current_path.to_string_lossy().to_string());
                        self.list_state.select(Some(0));
                        self.refresh_entries();
                        return Ok(FileBrowserResult::RefreshNeeded);
                    }
                } else if entry == Path::new(".") {
                    // Add current folder
                    let current_folder = self.current_path.clone();
                    let home_dir = crate::utils::get_home_dir();
                    let relative_path = current_folder.strip_prefix(&home_dir).map_or_else(
                        |_| current_folder.to_string_lossy().to_string(),
                        |p| p.to_string_lossy().to_string(),
                    );

                    // Validate
                    let repo_path = &config.repo_path;
                    let (is_safe, _reason) =
                        crate::utils::is_safe_to_add(&current_folder, repo_path);
                    if !is_safe {
                        // Return error via status message (caller handles this)
                        return Ok(FileBrowserResult::None); // TODO: Add error result variant
                    }

                    // Check if git repo
                    if crate::utils::is_git_repo(&current_folder) {
                        return Ok(FileBrowserResult::None); // TODO: Add error result variant
                    }

                    self.close();
                    return Ok(FileBrowserResult::Selected {
                        full_path: current_folder,
                        relative_path,
                    });
                } else {
                    // Regular file or directory
                    let full_path = if entry.is_absolute() {
                        entry.clone()
                    } else {
                        self.current_path.join(&entry)
                    };

                    if full_path.is_dir() {
                        // Navigate into directory
                        self.current_path = full_path.clone();
                        self.path_input
                            .set_text(full_path.to_string_lossy().to_string());
                        self.list_state.select(Some(0));
                        self.refresh_entries();
                        return Ok(FileBrowserResult::RefreshNeeded);
                    } else if full_path.is_file() {
                        // Select file
                        let home_dir = crate::utils::get_home_dir();
                        let relative_path = full_path.strip_prefix(&home_dir).map_or_else(
                            |_| full_path.to_string_lossy().to_string(),
                            |p| p.to_string_lossy().to_string(),
                        );

                        self.close();
                        return Ok(FileBrowserResult::Selected {
                            full_path,
                            relative_path,
                        });
                    }
                }
            }
        }

        Ok(FileBrowserResult::None)
    }

    /// Handle preview pane navigation
    fn handle_preview_navigation(
        &mut self,
        key_code: KeyCode,
        config: &Config,
    ) -> Result<FileBrowserResult> {
        let action = config
            .keymap
            .get_action(key_code, crossterm::event::KeyModifiers::NONE);

        if let Some(action) = action {
            match action {
                Action::MoveUp | Action::ScrollUp => {
                    self.preview_scroll = self.preview_scroll.saturating_sub(1);
                }
                Action::MoveDown | Action::ScrollDown => {
                    self.preview_scroll = self.preview_scroll.saturating_add(1);
                }
                Action::PageUp => {
                    self.preview_scroll = self.preview_scroll.saturating_sub(20);
                }
                Action::PageDown => {
                    self.preview_scroll = self.preview_scroll.saturating_add(20);
                }
                Action::GoToTop => {
                    self.preview_scroll = 0;
                }
                Action::GoToEnd => {
                    self.preview_scroll = 10000; // Will be clamped during render
                }
                Action::NextTab => {
                    self.focus = FileBrowserFocus::PathInput;
                }
                Action::Cancel | Action::Quit => {
                    self.close();
                    return Ok(FileBrowserResult::Cancelled);
                }
                _ => {}
            }
        }

        Ok(FileBrowserResult::None)
    }

    /// Handle mouse events for the file browser
    fn handle_mouse_event(
        &mut self,
        mouse: crossterm::event::MouseEvent,
        _config: &Config,
    ) -> Result<FileBrowserResult> {
        let pos = ratatui::layout::Position::new(mouse.column, mouse.row);

        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                // Click on file list item
                if let Some(&idx) = self.mouse_regions.hit_test(mouse.column, mouse.row) {
                    self.list_state.select(Some(idx));
                    self.preview_scroll = 0;
                    self.focus = FileBrowserFocus::List;
                    // Update scrollbar
                    self.scrollbar_state = self.scrollbar_state.position(idx);
                    return Ok(FileBrowserResult::None);
                }

                // Click on path input
                if let Some(area) = self.path_input_area {
                    if area.contains(pos) {
                        self.focus = FileBrowserFocus::PathInput;
                        return Ok(FileBrowserResult::None);
                    }
                }

                // Click on preview
                if let Some(area) = self.preview_pane_area {
                    if area.contains(pos) {
                        self.focus = FileBrowserFocus::Preview;
                        return Ok(FileBrowserResult::None);
                    }
                }

                // Click on list pane (but not item)
                if let Some(area) = self.list_pane_area {
                    if area.contains(pos) {
                        self.focus = FileBrowserFocus::List;
                        return Ok(FileBrowserResult::None);
                    }
                }
            }
            MouseEventKind::ScrollDown => {
                if let Some(area) = self.list_pane_area {
                    if area.contains(pos) {
                        for _ in 0..3 {
                            self.list_state.select_next();
                        }
                        self.preview_scroll = 0;
                        if let Some(selected) = self.list_state.selected() {
                            self.scrollbar_state = self.scrollbar_state.position(selected);
                        }
                        return Ok(FileBrowserResult::None);
                    }
                }
                if let Some(area) = self.preview_pane_area {
                    if area.contains(pos) {
                        self.preview_scroll = self.preview_scroll.saturating_add(3);
                        return Ok(FileBrowserResult::None);
                    }
                }
            }
            MouseEventKind::ScrollUp => {
                if let Some(area) = self.list_pane_area {
                    if area.contains(pos) {
                        for _ in 0..3 {
                            self.list_state.select_previous();
                        }
                        self.preview_scroll = 0;
                        if let Some(selected) = self.list_state.selected() {
                            self.scrollbar_state = self.scrollbar_state.position(selected);
                        }
                        return Ok(FileBrowserResult::None);
                    }
                }
                if let Some(area) = self.preview_pane_area {
                    if area.contains(pos) {
                        self.preview_scroll = self.preview_scroll.saturating_sub(3);
                        return Ok(FileBrowserResult::None);
                    }
                }
            }
            _ => {}
        }

        Ok(FileBrowserResult::None)
    }

    /// Render the file browser
    #[allow(clippy::too_many_arguments)]
    pub fn render(
        &mut self,
        frame: &mut Frame,
        area: Rect,
        config: &Config,
        syntax_set: &SyntaxSet,
        theme: &Theme,
    ) -> Result<()> {
        if !self.is_active {
            return Ok(());
        }

        let t = ui_theme();

        // Use Popup component for consistent styling
        let k = |a| config.keymap.get_key_display_for_action(a);
        let footer_text = format!(
            "{}: Switch Focus | {}: Navigate | {}: Select | {}: Cancel",
            k(Action::NextTab),
            config.keymap.navigation_display(),
            k(Action::Confirm),
            k(Action::Cancel)
        );

        // 1(path) + 3(input) + min 8(list+preview) + title/footer/borders ~5.
        let Some(popup_result) = Popup::new()
            .width(80)
            .height(70)
            .min_height(17)
            .min_width(60)
            .title("Select File or Directory")
            .footer(&footer_text)
            .render(frame, area)
        else {
            return Ok(());
        };

        let content_area = popup_result.content_area;

        // Split content area into path, list+preview
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1), // Current path display
                Constraint::Length(3), // Path input
                Constraint::Min(0),    // List and preview
            ])
            .split(content_area);

        // Current path display
        let path_display = Paragraph::new(self.current_path.to_string_lossy().to_string()).block(
            Block::default()
                .title(" Current Directory ")
                .title_alignment(Alignment::Center)
                .title_style(t.title_style())
                .style(t.background_style()),
        );
        frame.render_widget(path_display, chunks[0]);

        // Path input field
        self.path_input_area = Some(chunks[1]);
        let widget = TextInputWidget::new(&self.path_input)
            .title("Path Input")
            .focused(self.focus == FileBrowserFocus::PathInput);
        frame.render_text_input_widget(widget, chunks[1]);

        // Split list and preview horizontally
        let list_preview_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(chunks[2]);

        // Render file list
        self.render_list(frame, list_preview_chunks[0], config);

        // Store preview area
        self.preview_pane_area = Some(list_preview_chunks[1]);

        // Render preview
        self.render_preview(frame, list_preview_chunks[1], syntax_set, theme, config)?;

        Ok(())
    }

    /// Render the file/directory list
    fn render_list(&mut self, frame: &mut Frame, area: Rect, config: &Config) {
        let t = ui_theme();
        let icons = crate::icons::Icons::from_config(config);

        let items: Vec<ListItem> = self
            .entries
            .iter()
            .map(|path| {
                let is_dir = if path == Path::new("..") || path == Path::new(".") {
                    true
                } else {
                    path.is_dir()
                };

                let name = if path == Path::new("..") {
                    ".. (parent)".to_string()
                } else if path == Path::new(".") {
                    ". (add this folder)".to_string()
                } else {
                    path.file_name().and_then(|n| n.to_str()).map_or_else(
                        || path.to_string_lossy().to_string(),
                        std::string::ToString::to_string,
                    )
                };

                let prefix = if is_dir {
                    format!("{} ", icons.folder())
                } else {
                    format!("{} ", icons.file())
                };

                ListItem::new(format!("{prefix}{name}")).style(t.text_style())
            })
            .collect();

        let is_focused = self.focus == FileBrowserFocus::List;
        let border_style = if is_focused {
            focused_border_style().bg(t.background)
        } else {
            unfocused_border_style().bg(t.background)
        };

        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" Files ")
                    .border_type(t.border_type(is_focused))
                    .title_alignment(Alignment::Center)
                    .border_style(border_style)
                    .style(t.background_style()),
            )
            .highlight_style(t.highlight_style())
            .highlight_symbol(LIST_HIGHLIGHT_SYMBOL);

        StatefulWidget::render(list, area, frame.buffer_mut(), &mut self.list_state);

        // Populate mouse regions
        self.list_pane_area = Some(area);
        self.mouse_regions.clear();
        let inner = Block::default().borders(Borders::ALL).inner(area);
        let scroll_offset = self.list_state.offset();
        for i in 0..self.entries.len() {
            if i < scroll_offset {
                continue;
            }
            let visible_row = (i - scroll_offset) as u16;
            if visible_row >= inner.height {
                break;
            }
            let row_area = Rect::new(inner.x, inner.y + visible_row, inner.width, 1);
            self.mouse_regions.add(row_area, i);
        }

        // Render scrollbar
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some(""))
                .end_symbol(Some("")),
            area,
            &mut self.scrollbar_state,
        );
    }

    /// Render the preview pane
    fn render_preview(
        &mut self,
        frame: &mut Frame,
        area: Rect,
        syntax_set: &SyntaxSet,
        theme: &Theme,
        config: &crate::config::Config,
    ) -> Result<()> {
        let t = ui_theme();

        if let Some(selected_index) = self.list_state.selected() {
            if selected_index < self.entries.len() {
                let selected = &self.entries[selected_index];
                let full_path = if selected == Path::new("..") {
                    self.current_path
                        .parent()
                        .map_or_else(|| PathBuf::from("/"), std::path::Path::to_path_buf)
                } else if selected == Path::new(".") {
                    self.current_path.clone()
                } else if selected.is_absolute() {
                    selected.clone()
                } else {
                    self.current_path.join(selected)
                };

                let is_focused = self.focus == FileBrowserFocus::Preview;

                FilePreview::render(
                    frame,
                    area,
                    &full_path,
                    &mut self.preview_scroll,
                    is_focused,
                    Some("Preview"),
                    None,
                    syntax_set,
                    theme,
                    config,
                )?;

                return Ok(());
            }
        }

        // No selection - show empty preview
        let empty_preview = Paragraph::new("No selection")
            .style(t.muted_style())
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(t.border_type(false))
                    .title(" Preview ")
                    .title_alignment(Alignment::Center)
                    .style(t.background_style()),
            );
        frame.render_widget(empty_preview, area);

        Ok(())
    }
}