From b1f8914cba7a413baa3f62878607d28f8fc8fb14 Mon Sep 17 00:00:00 2001 From: Stephan Dilly Date: Fri, 27 Mar 2020 09:49:57 +0100 Subject: [PATCH] clamp scroll position to valid range --- asyncgit/src/sync/diff.rs | 11 ++++++++--- src/components/diff.rs | 10 ++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/asyncgit/src/sync/diff.rs b/asyncgit/src/sync/diff.rs index 61ac9d4b..3f2e9c89 100644 --- a/asyncgit/src/sync/diff.rs +++ b/asyncgit/src/sync/diff.rs @@ -61,7 +61,7 @@ pub struct Hunk(pub Vec); /// #[derive(Default, Clone, Hash)] -pub struct Diff(pub Vec); +pub struct Diff(pub Vec, pub u16); /// pub fn get_diff(p: String, stage: bool) -> Diff { @@ -94,6 +94,11 @@ pub fn get_diff(p: String, stage: bool) -> Diff { let mut current_lines = Vec::new(); let mut current_hunk: Option = None; + let mut adder = |lines: &Vec| { + res.0.push(Hunk(lines.clone())); + res.1 += lines.len() as u16; + }; + let mut put = |hunk: Option, line: git2::DiffLine| { if let Some(hunk) = hunk { let hunk_header = HunkHeader::from(hunk); @@ -101,7 +106,7 @@ pub fn get_diff(p: String, stage: bool) -> Diff { match current_hunk { None => current_hunk = Some(hunk_header), Some(h) if h != hunk_header => { - res.0.push(Hunk(current_lines.clone())); + adder(¤t_lines); current_lines.clear(); current_hunk = Some(hunk_header) } @@ -170,7 +175,7 @@ pub fn get_diff(p: String, stage: bool) -> Diff { } if !current_lines.is_empty() { - res.0.push(Hunk(current_lines)) + adder(¤t_lines); } res diff --git a/src/components/diff.rs b/src/components/diff.rs index 9119c743..1bb18a09 100644 --- a/src/components/diff.rs +++ b/src/components/diff.rs @@ -4,7 +4,7 @@ use crate::{ }; use asyncgit::{hash, Diff, DiffLine, DiffLineType}; use crossterm::event::{Event, KeyCode}; -use std::borrow::Cow; +use std::{borrow::Cow, cmp}; use tui::{ backend::Backend, layout::{Alignment, Rect}, @@ -27,7 +27,7 @@ pub struct DiffComponent { impl DiffComponent { /// fn can_scroll(&self) -> bool { - self.diff.0.len() > 1 + self.diff.1 > 1 } /// pub fn current(&self) -> (String, bool) { @@ -57,8 +57,10 @@ impl DiffComponent { fn scroll(&mut self, inc: bool) { if inc { - self.scroll = - self.scroll.checked_add(1).unwrap_or(self.scroll); + self.scroll = cmp::min( + self.diff.1.saturating_sub(1), + self.scroll.saturating_add(1), + ); } else { self.scroll = self.scroll.saturating_sub(1); }