ratatui_toolkit/widgets/code_diff/widget/methods/
select_prev_file.rs

1//! Method to select the previous file in the sidebar.
2
3use crate::widgets::code_diff::code_diff::CodeDiff;
4
5impl CodeDiff {
6    /// Selects the previous file in the sidebar file tree.
7    ///
8    /// This also updates the current diff hunks to show the selected file.
9    /// If already at the first file, stays at the first file.
10    ///
11    /// # Example
12    ///
13    /// ```rust
14    /// use ratatui_toolkit::code_diff::{CodeDiff, DiffConfig};
15    /// use ratatui_toolkit::widgets::code_diff::diff_file_tree::FileStatus;
16    ///
17    /// let mut diff = CodeDiff::new()
18    ///     .with_config(DiffConfig::new().sidebar_enabled(true))
19    ///     .with_file("file1.rs", FileStatus::Modified, "")
20    ///     .with_file("file2.rs", FileStatus::Added, "");
21    ///
22    /// diff.select_next_file();
23    /// diff.select_prev_file(); // Back to first file
24    /// ```
25    pub fn select_prev_file(&mut self) {
26        self.file_tree.select_prev();
27        self.sync_diff_from_tree();
28    }
29
30    /// Syncs the current diff hunks from the selected file in the tree.
31    fn sync_diff_from_tree(&mut self) {
32        if let Some(path) = self.file_tree.selected_path() {
33            if let Some(hunks) = self.file_diffs.get(&path) {
34                self.file_path = Some(path);
35                self.hunks = hunks.clone();
36                self.scroll_offset = 0; // Reset scroll when changing files
37            }
38        }
39    }
40}