clamp scroll position to valid range

This commit is contained in:
Stephan Dilly 2020-03-27 09:49:57 +01:00
parent 8ade74f201
commit b1f8914cba
2 changed files with 14 additions and 7 deletions

View File

@ -61,7 +61,7 @@ pub struct Hunk(pub Vec<DiffLine>);
///
#[derive(Default, Clone, Hash)]
pub struct Diff(pub Vec<Hunk>);
pub struct Diff(pub Vec<Hunk>, 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<HunkHeader> = None;
let mut adder = |lines: &Vec<DiffLine>| {
res.0.push(Hunk(lines.clone()));
res.1 += lines.len() as u16;
};
let mut put = |hunk: Option<DiffHunk>, 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(&current_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(&current_lines);
}
res

View File

@ -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);
}