Diff
A fast patch viewer, unified or side by side, with syntax highlighting and actions on selected lines.
Starting the preview. GPUI compiles to WebAssembly, so the first load takes a few seconds. This browser has neither WebGPU nor WebGL 2, so the live preview cannot run. The code on this page still works. The preview did not start.
fn diff_preview(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let t = UiTheme::read(cx).clone();
let s = t.spacing.unit;
let state = window
.use_keyed_state("diff_preview.state", cx, |_, cx| {
cx.new(|cx| DiffState::new(DiffFile::parse(PATCH).expect("sample patch parses"), cx))
})
.read(cx)
.clone();
let mode = window.use_keyed_state("diff_preview.mode", cx, |_, _| vec![SharedString::from("unified")]);
let note = window.use_keyed_state("diff_preview.note", cx, |_, _| {
SharedString::from("Drag across line numbers to select lines")
});
let mode_state = state.clone();
let mode_value = mode.clone();
let toggle = ToggleGroup::new("diff.mode")
.aria_label("Layout")
.segmented(true)
.value(mode.read(cx).clone())
.item(ToggleGroupItem::new("unified", "unified").aria_label("Unified").child("Unified"))
.item(ToggleGroupItem::new("split", "split").aria_label("Side by side").child("Side by side"))
.on_change(move |next, _, cx| {
let Some(value) = next.first().cloned() else { return };
mode_state.update(cx, |state, cx| {
state.set_mode(if value == "split" { DiffMode::Split } else { DiffMode::Unified }, cx)
});
mode_value.update(cx, |mode, cx| {
*mode = vec![value];
cx.notify();
});
});
let note_events = note.clone();
let view = DiffView::new("diff.view", &state)
.selection_actions([
DiffAction::new("stage", "Stage lines").icon(LucideIcon::Plus),
DiffAction::new("discard", "Discard lines").icon(LucideIcon::Undo2).destructive(true),
])
.file_actions([DiffAction::new("stage-file", "Stage file")])
.hunk_action(
DiffAction::new("stage-hunk", "Stage hunk").icon(LucideIcon::Plus),
[
DiffLineRange::new("src/repository.rs", DiffSide::Original, 14, 24)
.with_end_side(DiffSide::Modified),
DiffLineRange::new(".env", DiffSide::Original, 1, 2),
],
)
.on_intent(move |intent, _, cx| {
let what = match &intent.range {
Some(range) => format!("lines {}–{} of {}", range.start(), range.end(), intent.path),
None => intent.path.to_string(),
};
note_events.update(cx, |note, cx| {
*note = format!("{} · {what}", intent.action).into();
cx.notify();
});
});
div()
.size_full()
.min_w_0()
.min_h_0()
.flex()
.flex_col()
.gap(s * 2_f32)
.p(s * 2_f32)
.font_family(t.fonts.body.clone())
.child(toggle)
.child(div().flex_1().min_h_0().child(view))
.child(
div()
.text_size(px(12.) * t.text_scale)
.text_color(t.colors.muted_foreground)
.child(note.read(cx).clone()),
)
}
Installation
After the one-time setup, run the command from your app root. The CLI
writes the modules and keeps src/ui/mod.rs in step.
gpuicn add diff
If you prefer to copy the files by hand, declare them yourself:
// src/ui/mod.rs
pub mod theme;
pub mod button;
pub mod tooltip;
pub mod diff;
// src/main.rs
mod ui;
Usage
Put this in a view module and return example(patch, window, cx) from its render method.
use crate::ui::diff::*;
use gpui_kit::{App, AppContext as _, IntoElement, Window};
fn example(patch: &str, window: &mut Window, cx: &mut App) -> impl IntoElement {
// Parse once and keep the state; call `set_files` when the patch changes.
let files = DiffFile::parse(patch).unwrap_or_default();
let state = window
.use_keyed_state("diff", cx, |_, cx| cx.new(|cx| DiffState::new(files, cx)))
.read(cx)
.clone();
DiffView::new("diff", &state)
.selection_actions([DiffAction::new("stage", "Stage lines")])
.on_intent(|intent, _, _| {
// Build and apply the partial patch for `intent.range` here.
let _ = intent;
})
}
API reference
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self
An action with a stable ID and a visible label.
pub fn icon(mut self, icon: LucideIcon) -> Self
A leading Lucide icon.
pub fn destructive(mut self, destructive: bool) -> Self
Marks the action as destructive.
pub fn new(id: impl Into<ElementId>, state: &Entity<DiffState>) -> Self
A view of `state`; keep the state in your view and replace its files with `DiffState::set_files` when the patch changes.
pub fn read_only(mut self, read_only: bool) -> Self
Hides every action, for commit and review diffs.
pub fn selection_actions(mut self, actions: impl IntoIterator<Item = DiffAction>) -> Self
Actions shown under the selected lines once a selection ends.
pub fn file_actions(mut self, actions: impl IntoIterator<Item = DiffAction>) -> Self
Actions shown in every file header.
pub fn hunk_action(
mut self,
action: DiffAction,
hunks: impl IntoIterator<Item = DiffLineRange>,
) -> Self
One action for each of `hunks`, shown as a small icon button in the gutter beside the hunk's first line, such as "Stage hunk". Its intent carries the hunk's range. Give the action an icon; the label is its tooltip and accessible name. The buttons take a gutter lane, which changes the state's layout: give every view of one [`DiffState`] the same hunk action, or none.
pub fn header_visible(mut self, visible: bool) -> Self
Shows or hides the file headers, for a view of one file whose path is already shown elsewhere. Default is shown.
pub fn on_intent(
mut self,
handler: impl Fn(&DiffIntent, &mut Window, &mut App) + 'static,
) -> Self
Receives each intent. Selection is cleared after a selection action.
pub fn soft_wrap(mut self, soft_wrap: bool) -> Self
Wraps long lines instead of scrolling horizontally.
pub fn selection_anchor(
state: &DiffState,
read_only: bool,
has_actions: bool,
) -> Option<(DiffLineRange, DiffLinePosition)>
Where the selection's action strip goes: under the last selected line. `None` in read-only mode, without actions, or without a selection.
Installed source, 490 lines
//! Diff: a virtualized patch viewer, unified or side by side, with syntax
//! highlighting, line selection and caller-defined actions on the selection.
//!
//! GPUI Kit's `diff` supplies parsing, virtualization, both layouts, syntax
//! and inline-change highlighting, text copy and keyboard scrolling, and reads
//! the gpuicn theme through the synced Kit theme. gpuicn adds Nova defaults,
//! a read-only mode and an action strip under the selected lines whose
//! buttons report [`DiffIntent`]s with the selected range. Git execution and
//! patch building stay in the application.
use std::rc::Rc;
use gpui_icons::{LucideIcon, lucide};
use gpui_kit::{
App, ElementId, Entity, IntoElement, ParentElement as _, Refineable as _, RenderOnce,
SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _,
};
pub use gpui_kit::component::diff::{
Diff as KitDiff, DiffAnnotation, DiffChangeIndicator, DiffDecoration, DiffEvent, DiffFile,
DiffFileStatus, DiffGutterMarker, DiffHoverHighlight, DiffHunkSeparator, DiffLinePosition,
DiffLineRange, DiffMode, DiffParseError, DiffParseOptions, DiffSide, DiffState,
};
use super::button::{Button, ButtonSize, ButtonVariant};
use super::theme::UiTheme;
/// An action offered on a selection of lines or on a whole file, such as
/// "Stage lines" or "Discard file".
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffAction {
/// Stable ID reported back in [`DiffIntent`].
pub id: SharedString,
/// The button text.
pub label: SharedString,
/// An optional leading icon.
pub icon: Option<LucideIcon>,
/// Drawn as a destructive button; confirm before acting.
pub destructive: bool,
}
impl DiffAction {
/// An action with a stable ID and a visible label.
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
destructive: false,
}
}
/// A leading Lucide icon.
pub fn icon(mut self, icon: LucideIcon) -> Self {
self.icon = Some(icon);
self
}
/// Marks the action as destructive.
pub fn destructive(mut self, destructive: bool) -> Self {
self.destructive = destructive;
self
}
}
/// What the person asked to do, with the lines or file it applies to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffIntent {
/// The [`DiffAction::id`].
pub action: SharedString,
/// The file's path.
pub path: SharedString,
/// The selected lines, or `None` for a file action.
pub range: Option<DiffLineRange>,
}
type IntentHandler = Rc<dyn Fn(&DiffIntent, &mut Window, &mut App)>;
/// Renders a [`DiffState`] with Nova defaults. Without actions, or with
/// [`DiffView::read_only`], it is a viewer only: selection and copy still
/// work, and no intent is ever reported.
#[derive(IntoElement)]
pub struct DiffView {
id: ElementId,
state: Entity<DiffState>,
read_only: bool,
selection_actions: Vec<DiffAction>,
file_actions: Vec<DiffAction>,
hunk_action: Option<(DiffAction, Vec<DiffLineRange>)>,
on_intent: Option<IntentHandler>,
soft_wrap: bool,
header_visible: bool,
style: gpui_kit::StyleRefinement,
}
impl DiffView {
/// A view of `state`; keep the state in your view and replace its files
/// with `DiffState::set_files` when the patch changes.
pub fn new(id: impl Into<ElementId>, state: &Entity<DiffState>) -> Self {
Self {
id: id.into(),
state: state.clone(),
read_only: false,
selection_actions: Vec::new(),
file_actions: Vec::new(),
hunk_action: None,
on_intent: None,
soft_wrap: false,
header_visible: true,
style: Default::default(),
}
}
/// Hides every action, for commit and review diffs.
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
/// Actions shown under the selected lines once a selection ends.
pub fn selection_actions(mut self, actions: impl IntoIterator<Item = DiffAction>) -> Self {
self.selection_actions = actions.into_iter().collect();
self
}
/// Actions shown in every file header.
pub fn file_actions(mut self, actions: impl IntoIterator<Item = DiffAction>) -> Self {
self.file_actions = actions.into_iter().collect();
self
}
/// One action for each of `hunks`, shown as a small icon button in the
/// gutter beside the hunk's first line, such as "Stage hunk". Its intent
/// carries the hunk's range. Give the action an icon; the label is its
/// tooltip and accessible name.
///
/// The buttons take a gutter lane, which changes the state's layout: give
/// every view of one [`DiffState`] the same hunk action, or none.
pub fn hunk_action(
mut self,
action: DiffAction,
hunks: impl IntoIterator<Item = DiffLineRange>,
) -> Self {
self.hunk_action = Some((action, hunks.into_iter().collect()));
self
}
/// Shows or hides the file headers, for a view of one file whose path is
/// already shown elsewhere. Default is shown.
pub fn header_visible(mut self, visible: bool) -> Self {
self.header_visible = visible;
self
}
/// Receives each intent. Selection is cleared after a selection action.
pub fn on_intent(
mut self,
handler: impl Fn(&DiffIntent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_intent = Some(Rc::new(handler));
self
}
/// Wraps long lines instead of scrolling horizontally.
pub fn soft_wrap(mut self, soft_wrap: bool) -> Self {
self.soft_wrap = soft_wrap;
self
}
}
impl Styled for DiffView {
fn style(&mut self) -> &mut gpui_kit::StyleRefinement {
&mut self.style
}
}
/// Where the selection's action strip goes: under the last selected line.
/// `None` in read-only mode, without actions, or without a selection.
pub fn selection_anchor(
state: &DiffState,
read_only: bool,
has_actions: bool,
) -> Option<(DiffLineRange, DiffLinePosition)> {
if read_only || !has_actions {
return None;
}
let range = state.selected_lines()?;
let end = DiffLinePosition::new(range.path().clone(), range.end_side(), range.end());
Some((range, end))
}
fn action_button(
id: ElementId,
action: &DiffAction,
theme: &UiTheme,
on_click: impl Fn(&mut Window, &mut App) + 'static,
) -> Button {
Button::new(id)
.size(ButtonSize::Xs)
.variant(if action.destructive {
ButtonVariant::Destructive
} else {
ButtonVariant::Outline
})
.aria_label(action.label.clone())
.when_some(action.icon, |button, icon| {
button.child(lucide(icon).size(theme.spacing.unit * 3.5_f32).text_color(
if action.destructive {
theme.colors.destructive_foreground
} else {
theme.colors.foreground
},
))
})
.label(action.label.clone())
.on_click(move |_, window, cx| on_click(window, cx))
}
impl RenderOnce for DiffView {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = UiTheme::read(cx).clone();
let anchor = selection_anchor(
self.state.read(cx),
self.read_only,
!self.selection_actions.is_empty(),
);
let mut diff = KitDiff::new(&self.state)
.hover_highlight(DiffHoverHighlight::LineNumber)
.change_indicator(DiffChangeIndicator::Bars)
.soft_wrap(self.soft_wrap)
.header_visible(self.header_visible)
.font_family(theme.fonts.mono.clone());
if let Some((range, end)) = anchor {
let actions = Rc::new(self.selection_actions);
let handler = self.on_intent.clone();
let state = self.state.clone();
let strip_theme = theme.clone();
diff = diff
.annotations([DiffAnnotation::line(
ElementId::NamedChild(std::sync::Arc::new(self.id.clone()), "selection".into()),
end,
)])
.render_annotation(move |_, _, _| {
let mut strip = div()
.flex()
.flex_wrap()
.gap(strip_theme.spacing.unit * 2_f32)
.px(strip_theme.spacing.unit * 3_f32)
.py(strip_theme.spacing.unit * 2_f32)
.bg(strip_theme.colors.muted)
.border_y_1()
.border_color(strip_theme.colors.border)
.font_family(strip_theme.fonts.body.clone());
for action in actions.iter() {
let handler = handler.clone();
let state = state.clone();
let intent = DiffIntent {
action: action.id.clone(),
path: range.path().clone(),
range: Some(range.clone()),
};
strip = strip.child(action_button(
ElementId::Name(format!("diff.selection.{}", action.id).into()),
action,
&strip_theme,
move |window, cx| {
state.update(cx, |state, cx| state.set_selected_lines(None, cx));
if let Some(handler) = &handler {
handler(&intent, window, cx);
}
},
));
}
strip
});
}
if let Some((action, hunks)) = self
.hunk_action
.filter(|(_, hunks)| !self.read_only && !hunks.is_empty())
{
let ranges: Rc<Vec<DiffLineRange>> = Rc::new(hunks);
let markers: Vec<DiffGutterMarker> = ranges
.iter()
.enumerate()
.map(|(ix, range)| {
DiffGutterMarker::new(
ElementId::Name(format!("diff.hunk.{}.{ix}", range.path()).into()),
DiffLinePosition::new(range.path().clone(), range.side(), range.start()),
)
.with_label(action.label.clone())
})
.collect();
let handler = self.on_intent.clone();
let marker_theme = theme.clone();
diff = diff
.gutter_markers(markers)
.render_gutter_marker(move |marker, _, _| {
let position = marker.position();
let range = ranges.iter().find(|range| {
range.path() == position.path()
&& range.side() == position.side()
&& range.start() == position.line()
});
let intent = range.map(|range| DiffIntent {
action: action.id.clone(),
path: range.path().clone(),
range: Some(range.clone()),
});
let handler = handler.clone();
let label = action.label.clone();
let theme = marker_theme.clone();
Button::new(marker.id().clone())
.aria_label(label.clone())
.style_with(move |button| {
let label = label.clone();
super::button::style_button(
button,
false,
ButtonVariant::Ghost,
ButtonSize::IconXs,
&theme,
)
.tooltip(move |_, cx| super::tooltip::text_tooltip(label.clone(), cx))
})
.when_some(action.icon, |button, icon| {
button.child(
lucide(icon)
.size(marker_theme.spacing.unit * 3.5_f32)
.text_color(marker_theme.colors.foreground),
)
})
.on_click(move |_, window, cx| {
if let (Some(handler), Some(intent)) = (&handler, &intent) {
handler(intent, window, cx);
}
})
});
}
if !self.read_only && !self.file_actions.is_empty() {
let actions = Rc::new(self.file_actions);
let handler = self.on_intent;
let header_theme = theme.clone();
diff = diff.render_header_suffix(move |file, _, _| {
let mut row = div().flex().gap(header_theme.spacing.unit);
for action in actions.iter() {
let handler = handler.clone();
let intent = DiffIntent {
action: action.id.clone(),
path: file.path().clone(),
range: None,
};
row = row.child(action_button(
ElementId::Name(format!("diff.file.{}.{}", file.path(), action.id).into()),
action,
&header_theme,
move |window, cx| {
if let Some(handler) = &handler {
handler(&intent, window, cx);
}
},
));
}
row
});
}
let mut root = div()
.size_full()
.min_w_0()
.min_h_0()
.overflow_hidden()
.rounded(theme.radius.md)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.background)
.child(diff.size_full());
root.style().refine(&self.style);
root
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui_kit::{AppContext as _, Context, Render, TestAppContext, VisualTestContext};
const PATCH: &str = "diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,5 @@
fn main() {
- println!(\"old\");
+ println!(\"new\");
+ println!(\"more\");
}
";
#[test]
fn parses_a_git_patch() {
let files = DiffFile::parse(PATCH).unwrap();
assert_eq!(files.len(), 1);
assert_eq!(files[0].path().as_ref(), "src/lib.rs");
assert_eq!((files[0].additions(), files[0].deletions()), (2, 1));
}
struct Probe {
state: Entity<DiffState>,
read_only: bool,
intents: Rc<std::cell::RefCell<Vec<DiffIntent>>>,
}
impl Render for Probe {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size(gpui_kit::px(600.)).child(
DiffView::new("probe", &self.state)
.read_only(self.read_only)
.selection_actions([
DiffAction::new("stage", "Stage lines").icon(LucideIcon::Plus)
])
.file_actions([DiffAction::new("discard", "Discard").destructive(true)])
.hunk_action(
DiffAction::new("stage-hunk", "Stage hunk").icon(LucideIcon::Plus),
[DiffLineRange::new("src/lib.rs", DiffSide::Original, 2, 2)
.with_end_side(DiffSide::Modified)],
)
.header_visible(true)
.on_intent({
let intents = self.intents.clone();
move |intent, _, _| intents.borrow_mut().push(intent.clone())
}),
)
}
}
#[gpui_kit::test]
fn the_selection_strip_follows_the_selection_and_read_only_hides_it(cx: &mut TestAppContext) {
cx.update(super::super::theme::init);
let state = cx.new(|cx| DiffState::new(DiffFile::parse(PATCH).unwrap(), cx));
state.read_with(cx, |state, _| {
assert!(
selection_anchor(state, false, true).is_none(),
"nothing selected"
);
});
let range = DiffLineRange::new("src/lib.rs", DiffSide::Modified, 2, 3);
state.update(cx, |state, cx| {
state.set_selected_lines(Some(range.clone()), cx)
});
state.read_with(cx, |state, _| {
let (selected, end) = selection_anchor(state, false, true).unwrap();
assert_eq!(selected, range);
assert_eq!(end.line(), 3);
assert!(selection_anchor(state, true, true).is_none(), "read-only");
assert!(
selection_anchor(state, false, false).is_none(),
"no actions"
);
});
// One state per view: views of one state with and without hunk
// buttons lay it out differently, so each would re-measure it for
// the other on every frame.
for read_only in [false, true] {
let probe_state = cx.new(|cx| DiffState::new(DiffFile::parse(PATCH).unwrap(), cx));
probe_state.update(cx, |state, cx| {
state.set_selected_lines(Some(range.clone()), cx);
});
let window = cx.add_window(move |_, _| Probe {
state: probe_state,
read_only,
intents: Rc::default(),
});
let mut cx = VisualTestContext::from_window(window.into(), cx);
for mode in [
super::super::theme::ThemeMode::Light,
super::super::theme::ThemeMode::Dark,
] {
cx.update(|_, cx| UiTheme::switch(cx, mode));
cx.update(|window, cx| window.draw(cx).clear(cx));
}
}
}
}
Platform notes
A native desktop composition, not a shadcn port. Implementation:
crates/ui/registry/diff/diff.rs, wrapping GPUI Kit 0.9.1's diff.
GPUI Kit supplies the viewer: Git patch parsing (DiffFile::parse), one
retained DiffState for any number of files, virtualized rows, unified and
side-by-side layouts (DiffState::set_mode) with synchronized scrolling,
syntax highlighting, inline change highlighting, hunk headers, collapsed
unchanged regions, per-file collapse, line-number selection with the pointer
and Shift+Up/Down, text copy, keyboard scrolling, and conflict decorations.
It reads gpuicn's theme through the synced Kit theme, so colors, radius and
the mono font follow the app theme.
gpuicn's DiffView adds:
- Nova defaults: a bordered rounded surface, change bars instead of +/− signs, line-number hover, the theme's mono font.
- Selection actions. When lines are selected, an action strip appears under
the last selected line with the caller's
DiffActionbuttons. A press clears the selection and reports aDiffIntentwith the action ID, the file path and the selectedDiffLineRange(side and 1-based lines). - File actions in every file header, reported with
range: None. read_only(true)for commit and review diffs: selection and copy still work, no action is shown and no intent is reported.
The application owns everything Git: producing the patch, mapping a range to
a hunk or lines, building and applying partial patches, and confirming
destructive actions. Every re-parse should go through set_files, which
keeps scroll position and collapse state where paths survive.
Limits
- Kit's selection is one contiguous range per file side; multiple disjoint ranges are not supported.
- Kit renders rows itself, so per-row accessibility follows Kit's diff.
- Native macOS pointer, VoiceOver and very large patch measurements are still to be recorded.