Skip to content

Commit 7a4d183

Browse files
authored
feat(tui): add diff hunk navigation (anomalyco#30935)
1 parent edbe228 commit 7a4d183

3 files changed

Lines changed: 205 additions & 16 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/config/keybind.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ export const Definitions = {
6565
diff_expand_all: keybind("E", "Expand all diff viewer folders"),
6666
diff_collapse: keybind("left", "Collapse diff viewer item"),
6767
diff_switch_focus: keybind("tab", "Switch diff viewer focus"),
68+
diff_next_hunk: keybind("]", "Jump to next diff hunk"),
69+
diff_previous_hunk: keybind("[", "Jump to previous diff hunk"),
6870
diff_next_file: keybind("n", "Jump to next diff file"),
6971
diff_previous_file: keybind("p", "Jump to previous diff file"),
7072
diff_toggle_file_tree: keybind("b", "Toggle diff viewer file tree"),
@@ -267,6 +269,8 @@ export const CommandMap = {
267269
diff_expand_all: "diff.expand_all",
268270
diff_collapse: "diff.collapse",
269271
diff_switch_focus: "diff.switch_focus",
272+
diff_next_hunk: "diff.next_hunk",
273+
diff_previous_hunk: "diff.previous_hunk",
270274
diff_next_file: "diff.next_file",
271275
diff_previous_file: "diff.previous_file",
272276
diff_toggle_file_tree: "diff.toggle_file_tree",

‎packages/opencode/src/cli/cmd/tui/feature-plugins/system/diff-viewer.tsx‎

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
/** @jsxImportSource @opentui/solid */
22
import type { TuiPlugin, TuiPluginApi, TuiRouteCurrent } from "@opencode-ai/plugin/tui"
33
import type { SnapshotFileDiff, VcsFileDiff } from "@opencode-ai/sdk/v2"
4-
import { TextAttributes, type BorderSides, type BoxRenderable, type ScrollBoxRenderable } from "@opentui/core"
4+
import {
5+
TextAttributes,
6+
type BorderSides,
7+
type BoxRenderable,
8+
type DiffRenderable,
9+
type ScrollBoxRenderable,
10+
} from "@opentui/core"
511
import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
612
import { useBindings, useCommandShortcut } from "@tui/keymap"
713
import { useTheme } from "@tui/context/theme"
@@ -40,6 +46,7 @@ const KV_VIEW = "diff_viewer_view"
4046
type DiffMode = "git" | "last-turn"
4147
type DiffViewerFocus = "patches" | "files"
4248
type DiffView = "split" | "unified"
49+
type SelectedHunk = { readonly fileIndex: number; readonly hunkIndex: number; readonly scrollTop: number }
4350

4451
type DiffFile = {
4552
readonly file: string
@@ -143,6 +150,8 @@ function DiffViewer(props: { api: TuiPluginApi }) {
143150
const patchFileIndexes = createMemo(() => orderedPatchFileIndexes(flattenFileTree(fileTree())))
144151
const focusRunner = (input: Record<DiffViewerFocus, () => void>) => () => input[focus()]()
145152
const switchFocusShortcut = useCommandShortcut("diff.switch_focus")
153+
const nextHunkShortcut = useCommandShortcut("diff.next_hunk")
154+
const previousHunkShortcut = useCommandShortcut("diff.previous_hunk")
146155
const nextFileShortcut = useCommandShortcut("diff.next_file")
147156
const previousFileShortcut = useCommandShortcut("diff.previous_file")
148157
const toggleFileTreeShortcut = useCommandShortcut("diff.toggle_file_tree")
@@ -153,6 +162,8 @@ function DiffViewer(props: { api: TuiPluginApi }) {
153162
const helpShortcut = useCommandShortcut("diff.help")
154163
let scroll: ScrollBoxRenderable | undefined
155164
const patchNodeByFileIndex = new Map<number, BoxRenderable>()
165+
const diffNodeByFileIndex = new Map<number, DiffRenderable>()
166+
const [selectedHunk, setSelectedHunk] = createSignal<SelectedHunk | undefined>()
156167
const [pendingPatchScrollFileIndex, setPendingPatchScrollFileIndex] = createSignal<number | undefined>()
157168
const [patchFillerHeight, setPatchFillerHeight] = createSignal(0)
158169

@@ -164,6 +175,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
164175
setLastHighlightedFileNode(undefined)
165176
setActivePatchFileIndex(undefined)
166177
setSelectedFileIndex(undefined)
178+
setSelectedHunk(undefined)
167179
setReviewedFileNames(new Set<string>())
168180
})
169181

@@ -189,6 +201,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
189201
const clearFileTreePatchState = () => {
190202
setHighlightedFileNode(undefined)
191203
setActivePatchFileIndex(undefined)
204+
setSelectedHunk(undefined)
192205
}
193206

194207
const scrollPatchNodeToTop = (patchNode: BoxRenderable) => {
@@ -227,6 +240,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
227240

228241
const jumpToFileIndex = (fileIndex: number | undefined) => {
229242
if (fileIndex === undefined) return
243+
setSelectedHunk(undefined)
230244
scrollToFileIndex(fileIndex)
231245
}
232246

@@ -248,6 +262,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
248262
}
249263

250264
const jumpRelativePatchFile = (offset: number) => {
265+
setSelectedHunk(undefined)
251266
const next = movePatchFileIndex(patchFileIndexes(), selectedFileIndex() ?? activePatchFileIndex(), offset)
252267
if (singlePatch()) {
253268
if (next === undefined) return
@@ -258,6 +273,38 @@ function DiffViewer(props: { api: TuiPluginApi }) {
258273
scrollToFileIndex(next)
259274
}
260275

276+
const jumpRelativeHunk = (offset: -1 | 1) => {
277+
const patchScroll = scroll
278+
if (!patchScroll) return
279+
const hunks = visiblePatchFiles()
280+
.flatMap((entry) => {
281+
const node = diffNodeByFileIndex.get(entry.fileIndex)
282+
if (!node || node.isDestroyed) return []
283+
const contentY = patchScroll.scrollTop + node.y - patchScroll.viewport.y
284+
return node.getHunkRowOffsets().map((row, hunkIndex) => ({
285+
fileIndex: entry.fileIndex,
286+
hunkIndex,
287+
contentY: contentY + row,
288+
}))
289+
})
290+
.sort((left, right) => left.contentY - right.contentY)
291+
const selected = selectedHunk()
292+
const selectedIndex =
293+
selected?.scrollTop === patchScroll.scrollTop
294+
? hunks.findIndex((hunk) => hunk.fileIndex === selected.fileIndex && hunk.hunkIndex === selected.hunkIndex)
295+
: -1
296+
const next =
297+
selectedIndex !== -1
298+
? hunks[selectedIndex + offset]
299+
: offset === 1
300+
? hunks.find((hunk) => hunk.contentY > patchScroll.scrollTop)
301+
: hunks.findLast((hunk) => hunk.contentY < patchScroll.scrollTop)
302+
if (!next) return
303+
selectPatchFile(next.fileIndex)
304+
patchScroll.scrollTo(next.contentY)
305+
setSelectedHunk({ fileIndex: next.fileIndex, hunkIndex: next.hunkIndex, scrollTop: patchScroll.scrollTop })
306+
}
307+
261308
const highlightedPatchFileIndex = () => fileRows().find((row) => row.id === highlightedFileNode())?.fileIndex
262309
const firstPatchFileIndex = () => fileRows().find((row) => row.fileIndex !== undefined)?.fileIndex
263310
const visiblePatchFiles = createMemo(() => {
@@ -504,6 +551,22 @@ function DiffViewer(props: { api: TuiPluginApi }) {
504551
patches() {},
505552
}),
506553
},
554+
{
555+
name: "diff.next_hunk",
556+
title: "Jump to next diff hunk",
557+
category: "VCS",
558+
run() {
559+
jumpRelativeHunk(1)
560+
},
561+
},
562+
{
563+
name: "diff.previous_hunk",
564+
title: "Jump to previous diff hunk",
565+
category: "VCS",
566+
run() {
567+
jumpRelativeHunk(-1)
568+
},
569+
},
507570
{
508571
name: "diff.next_file",
509572
title: "Jump to next diff file",
@@ -557,6 +620,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
557620
title: "Toggle single patch view",
558621
category: "VCS",
559622
run() {
623+
setSelectedHunk(undefined)
560624
if (!singlePatch()) {
561625
ensureHighlightedPatchFile()
562626
setSinglePatch(true)
@@ -592,6 +656,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
592656
category: "VCS",
593657
run() {
594658
if (!splitAvailable()) return
659+
setSelectedHunk(undefined)
595660
const next = view() === "split" ? "unified" : "split"
596661
setViewOverride(next)
597662
props.api.kv.set(KV_VIEW, next)
@@ -716,6 +781,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
716781
<Panel flexGrow={1} minHeight={0} border="none">
717782
<Separator axis="x" start={showFileTree() ? "edge-out" : undefined} />
718783
<scrollbox
784+
id="diff-viewer-patches"
719785
ref={(element: ScrollBoxRenderable) => (scroll = element)}
720786
flexGrow={1}
721787
minHeight={0}
@@ -755,6 +821,8 @@ function DiffViewer(props: { api: TuiPluginApi }) {
755821
{(patch) => (
756822
<box border={patchLeftBorder()} borderColor={theme().border}>
757823
<diff
824+
id={`diff-viewer-patch-${entry.fileIndex}`}
825+
ref={(element: DiffRenderable) => diffNodeByFileIndex.set(entry.fileIndex, element)}
758826
diff={patch()}
759827
view={view()}
760828
filetype={reviewed() ? PLAIN_TEXT_FILETYPE : filetype(entry.file.file)}
@@ -808,6 +876,20 @@ function DiffViewer(props: { api: TuiPluginApi }) {
808876
</text>
809877
)}
810878
</Show>
879+
<Show when={nextHunkShortcut()}>
880+
{(shortcut) => (
881+
<text fg={theme().text}>
882+
{shortcut()} <span style={{ fg: theme().textMuted }}>next hunk</span>
883+
</text>
884+
)}
885+
</Show>
886+
<Show when={previousHunkShortcut()}>
887+
{(shortcut) => (
888+
<text fg={theme().text}>
889+
{shortcut()} <span style={{ fg: theme().textMuted }}>previous hunk</span>
890+
</text>
891+
)}
892+
</Show>
811893
<Show when={previousFileShortcut()}>
812894
{(shortcut) => (
813895
<text fg={theme().text}>
@@ -855,6 +937,16 @@ function DiffViewerHelpDialog() {
855937
action: "Focus file tree",
856938
description: "Move keyboard focus between the file tree and patch pane",
857939
},
940+
{
941+
shortcut: useCommandShortcut("diff.next_hunk"),
942+
action: "Next hunk",
943+
description: "Jump to the next diff hunk",
944+
},
945+
{
946+
shortcut: useCommandShortcut("diff.previous_hunk"),
947+
action: "Previous hunk",
948+
description: "Jump to the previous diff hunk",
949+
},
858950
{
859951
shortcut: useCommandShortcut("diff.next_file"),
860952
action: "Next file",

‎packages/opencode/test/cli/tui/diff-viewer.test.tsx‎

Lines changed: 108 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,114 @@ import { expect, test } from "bun:test"
33
import path from "path"
44
import { mkdir } from "fs/promises"
55
import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
6+
import type { DiffRenderable, Renderable, ScrollBoxRenderable } from "@opentui/core"
67
import { testRender, useRenderer } from "@opentui/solid"
78
import { Global } from "@opencode-ai/core/global"
89
import type { TuiPluginApi, TuiPluginMeta, TuiRouteCurrent, TuiRouteDefinition } from "@opencode-ai/plugin/tui"
910
import type { Session } from "@opencode-ai/sdk/v2"
1011
import { KVProvider } from "../../../src/cli/cmd/tui/context/kv"
1112
import { ThemeProvider } from "../../../src/cli/cmd/tui/context/theme"
1213
import { TuiConfigProvider } from "../../../src/cli/cmd/tui/context/tui-config"
14+
import { TuiKeybind } from "../../../src/cli/cmd/tui/config/keybind"
1315
import { OpencodeKeymapProvider } from "../../../src/cli/cmd/tui/keymap"
1416
import diffViewerPlugin from "../../../src/cli/cmd/tui/feature-plugins/system/diff-viewer"
1517
import { createTuiPluginApi } from "../../fixture/tui-plugin"
1618
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
1719

1820
test("closing the diff viewer returns to the route it opened from", async () => {
19-
const startRoute: TuiRouteCurrent = { name: "session", params: { sessionID: "session-1" } }
21+
const viewer = await renderDiffViewer([])
22+
try {
23+
expect(viewer.current()).toEqual({
24+
name: "diff",
25+
params: { mode: "git", sessionID: "session-1", returnRoute: startRoute },
26+
})
27+
expect(viewer.vcsDiffInput()).toEqual({ directory: "/repo/session", mode: "git", context: 12 })
28+
29+
expect(viewer.commands.has("diff.close")).toBe(true)
30+
viewer.commands.get("diff.close")!.run?.({} as never)
31+
expect(viewer.current()).toEqual(startRoute)
32+
} finally {
33+
viewer.app.renderer.destroy()
34+
}
35+
})
36+
37+
test("brackets navigate diff hunks", async () => {
38+
const viewer = await renderDiffViewer(
39+
[
40+
{
41+
file: "src/file.ts",
42+
additions: 3,
43+
deletions: 3,
44+
status: "modified",
45+
patch: `--- a/src/file.ts
46+
+++ b/src/file.ts
47+
@@ -1,3 +1,3 @@
48+
const first = true
49+
-const oldFirst = true
50+
+const newFirst = true
51+
const afterFirst = true
52+
@@ -20,3 +20,3 @@
53+
const second = true
54+
-const oldSecond = true
55+
+const newSecond = true
56+
const afterSecond = true
57+
@@ -40,3 +40,3 @@
58+
const third = true
59+
-const oldThird = true
60+
+const newThird = true
61+
const afterThird = true`,
62+
},
63+
],
64+
12,
65+
)
66+
try {
67+
await viewer.app.waitForFrame((frame) => frame.includes("const first"))
68+
await viewer.app.waitFor(() => Boolean(findRenderable(viewer.app.renderer.root, "diff-viewer-patches")))
69+
await viewer.app.flush()
70+
const scroll = findRenderable(viewer.app.renderer.root, "diff-viewer-patches") as ScrollBoxRenderable
71+
const diff = findRenderable(viewer.app.renderer.root, "diff-viewer-patch-0") as DiffRenderable
72+
expect(diff.getHunkRowOffsets()).toEqual([0, 4, 8])
73+
const initial = scroll.scrollTop
74+
75+
expect(TuiKeybind.defaultValue("diff_next_hunk")).toBe("]")
76+
expect(TuiKeybind.defaultValue("diff_previous_hunk")).toBe("[")
77+
78+
viewer.commands.get("diff.next_hunk")!.run?.({} as never)
79+
await viewer.app.renderOnce()
80+
const first = scroll.scrollTop
81+
expect(first).toBeGreaterThan(initial)
82+
83+
viewer.commands.get("diff.next_hunk")!.run?.({} as never)
84+
await viewer.app.renderOnce()
85+
const second = scroll.scrollTop
86+
expect(second).toBeGreaterThan(first)
87+
88+
viewer.commands.get("diff.previous_hunk")!.run?.({} as never)
89+
await viewer.app.renderOnce()
90+
expect(scroll.scrollTop).toBe(first)
91+
92+
viewer.commands.get("diff.next_hunk")!.run?.({} as never)
93+
await viewer.app.renderOnce()
94+
expect(scroll.scrollTop).toBe(second)
95+
96+
scroll.scrollTo(initial)
97+
viewer.commands.get("diff.next_hunk")!.run?.({} as never)
98+
await viewer.app.renderOnce()
99+
expect(scroll.scrollTop).toBe(first)
100+
} finally {
101+
viewer.app.renderer.destroy()
102+
}
103+
})
104+
105+
async function renderDiffViewer(vcsDiff: unknown[], height = 20) {
20106
const commands = new Map<
21107
string,
22108
NonNullable<Parameters<TuiPluginApi["keymap"]["registerLayer"]>[0]["commands"]>[number]
23109
>()
24110
let current = startRoute
25111
let renderDiff: TuiRouteDefinition["render"] | undefined
26112
let vcsDiffInput: unknown
113+
const config = createTuiResolvedConfig()
27114
await mkdir(Global.Path.state, { recursive: true })
28115
await Bun.write(path.join(Global.Path.state, "kv.json"), "{}")
29116

@@ -41,7 +128,7 @@ test("closing the diff viewer returns to the route it opened from", async () =>
41128
vcs: {
42129
diff: async (input: unknown) => {
43130
vcsDiffInput = input
44-
return { data: [] }
131+
return { data: vcsDiff }
45132
},
46133
},
47134
session: { diff: async () => ({ data: [] }) },
@@ -73,7 +160,7 @@ test("closing the diff viewer returns to the route it opened from", async () =>
73160

74161
return (
75162
<OpencodeKeymapProvider keymap={keymap}>
76-
<TuiConfigProvider config={createTuiResolvedConfig()}>
163+
<TuiConfigProvider config={config}>
77164
<KVProvider>
78165
<ThemeProvider mode="dark">
79166
{renderDiff?.({ params: "params" in current ? current.params : undefined })}
@@ -84,19 +171,25 @@ test("closing the diff viewer returns to the route it opened from", async () =>
84171
)
85172
}
86173

87-
const app = await testRender(() => <Harness />, { width: 80, height: 20 })
88-
try {
89-
await waitForCommand(app, commands, "diff.close")
90-
expect(current).toEqual({ name: "diff", params: { mode: "git", sessionID: "session-1", returnRoute: startRoute } })
91-
expect(vcsDiffInput).toEqual({ directory: "/repo/session", mode: "git", context: 12 })
92-
93-
expect(commands.has("diff.close")).toBe(true)
94-
commands.get("diff.close")!.run?.({} as never)
95-
expect(current).toEqual(startRoute)
96-
} finally {
97-
app.renderer.destroy()
174+
const app = await testRender(() => <Harness />, { width: 80, height })
175+
await waitForCommand(app, commands, "diff.close")
176+
return {
177+
app,
178+
commands,
179+
current: () => current,
180+
vcsDiffInput: () => vcsDiffInput,
98181
}
99-
})
182+
}
183+
184+
const startRoute: TuiRouteCurrent = { name: "session", params: { sessionID: "session-1" } }
185+
186+
function findRenderable(root: Renderable, id: string): Renderable | undefined {
187+
if (root.id === id) return root
188+
return root
189+
.getChildren()
190+
.map((child) => findRenderable(child, id))
191+
.find(Boolean)
192+
}
100193

101194
const session = {
102195
id: "session-1",

0 commit comments

Comments
 (0)