use crate::tui::shared::scroll::{Axis, BodyScroll};
use crate::tui::syntax::HighlightedSpan;
use crate::tui::views::diff::line_width::{diff_line_rendered_width, read_line_rendered_width};
use ratatui::layout::Rect;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DiffFocus {
#[default]
Files,
Body,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BodyMode {
#[default]
Diff,
Read,
}
#[derive(Debug, Clone)]
pub struct DiffFile {
pub path: String,
pub status: DiffStatus,
pub additions: usize,
pub deletions: usize,
pub binary: bool,
pub old_path: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffStatus {
Modified,
Added,
Deleted,
Renamed,
Untracked,
Other,
}
impl DiffStatus {
pub fn letter(self) -> char {
match self {
DiffStatus::Modified => 'M',
DiffStatus::Added => 'A',
DiffStatus::Deleted => 'D',
DiffStatus::Renamed => 'R',
DiffStatus::Untracked => 'U',
DiffStatus::Other => '?',
}
}
}
#[derive(Debug, Clone)]
pub struct DiffLine {
pub kind: DiffLineKind,
pub text: String,
pub old_lineno: Option<u32>,
pub new_lineno: Option<u32>,
pub spans: Vec<HighlightedSpan>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineKind {
Added,
Removed,
Context,
Hunk,
Header,
}
impl DiffLineKind {
pub fn classify(line: &str) -> Self {
if line.starts_with("@@") {
return DiffLineKind::Hunk;
}
if line.starts_with("diff --git")
|| line.starts_with("index ")
|| line.starts_with("--- ")
|| line.starts_with("+++ ")
|| line.starts_with("Binary files")
|| line.starts_with("new file mode")
|| line.starts_with("deleted file mode")
|| line.starts_with("similarity index")
|| line.starts_with("rename from")
|| line.starts_with("rename to")
|| line.starts_with("copy from")
|| line.starts_with("copy to")
{
return DiffLineKind::Header;
}
if line.starts_with('+') {
return DiffLineKind::Added;
}
if line.starts_with('-') {
return DiffLineKind::Removed;
}
DiffLineKind::Context
}
}
#[derive(Debug, Clone)]
pub struct ReadLine {
pub kind: ReadLineKind,
pub lineno: u32,
pub text: String,
pub spans: Vec<HighlightedSpan>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReadLineKind {
#[default]
Plain,
Added,
Modified,
Separator {
removed: usize,
},
}
#[derive(Debug, Clone, Default)]
pub struct DiffView {
pub files: Vec<DiffFile>,
pub selected: usize,
pub cache: HashMap<String, Vec<DiffLine>>,
pub loaded: bool,
pub error: Option<String>,
pub trunk: Option<String>,
pub anchor: Option<String>,
pub anchor_short: Option<String>,
pub branch: Option<String>,
pub additions_total: usize,
pub deletions_total: usize,
pub focus: DiffFocus,
pub diff_scroll: BodyScroll,
pub read_scroll: BodyScroll,
pub body_height: Cell<u16>,
pub body_width: Cell<u16>,
pub files_rect: Cell<Option<Rect>>,
pub body_rect: Cell<Option<Rect>>,
pub wrap: bool,
pub file_row_rects: RefCell<Vec<Rect>>,
pub lazygit_available: bool,
pub last_g_press: Option<std::time::Instant>,
pub body_mode: BodyMode,
pub read_cache: HashMap<String, Vec<ReadLine>>,
}
impl DiffView {
pub fn set_files(&mut self, files: Vec<DiffFile>) {
self.additions_total = files.iter().map(|f| f.additions).sum();
self.deletions_total = files.iter().map(|f| f.deletions).sum();
self.files = files;
self.loaded = true;
if self.selected >= self.files.len() {
self.selected = self.files.len().saturating_sub(1);
}
self.error = None;
}
pub fn set_error(&mut self, msg: String) {
self.error = Some(msg);
self.loaded = true;
}
pub fn set_anchor(
&mut self,
trunk: Option<String>,
anchor: Option<String>,
branch: Option<String>,
anchor_short: Option<String>,
) {
self.trunk = trunk;
self.anchor = anchor;
self.branch = branch;
self.anchor_short = anchor_short;
}
pub fn set_lazygit_available(&mut self, available: bool) {
self.lazygit_available = available;
}
pub fn select_next(&mut self) {
if self.files.is_empty() {
return;
}
self.selected = (self.selected + 1).min(self.files.len() - 1);
}
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
pub fn select_at(&mut self, idx: usize) {
if self.files.is_empty() {
return;
}
self.selected = idx.min(self.files.len() - 1);
}
pub fn selected_file(&self) -> Option<&DiffFile> {
self.files.get(self.selected)
}
pub fn cache_for(&self, path: &str) -> Option<&Vec<DiffLine>> {
self.cache.get(path)
}
pub fn set_cache(&mut self, path: String, lines: Vec<DiffLine>) {
self.cache.insert(path, lines);
}
pub fn read_cache_for(&self, path: &str) -> Option<&Vec<ReadLine>> {
self.read_cache.get(path)
}
pub fn set_read_cache(&mut self, path: String, lines: Vec<ReadLine>) {
self.read_cache.insert(path, lines);
}
pub fn body_mode(&self) -> BodyMode {
self.body_mode
}
pub fn toggle_body_mode(&mut self) {
self.body_mode = match self.body_mode {
BodyMode::Diff => BodyMode::Read,
BodyMode::Read => BodyMode::Diff,
};
self.last_g_press = None;
}
pub fn mark_stale(&mut self) {
self.loaded = false;
self.cache.clear();
self.diff_scroll.clear();
self.read_cache.clear();
self.read_scroll.clear();
self.additions_total = 0;
self.deletions_total = 0;
}
pub fn focus(&self) -> DiffFocus {
self.focus
}
pub fn toggle_focus(&mut self) {
self.focus = match self.focus {
DiffFocus::Files => DiffFocus::Body,
DiffFocus::Body => DiffFocus::Files,
};
self.last_g_press = None;
}
pub fn set_focus(&mut self, focus: DiffFocus) {
self.focus = focus;
self.last_g_press = None;
}
pub fn body_scroll(&self) -> usize {
let path = match self.selected_file() {
Some(f) => &f.path,
None => return 0,
};
self.active_scroll().get(path, Axis::Vertical)
}
pub fn body_scroll_by(&mut self, delta: i32) {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
let total = self.active_content_len(&path);
let viewport = self.body_height.get() as usize;
let max = total.saturating_sub(viewport.max(1));
self.active_scroll_mut()
.scroll_by(&path, Axis::Vertical, delta, max);
}
pub fn body_scroll_to_top(&mut self) {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
self.active_scroll_mut().set(&path, Axis::Vertical, 0);
}
pub fn body_scroll_to_bottom(&mut self) {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
let total = self.active_content_len(&path);
let viewport = self.body_height.get() as usize;
let bottom = total.saturating_sub(viewport.max(1));
self.active_scroll_mut().set(&path, Axis::Vertical, bottom);
}
fn active_scroll(&self) -> &BodyScroll {
match self.body_mode {
BodyMode::Diff => &self.diff_scroll,
BodyMode::Read => &self.read_scroll,
}
}
fn active_scroll_mut(&mut self) -> &mut BodyScroll {
match self.body_mode {
BodyMode::Diff => &mut self.diff_scroll,
BodyMode::Read => &mut self.read_scroll,
}
}
fn active_max_line_width(&self, path: &str) -> usize {
match self.body_mode {
BodyMode::Diff => {
let Some(lines) = self.cache.get(path) else {
return 0;
};
let max_lineno = lines
.iter()
.filter_map(|l| l.new_lineno.map(u64::from).or(l.old_lineno.map(u64::from)))
.max()
.unwrap_or(0);
let gutter_w = max_lineno.to_string().len().max(1);
lines
.iter()
.map(|l| diff_line_rendered_width(l, gutter_w))
.max()
.unwrap_or(0)
}
BodyMode::Read => {
let Some(lines) = self.read_cache.get(path) else {
return 0;
};
let max_lineno = lines.iter().map(|l| l.lineno).max().unwrap_or(0);
let gutter_w = max_lineno.to_string().len().max(1);
lines
.iter()
.map(|l| read_line_rendered_width(l, gutter_w))
.max()
.unwrap_or(0)
}
}
}
fn max_h_scroll(&self, path: &str) -> usize {
let max_line = self.active_max_line_width(path);
let viewport = self.body_width.get() as usize;
max_line.saturating_sub(viewport)
}
pub fn body_h_scroll(&self) -> usize {
if self.wrap {
return 0;
}
let path = match self.selected_file() {
Some(f) => &f.path,
None => return 0,
};
self.active_scroll()
.get(path, Axis::Horizontal)
.min(self.max_h_scroll(path))
}
pub fn body_h_scroll_by(&mut self, delta: i32) {
if self.wrap {
return;
}
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
let max = self.max_h_scroll(&path);
self.active_scroll_mut()
.scroll_by(&path, Axis::Horizontal, delta, max);
}
fn active_content_len(&self, path: &str) -> usize {
match self.body_mode {
BodyMode::Diff => self.cache.get(path).map(|v| v.len()).unwrap_or(0),
BodyMode::Read => self.read_cache.get(path).map(|v| v.len()).unwrap_or(0),
}
}
pub fn jump_hunk_next(&mut self) {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
let Some(lines) = self.cache.get(&path) else {
return;
};
let cur = self.diff_scroll.get(&path, Axis::Vertical);
let next = lines
.iter()
.enumerate()
.skip(cur + 1)
.find(|(_, l)| l.kind == DiffLineKind::Hunk)
.map(|(i, _)| i);
if let Some(i) = next {
let viewport = self.body_height.get() as usize;
let max = lines.len().saturating_sub(viewport.max(1));
self.diff_scroll.set(&path, Axis::Vertical, i.min(max));
}
}
pub fn jump_hunk_prev(&mut self) {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
let Some(lines) = self.cache.get(&path) else {
return;
};
let cur = self.diff_scroll.get(&path, Axis::Vertical);
let prev = lines
.iter()
.enumerate()
.take(cur)
.rev()
.find(|(_, l)| l.kind == DiffLineKind::Hunk)
.map(|(i, _)| i);
if let Some(i) = prev {
self.diff_scroll.set(&path, Axis::Vertical, i);
}
}
pub fn toggle_wrap(&mut self) {
self.wrap = !self.wrap;
if self.wrap {
let Some(file) = self.files.get(self.selected) else {
return;
};
let path = file.path.clone();
self.diff_scroll.remove(&path, Axis::Horizontal);
self.read_scroll.remove(&path, Axis::Horizontal);
}
}
pub fn consume_g_chord(&mut self) -> bool {
let now = std::time::Instant::now();
let window = std::time::Duration::from_millis(500);
let armed = self
.last_g_press
.map(|t| now.duration_since(t) <= window)
.unwrap_or(false);
self.last_g_press = if armed { None } else { Some(now) };
armed
}
}