diff --git a/CLAUDE.md b/CLAUDE.md index d180043..b841be4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,3 +58,4 @@ gitrat is a terminal UI (TUI) for staging, viewing diffs, and committing — a l - `p` pushes on a background thread; sets upstream (`branch..pushRemote`, `remote.pushDefault`, `origin`, or the only remote) when missing; ssh runs with `BatchMode=yes` unless the user configured an ssh command. - Diff scroll: `Ctrl-D/U` half page, `Ctrl-F/B` page, `J/K` line, `g/G`, `h/l` horizontal, mouse wheel. Letter bindings exist because Terminal.app swallows PageUp/PageDown/Home/End. - `FileStatus::StagedModified` shows staged and unstaged diffs as separate sections (`DiffSection` titles). +- The file list is split into Staged/Unstaged groups (`FileEntry::group`; `±` files stay in Staged). `App::files` is sorted by group; `list_state` indexes `App::list_rows()` (headers included), so use `App::row_of` to map a file index to a list row. Empty groups have no header. diff --git a/assets/screenshot.png b/assets/screenshot.png index 995fbbc..7eb8887 100644 Binary files a/assets/screenshot.png and b/assets/screenshot.png differ diff --git a/src/app.rs b/src/app.rs index 2957a51..9676578 100644 --- a/src/app.rs +++ b/src/app.rs @@ -15,6 +15,7 @@ use crate::git::GitResult; use crate::git::Repo; use crate::theme::Theme; use crate::types::FileEntry; +use crate::types::FileGroup; /// How often the file list is re-read from git while idle. const AUTO_REFRESH: Duration = Duration::from_secs(3); @@ -54,6 +55,15 @@ pub enum MessageKind { Error, } +/// One row of the file list: a group header or a file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ListRow { + /// Section header with the number of files in the group. + Header(FileGroup, usize), + /// Index into [`App::files`]. + File(usize), +} + /// A transient message shown in the commit bar title. #[derive(Debug, Clone)] pub struct Message { @@ -75,11 +85,12 @@ pub struct App { pub theme: Theme, /// Branch description from `git status --branch`. pub branch: String, - /// List of changed/untracked files from `git status`. + /// List of changed/untracked files from `git status`, staged group first. pub files: Vec, /// Index into `files` of the currently highlighted entry. pub selected: usize, - /// Ratatui list widget state, kept in sync with `selected`. + /// Ratatui list widget state, kept in sync with `selected` (indexes + /// [`list_rows`](App::list_rows), which include group headers). pub list_state: ListState, /// Processed diff for the currently selected file. pub diff: DiffView, @@ -164,6 +175,8 @@ impl App { self.branch = status.branch; self.files = status.files; + // Stable sort: git's path order is kept inside each group. + self.files.sort_by_key(FileEntry::group); if self.files.is_empty() { self.selected = 0; @@ -183,7 +196,7 @@ impl App { self.selected = self.selected.min(self.files.len() - 1); } - self.list_state.select(Some(self.selected)); + self.list_state.select(Some(self.row_of(self.selected))); let same_file = previous.as_deref() == self.selected_file().map(|f| f.path.as_str()); if !same_file { @@ -256,7 +269,7 @@ impl App { } self.selected = index.min(self.files.len() - 1); - self.list_state.select(Some(self.selected)); + self.list_state.select(Some(self.row_of(self.selected))); self.diff_scroll = 0; self.diff_hscroll = 0; self.load_diff(); @@ -287,7 +300,40 @@ impl App { self.select(self.files.len().saturating_sub(1)); } + /// Rows of the file list: a header before each non-empty group, then its files. + pub fn list_rows(&self) -> Vec { + let mut rows = Vec::with_capacity(self.files.len() + 2); + let mut current = None; + for (i, file) in self.files.iter().enumerate() { + let group = file.group(); + if current != Some(group) { + current = Some(group); + let count = self.files[i..] + .iter() + .take_while(|f| f.group() == group) + .count(); + rows.push(ListRow::Header(group, count)); + } + + rows.push(ListRow::File(i)); + } + + rows + } + + /// List row of the file at `index` (accounts for the group headers above it). + pub fn row_of(&self, index: usize) -> usize { + let staged = self + .files + .iter() + .take_while(|f| f.group() == FileGroup::Staged) + .count(); + // The first group always has a header; files past it also sit below the second. + index + 1 + usize::from(staged > 0 && index >= staged) + } + /// Selects the file at screen row `row` (mouse click in the file list). + /// Clicks on group headers are ignored. pub fn click_file(&mut self, row: u16) { let inner_top = self.files_area.y + 1; if row < inner_top || row >= self.files_area.bottom().saturating_sub(1) { @@ -295,8 +341,8 @@ impl App { } let index = self.list_state.offset() + usize::from(row - inner_top); - if index < self.files.len() { - self.select(index); + if let Some(ListRow::File(file)) = self.list_rows().get(index) { + self.select(*file); } } diff --git a/src/types.rs b/src/types.rs index 30525d3..fd63608 100644 --- a/src/types.rs +++ b/src/types.rs @@ -40,4 +40,24 @@ impl FileEntry { pub fn is_new_in_index(&self) -> bool { self.index == 'A' } + + /// The list section this file belongs to. + /// + /// Files with both staged and unstaged changes (`±`) stay in the staged group, + /// since part of them goes into the next commit. + pub fn group(&self) -> FileGroup { + match self.status { + FileStatus::Staged | FileStatus::StagedModified => FileGroup::Staged, + _ => FileGroup::Unstaged, + } + } +} + +/// Section of the file list an entry is shown in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum FileGroup { + /// Changes that will go into the next commit. + Staged, + /// Working-tree changes, untracked and conflicted files. + Unstaged, } diff --git a/src/ui.rs b/src/ui.rs index 3d6bdc1..731967b 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -20,12 +20,14 @@ use unicode_width::UnicodeWidthStr; use crate::app::App; use crate::app::Confirm; +use crate::app::ListRow; use crate::app::MessageKind; use crate::app::Mode; use crate::diff::Row; use crate::diff::RowKind; use crate::git::sanitize; use crate::theme::Theme; +use crate::types::FileGroup; use crate::types::FileStatus; // Only the 16 ANSI colours are used (plus Reset, the terminal's own foreground), @@ -109,10 +111,25 @@ fn render_file_list(frame: &mut Frame, app: &mut App, area: Rect) { // Room for border (2), highlight symbol (2), status icon and space (2). let max_path = usize::from(area.width.saturating_sub(6)); - let items: Vec = app - .files + let rows = app.list_rows(); + let items: Vec = rows .iter() - .map(|file| { + .map(|row| { + let file = match *row { + ListRow::Header(group, count) => { + let (name, color) = match group { + FileGroup::Staged => ("Staged", Color::Green), + FileGroup::Unstaged => ("Unstaged", Color::Red), + }; + + return ListItem::new(Line::styled( + format!("{name} ({count})"), + Style::default().fg(color).add_modifier(Modifier::BOLD), + )); + } + ListRow::File(i) => &app.files[i], + }; + let (icon, color) = status_style(file.status); let path = match &file.orig_path { Some(orig) => format!("{} → {}", sanitize(orig), sanitize(&file.path)), @@ -143,6 +160,15 @@ fn render_file_list(frame: &mut Frame, app: &mut App, area: Rect) { .highlight_style(Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD)) .highlight_symbol("▶ "); + // Keep the group header visible when its first file is selected at the top. + if let Some(selected) = app.list_state.selected() + && selected > 0 + && app.list_state.offset() >= selected + && matches!(rows.get(selected - 1), Some(ListRow::Header(..))) + { + *app.list_state.offset_mut() = selected - 1; + } + frame.render_stateful_widget(list, area, &mut app.list_state); } diff --git a/tests/app.rs b/tests/app.rs index 3449465..77a2d05 100644 --- a/tests/app.rs +++ b/tests/app.rs @@ -1,4 +1,12 @@ +mod common; + +use common::TempRepo; +use gitrat::app::App; +use gitrat::app::ListRow; use gitrat::app::delete_last_word; +use gitrat::theme::Theme; +use gitrat::types::FileGroup; +use ratatui::layout::Rect; #[test] fn deletes_last_word() { @@ -12,3 +20,96 @@ fn deletes_last_word() { delete_last_word(&mut text); assert_eq!(text, ""); } + +fn paths(app: &App) -> Vec<&str> { + app.files.iter().map(|f| f.path.as_str()).collect() +} + +fn assert_rows_match(app: &App) { + let rows = app.list_rows(); + for i in 0..app.files.len() { + assert_eq!(rows[app.row_of(i)], ListRow::File(i)); + } +} + +#[test] +fn groups_staged_files_first() { + let t = TempRepo::new(); + t.write("a.txt", "a\n"); + t.write("b.txt", "b\n"); + t.write("c.txt", "c\n"); + t.git(&["add", "c.txt"]); + + let app = App::new(t.repo.clone(), Theme::new(true, false)); + assert_eq!(paths(&app), ["c.txt", "a.txt", "b.txt"]); + assert_eq!( + app.list_rows(), + [ + ListRow::Header(FileGroup::Staged, 1), + ListRow::File(0), + ListRow::Header(FileGroup::Unstaged, 2), + ListRow::File(1), + ListRow::File(2), + ] + ); + assert_rows_match(&app); +} + +#[test] +fn hides_empty_groups() { + let t = TempRepo::new(); + t.write("a.txt", "a\n"); + let mut app = App::new(t.repo.clone(), Theme::new(true, false)); + assert_eq!( + app.list_rows(), + [ListRow::Header(FileGroup::Unstaged, 1), ListRow::File(0)] + ); + assert_rows_match(&app); + + app.stage_all(); + assert_eq!( + app.list_rows(), + [ListRow::Header(FileGroup::Staged, 1), ListRow::File(0)] + ); + assert_rows_match(&app); +} + +#[test] +fn selection_follows_file_across_groups() { + let t = TempRepo::new(); + t.write("a.txt", "a\n"); + t.write("b.txt", "b\n"); + let mut app = App::new(t.repo.clone(), Theme::new(true, false)); + app.next(); + assert_eq!(app.selected_file().unwrap().path, "b.txt"); + + app.toggle_stage(); + assert_eq!(paths(&app), ["b.txt", "a.txt"]); + assert_eq!(app.selected_file().unwrap().path, "b.txt"); + assert_eq!(app.list_state.selected(), Some(1)); + + app.toggle_stage(); + assert_eq!(paths(&app), ["a.txt", "b.txt"]); + assert_eq!(app.selected_file().unwrap().path, "b.txt"); + assert_eq!(app.list_state.selected(), Some(2)); +} + +#[test] +fn click_skips_group_headers() { + let t = TempRepo::new(); + t.write("a.txt", "a\n"); + t.write("b.txt", "b\n"); + t.git(&["add", "b.txt"]); + let mut app = App::new(t.repo.clone(), Theme::new(true, false)); + app.files_area = Rect::new(0, 0, 30, 10); + + // Rows: 1 "Staged", 2 b.txt, 3 "Unstaged", 4 a.txt. + app.click_file(4); + assert_eq!(app.selected_file().unwrap().path, "a.txt"); + app.click_file(1); + assert_eq!(app.selected_file().unwrap().path, "a.txt"); + app.click_file(3); + assert_eq!(app.selected_file().unwrap().path, "a.txt"); + app.click_file(2); + assert_eq!(app.selected_file().unwrap().path, "b.txt"); +} diff --git a/tests/ui.rs b/tests/ui.rs index 9074234..43eda14 100644 --- a/tests/ui.rs +++ b/tests/ui.rs @@ -42,3 +42,32 @@ fn renders_in_small_and_large_terminals() { } } } + +#[test] +fn renders_group_headers() { + let t = TempRepo::new(); + t.write("staged.txt", "s\n"); + t.write("unstaged.txt", "u\n"); + t.git(&["add", "staged.txt"]); + let mut app = App::new(t.repo.clone(), Theme::new(true, false)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|f| render(f, &mut app)).unwrap(); + let screen: Vec = (0..20) + .map(|y| { + (0..30) + .map(|x| terminal.backend().buffer()[(x, y)].symbol().to_string()) + .collect() + }) + .collect(); + + let line = |text: &str| { + screen + .iter() + .position(|l| l.contains(text)) + .unwrap_or_else(|| panic!("{text:?} not rendered:\n{}", screen.join("\n"))) + }; + assert!(line("Staged (1)") < line("staged.txt")); + assert!(line("staged.txt") < line("Unstaged (1)")); + assert!(line("Unstaged (1)") < line("unstaged.txt")); +}