Skip to main content

comb/widgets/
diff.rs

1//! A scrollable unified-diff view (additions / deletions / context).
2
3use crate::core::buffer::Buffer;
4use crate::core::geom::Rect;
5use crate::core::style::{Color, Style};
6use crate::core::text::{Line, Span};
7use crate::term::event::MouseKind;
8use crate::widgets::scrollbar::Scrollbar;
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug)]
11pub enum DiffOp {
12    Header,
13    Context,
14    Add,
15    Delete,
16}
17
18/// Colours for a diff view.
19#[derive(Clone, Copy, Debug)]
20pub struct DiffTheme {
21    pub header: Style,
22    pub context: Style,
23    pub add: Style,
24    pub delete: Style,
25    pub meta: Style,
26}
27
28impl DiffTheme {
29    pub fn dark() -> Self {
30        DiffTheme {
31            header: Style::new().fg(Color::rgb(0x7a, 0xa2, 0xf7)).bold(),
32            context: Style::new().fg(Color::rgb(0xa0, 0xa0, 0xa0)),
33            add: Style::new().fg(Color::rgb(0x81, 0xc7, 0x84)),
34            delete: Style::new().fg(Color::rgb(0xe5, 0x73, 0x73)),
35            meta: Style::new().fg(Color::rgb(0x70, 0x70, 0x70)),
36        }
37    }
38}
39
40/// Scrollable highlighted unified diff.
41pub struct DiffView {
42    pub theme: DiffTheme,
43    pub scrollbar: Scrollbar,
44    pub offset: usize,
45    lines: Vec<Line>,
46}
47
48impl DiffView {
49    pub fn new(old: &str, new: &str) -> Self {
50        let mut v = DiffView {
51            theme: DiffTheme::dark(),
52            scrollbar: Scrollbar::default(),
53            offset: 0,
54            lines: Vec::new(),
55        };
56        v.set_diff(old, new);
57        v
58    }
59
60    pub fn from_lines(lines: Vec<Line>) -> Self {
61        DiffView {
62            theme: DiffTheme::dark(),
63            scrollbar: Scrollbar::default(),
64            offset: 0,
65            lines,
66        }
67    }
68
69    pub fn set_diff(&mut self, old: &str, new: &str) {
70        self.lines = unified_diff(old, new, &self.theme);
71        self.offset = 0;
72    }
73
74    pub fn line_count(&self) -> usize {
75        self.lines.len()
76    }
77
78    pub fn scroll_by(&mut self, delta: isize) {
79        let last = self.lines.len().saturating_sub(1) as isize;
80        self.offset = (self.offset as isize + delta).clamp(0, last.max(0)) as usize;
81    }
82
83    pub fn render(&mut self, buf: &mut Buffer, area: Rect, bg: Option<Style>) {
84        if area.is_empty() {
85            return;
86        }
87        if let Some(bg) = bg {
88            buf.paint(area, bg);
89        }
90        let h = area.height as usize;
91        let overflow = self.lines.len() > h;
92        let content = self.scrollbar.content_area(area, overflow);
93        self.offset = self.offset.min(self.lines.len().saturating_sub(h));
94        match bg {
95            Some(bg) => buf.set_lines_on(content, &self.lines, self.offset, bg),
96            None => buf.set_lines(content, &self.lines, self.offset),
97        }
98        if overflow {
99            let bar = self.scrollbar.area(area);
100            self.scrollbar
101                .render(buf, bar, self.lines.len(), h, self.offset);
102        }
103    }
104
105    pub fn handle_mouse(&mut self, area: Rect, kind: MouseKind, col: u16, row: u16) -> bool {
106        let h = area.height as usize;
107        let overflow = self.lines.len() > h;
108        if !overflow {
109            return false;
110        }
111        let bar_area = self.scrollbar.area(area);
112        if self.scrollbar.is_dragging() || bar_area.contains(col, row) {
113            return self.scrollbar.on_mouse(
114                bar_area,
115                self.lines.len(),
116                h,
117                &mut self.offset,
118                kind,
119                col,
120                row,
121            );
122        }
123        let content = self.scrollbar.content_area(area, true);
124        if !content.contains(col, row) {
125            return false;
126        }
127        match kind {
128            MouseKind::ScrollUp => {
129                self.scroll_by(-3);
130                true
131            }
132            MouseKind::ScrollDown => {
133                self.scroll_by(3);
134                true
135            }
136            _ => false,
137        }
138    }
139
140    pub fn end_drag(&mut self) {
141        self.scrollbar.end_drag();
142    }
143}
144
145/// Build a simple unified diff between `old` and `new` (line-based LCS).
146pub fn unified_diff(old: &str, new: &str, theme: &DiffTheme) -> Vec<Line> {
147    let a: Vec<&str> = old.lines().collect();
148    let b: Vec<&str> = new.lines().collect();
149    let mut out = Vec::new();
150    out.push(line("--- a/source.rs".to_string(), theme.meta));
151    out.push(line("+++ b/source.rs".to_string(), theme.meta));
152    out.push(line(
153        format!("@@ -1,{} +1,{} @@", a.len(), b.len()),
154        theme.header,
155    ));
156
157    let pairs = lcs_ops(&a, &b);
158    for (op, text) in pairs {
159        let (prefix, st) = match op {
160            DiffOp::Context => (' ', theme.context),
161            DiffOp::Add => ('+', theme.add),
162            DiffOp::Delete => ('-', theme.delete),
163            DiffOp::Header => ('@', theme.header),
164        };
165        out.push(line(format!("{prefix}{text}"), st));
166    }
167    out
168}
169
170fn line(s: String, st: Style) -> Line {
171    Line::from(Span::styled(s, st))
172}
173
174fn lcs_ops<'a>(a: &[&'a str], b: &[&'a str]) -> Vec<(DiffOp, &'a str)> {
175    let (n, m) = (a.len(), b.len());
176    let mut dp = vec![vec![0u16; m + 1]; n + 1];
177    for i in 0..n {
178        for j in 0..m {
179            dp[i + 1][j + 1] = if a[i] == b[j] {
180                dp[i][j] + 1
181            } else {
182                dp[i][j + 1].max(dp[i + 1][j])
183            };
184        }
185    }
186    let mut ops = Vec::new();
187    let (mut i, mut j) = (n, m);
188    while i > 0 || j > 0 {
189        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {
190            ops.push((DiffOp::Context, a[i - 1]));
191            i -= 1;
192            j -= 1;
193        } else if j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j]) {
194            ops.push((DiffOp::Add, b[j - 1]));
195            j -= 1;
196        } else {
197            ops.push((DiffOp::Delete, a[i - 1]));
198            i -= 1;
199        }
200    }
201    ops.reverse();
202    ops
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn detects_add_and_delete() {
211        let theme = DiffTheme::dark();
212        let lines = unified_diff("a\nb\nc\n", "a\nx\nc\n", &theme);
213        let text: Vec<String> = lines
214            .iter()
215            .map(|l| l.spans.iter().map(|s| s.content.clone()).collect())
216            .collect();
217        assert!(text.iter().any(|t| t.starts_with("-b")));
218        assert!(text.iter().any(|t| t.starts_with("+x")));
219        assert!(text.iter().any(|t| t.starts_with(" a") || t == " a"));
220    }
221}