Skip to main content

kitchen_ui/widgets/
diff_view.rs

1//! The diff view: a git-style diff of two texts or two JSON documents, with unchanged runs folded
2//! and, for reviewing an agent's proposed change, Accept / Reject per hunk.
3
4use std::collections::BTreeSet;
5
6use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::{Selectable as _, Sizable as _, h_flex, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::{
11    AnyElement, ClipboardItem, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
12    ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, TestSupportExt as _,
13    Window, div, px,
14};
15
16use crate::diff::{ARRAY_SUMMARY, CONTEXT, Diff, DiffLine, LineKind};
17use crate::theme::{self, color};
18use crate::widgets::icon_button;
19
20/// What the reviewer decided for a hunk ([`DiffView::reviewable`]).
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct HunkDecision {
23    /// The hunk ([`Diff::hunks`] index).
24    pub hunk: usize,
25    /// Accepted (`true`) or rejected.
26    pub accept: bool,
27}
28
29/// A git-style diff: added lines on a green tint, removed lines on a red one (the shared
30/// success / danger colours, contrast-checked in both themes), old and new line numbers, a header
31/// per hunk, and the unchanged runs between hunks folded to one line ("⋯ 12 unchanged lines",
32/// a click shows them). Each hunk keeps [`CONTEXT`] unchanged lines around its changes.
33///
34/// [`DiffView::json`] compares JSON by key (sorted keys, long arrays as one summary line: see
35/// [`crate::diff`]). [`DiffView::reviewable`] adds Accept / Reject to each hunk; a choice emits
36/// [`HunkDecision`] and stays shown. The header counts the lines and copies the diff as text.
37pub struct DiffView {
38    id: SharedString,
39    title: Option<SharedString>,
40    diff: Diff,
41    expanded: BTreeSet<usize>,
42    reviewable: bool,
43    decisions: Vec<Option<bool>>,
44}
45
46impl EventEmitter<HunkDecision> for DiffView {}
47
48impl DiffView {
49    /// A view of `diff`. `id` names its elements (unique in the window).
50    pub fn new(id: impl Into<SharedString>, diff: Diff) -> Self {
51        let decisions = vec![None; diff.hunks.len()];
52        Self { id: id.into(), title: None, diff, expanded: BTreeSet::new(), reviewable: false, decisions }
53    }
54
55    /// The line diff of two texts.
56    pub fn text(id: impl Into<SharedString>, old: &str, new: &str) -> Self {
57        Self::new(id, Diff::text(old, new, CONTEXT))
58    }
59
60    /// Two JSON documents compared by key ([`Diff::json`]): reordered keys are not changes, long
61    /// arrays are one line.
62    pub fn json(id: impl Into<SharedString>, old: &str, new: &str) -> Self {
63        Self::new(id, Diff::json(old, new, CONTEXT, ARRAY_SUMMARY))
64    }
65
66    /// A title in the header (a file name: `session.json`).
67    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
68        self.title = Some(title.into());
69        self
70    }
71
72    /// Accept / Reject buttons on each hunk (an agent's proposed change under review).
73    pub fn reviewable(mut self, reviewable: bool) -> Self {
74        self.reviewable = reviewable;
75        self
76    }
77
78    /// Shows another diff (the decisions and unfolded runs are cleared).
79    pub fn set_diff(&mut self, diff: Diff, cx: &mut Context<Self>) {
80        self.decisions = vec![None; diff.hunks.len()];
81        self.expanded.clear();
82        self.diff = diff;
83        cx.notify();
84    }
85
86    /// The diff shown.
87    pub fn diff(&self) -> &Diff {
88        &self.diff
89    }
90
91    /// The decision on each hunk so far (`None`: not decided).
92    pub fn decisions(&self) -> &[Option<bool>] {
93        &self.decisions
94    }
95
96    /// Accepts or rejects `hunk` and tells the owner.
97    pub fn decide(&mut self, hunk: usize, accept: bool, cx: &mut Context<Self>) {
98        if let Some(d) = self.decisions.get_mut(hunk) {
99            *d = Some(accept);
100            cx.emit(HunkDecision { hunk, accept });
101            cx.notify();
102        }
103    }
104
105    /// Shows (or folds again) the unchanged run [`Diff::gaps`]`[gap]`.
106    pub fn toggle_gap(&mut self, gap: usize, cx: &mut Context<Self>) {
107        if !self.expanded.remove(&gap) {
108            self.expanded.insert(gap);
109        }
110        cx.notify();
111    }
112
113    fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
114        let (added, removed) = (self.diff.added(), self.diff.removed());
115        let unified = self.diff.unified();
116        let copy = icon_button(SharedString::from(format!("{}-copy", self.id)), IconName::Copy, "Copy the diff")
117            .on_click(move |_, _, cx| {
118                cx.write_to_clipboard(ClipboardItem::new_string(unified.clone()));
119            });
120        let all_open = self.expanded.len() == self.diff.gaps().len();
121        let gaps = self.diff.gaps().len();
122        let unfold = icon_button(
123            SharedString::from(format!("{}-unfold", self.id)),
124            if all_open { IconName::ChevronUp } else { IconName::ChevronsUpDown },
125            if all_open { "Fold the unchanged lines" } else { "Show every line" },
126        )
127        .on_click(cx.listener(move |this, _, _, cx| {
128            if this.expanded.len() == gaps {
129                this.expanded.clear();
130            } else {
131                this.expanded = (0..gaps).collect();
132            }
133            cx.notify();
134        }));
135        h_flex()
136            .w_full()
137            .gap(px(theme::SM))
138            .px(px(theme::SM))
139            .py(px(theme::XS))
140            .bg(color::raised())
141            .border_b_1()
142            .border_color(color::border())
143            .when_some(self.title.clone(), |d, t| {
144                d.child(div().min_w_0().truncate().text_sm().font_weight(FontWeight::SEMIBOLD).child(t))
145            })
146            .child(div().text_sm().font_family("monospace").text_color(color::success()).child(format!("+{added}")))
147            .child(div().text_sm().font_family("monospace").text_color(color::danger()).child(format!("−{removed}")))
148            .when(self.diff.json, |d| d.child(div().text_xs().text_color(color::text_muted()).child("JSON, by key")))
149            .child(div().flex_1())
150            .when(gaps > 0, |d| d.child(unfold))
151            .child(copy)
152    }
153
154    fn hunk_header(&self, i: usize, cx: &mut Context<Self>) -> impl IntoElement {
155        let h = &self.diff.hunks[i];
156        let decided = self.decisions.get(i).copied().flatten();
157        let review = self.reviewable.then(|| {
158            let accept = Button::new(SharedString::from(format!("{}-accept-{i}", self.id)))
159                .small()
160                .icon(IconName::Check)
161                .label("Accept")
162                .when(decided == Some(true), |b| b.primary())
163                .when(decided != Some(true), |b| b.outline())
164                .selected(decided == Some(true))
165                .tooltip("Keep this change")
166                .on_click(cx.listener(move |this, _, _, cx| this.decide(i, true, cx)));
167            let reject = Button::new(SharedString::from(format!("{}-reject-{i}", self.id)))
168                .small()
169                .icon(IconName::Close)
170                .label("Reject")
171                .when(decided == Some(false), |b| b.danger())
172                .when(decided != Some(false), |b| b.outline())
173                .selected(decided == Some(false))
174                .tooltip("Drop this change")
175                .on_click(cx.listener(move |this, _, _, cx| this.decide(i, false, cx)));
176            h_flex().gap(px(theme::XS)).child(accept).child(reject)
177        });
178        let status = decided.map(|a| {
179            let (text, c) = if a { ("Accepted", color::success()) } else { ("Rejected", color::danger()) };
180            div().text_xs().font_weight(FontWeight::SEMIBOLD).text_color(c).child(text)
181        });
182        h_flex()
183            .w_full()
184            .min_h(px(theme::TARGET_MIN + theme::XS))
185            .gap(px(theme::SM))
186            .px(px(theme::SM))
187            .bg(color::raised())
188            .border_t_1()
189            .border_b_1()
190            .border_color(color::border())
191            .child(
192                div()
193                    .flex_1()
194                    .min_w_0()
195                    .truncate()
196                    .text_xs()
197                    .font_family("monospace")
198                    .text_color(color::text_muted())
199                    .child(h.header()),
200            )
201            .children(status)
202            .children(review)
203    }
204
205    fn gap_row(&self, gap: usize, len: usize, cx: &mut Context<Self>) -> impl IntoElement {
206        let label = if len == 1 {
207            "⋯ 1 unchanged line".to_string()
208        } else {
209            format!("⋯ {} unchanged lines", crate::diff::group_digits(len))
210        };
211        h_flex()
212            .id(SharedString::from(format!("{}-gap-{gap}", self.id)))
213            .w_full()
214            .min_h(px(theme::TARGET_MIN))
215            .px(px(theme::SM))
216            .bg(color::panel())
217            .text_xs()
218            .text_color(color::text_muted())
219            .cursor_pointer()
220            .hover(|d| d.bg(color::hover()))
221            .child(label)
222            .on_click(cx.listener(move |this, _, _, cx| this.toggle_gap(gap, cx)))
223            .test_support()
224    }
225}
226
227/// One line of the diff: old number, new number, sign, text.
228fn line_row(l: &DiffLine) -> AnyElement {
229    let (bg, sign, sign_color): (Option<Hsla>, &str, Hsla) = match l.kind {
230        LineKind::Context => (None, " ", color::text_muted()),
231        LineKind::Added => (Some(color::diff_added()), "+", color::success()),
232        LineKind::Removed => (Some(color::diff_removed()), "−", color::danger()),
233        LineKind::Summary => (Some(color::control()), "~", color::text_muted()),
234    };
235    let num = |n: Option<usize>| {
236        div()
237            .flex_none()
238            .w(px(40.))
239            .pr(px(theme::XS))
240            .text_right()
241            .text_color(color::text_muted())
242            .child(n.map(|n| n.to_string()).unwrap_or_default())
243    };
244    h_flex()
245        .w_full()
246        .items_start()
247        .font_family("monospace")
248        .text_xs()
249        .when_some(bg, |d, bg| d.bg(bg))
250        .child(num(l.old))
251        .child(num(l.new))
252        .child(
253            div()
254                .flex_none()
255                .w(px(16.))
256                .text_center()
257                .font_weight(FontWeight::SEMIBOLD)
258                .text_color(sign_color)
259                .child(sign),
260        )
261        .child(
262            div()
263                .flex_1()
264                .min_w_0()
265                .pr(px(theme::SM))
266                .when(l.kind == LineKind::Summary, |d| d.italic())
267                .child(if l.text.is_empty() { " ".to_string() } else { l.text.clone() }),
268        )
269        .into_any_element()
270}
271
272impl Render for DiffView {
273    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
274        let gaps = self.diff.gaps();
275        let mut body: Vec<AnyElement> = Vec::new();
276        if let Some(note) = &self.diff.note {
277            body.push(
278                div()
279                    .px(px(theme::SM))
280                    .py(px(theme::XS))
281                    .text_xs()
282                    .text_color(color::warning())
283                    .child(note.clone())
284                    .into_any_element(),
285            );
286        }
287        if self.diff.is_empty() {
288            body.push(
289                div()
290                    .px(px(theme::SM))
291                    .py(px(theme::SM))
292                    .text_sm()
293                    .text_color(color::text_muted())
294                    .child("No changes.")
295                    .into_any_element(),
296            );
297        } else {
298            // Walk the lines: folded runs and hunks in order
299            let mut gi = 0;
300            for hi in 0..self.diff.hunks.len() {
301                let start = self.diff.hunks[hi].lines.start;
302                while gi < gaps.len() && gaps[gi].end <= start {
303                    body.extend(self.gap(gi, &gaps, cx));
304                    gi += 1;
305                }
306                body.push(self.hunk_header(hi, cx).into_any_element());
307                body.extend(self.diff.lines[self.diff.hunks[hi].lines.clone()].iter().map(line_row));
308            }
309            while gi < gaps.len() {
310                body.extend(self.gap(gi, &gaps, cx));
311                gi += 1;
312            }
313        }
314        v_flex()
315            .id(self.id.clone())
316            .size_full()
317            .rounded(px(theme::RADIUS_LG))
318            .border_1()
319            .border_color(color::border())
320            .bg(color::panel())
321            .overflow_hidden()
322            .child(self.header(cx))
323            .child(
324                v_flex()
325                    .id(SharedString::from(format!("{}-body", self.id)))
326                    .flex_1()
327                    .min_h_0()
328                    .w_full()
329                    .overflow_y_scroll()
330                    .children(body),
331            )
332    }
333}
334
335impl DiffView {
336    /// A folded run as its expander, or its lines when shown.
337    fn gap(&self, gi: usize, gaps: &[std::ops::Range<usize>], cx: &mut Context<Self>) -> Vec<AnyElement> {
338        let range = gaps[gi].clone();
339        if self.expanded.contains(&gi) {
340            let mut out = vec![self.gap_row_open(gi, cx).into_any_element()];
341            out.extend(self.diff.lines[range].iter().map(line_row));
342            out
343        } else {
344            vec![self.gap_row(gi, range.len(), cx).into_any_element()]
345        }
346    }
347
348    fn gap_row_open(&self, gap: usize, cx: &mut Context<Self>) -> impl IntoElement {
349        h_flex()
350            .id(SharedString::from(format!("{}-gap-{gap}", self.id)))
351            .w_full()
352            .min_h(px(theme::TARGET_MIN))
353            .px(px(theme::SM))
354            .text_xs()
355            .text_color(color::text_muted())
356            .cursor_pointer()
357            .hover(|d| d.bg(color::hover()))
358            .child("Fold the unchanged lines")
359            .on_click(cx.listener(move |this, _, _, cx| this.toggle_gap(gap, cx)))
360            .test_support()
361    }
362}