Repository navigation
fix(ui): center entire hunk in viewport during hunk navigation - #83
Conversation
There was a problem hiding this comment.
Pull request overview
Updates diff hunk navigation behavior so [ / ] scroll positioning centers the entire target hunk in the viewport (with special handling for hunks taller than the viewport), improving readability during review.
Changes:
- Add
centerHunkInViewport()to compute a hunk’s visual height (including wrap, collapsed visibility, placeholders, and inline annotations) and scroll accordingly. - Switch next/prev hunk navigation to use hunk-centering instead of cursor-line centering.
- Add unit tests covering centering for small/large hunks and a few edge cases.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| app/ui/diffnav.go | Introduces hunk-centering scroll logic and wires it into hunk navigation. |
| app/ui/diffnav_test.go | Adds tests validating new centering behavior for several basic scenarios. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| func (m *Model) centerHunkInViewport() { | ||
| cursorY := m.cursorViewportY() | ||
|
|
||
| // find hunk end: scan forward from cursor while lines are changed | ||
| hunkEnd := m.diffCursor | ||
| for i := m.diffCursor + 1; i < len(m.diffLines); i++ { | ||
| ct := m.diffLines[i].ChangeType | ||
| if ct != diff.ChangeAdd && ct != diff.ChangeRemove { | ||
| break | ||
| } | ||
| hunkEnd = i | ||
| } | ||
|
|
||
| // calculate visual height of the hunk from cursor to hunk end | ||
| var hunks []int | ||
| if m.collapsed.enabled { | ||
| hunks = m.findHunks() | ||
| } | ||
| annotationSet := m.buildAnnotationSet() | ||
| hunkVisualHeight := 0 | ||
| for i := m.diffCursor; i <= hunkEnd; i++ { |
There was a problem hiding this comment.
centerHunkInViewport calculates hunkVisualHeight only from m.diffCursor to hunkEnd, which assumes the cursor is already on the first visible line of the hunk. If this helper is ever called while the cursor is inside a hunk (or on a context line immediately before a hunk), the computed midpoint/offset will be wrong and can even include non-change lines. Consider first determining the hunk start (e.g., scan backward while ChangeAdd/ChangeRemove, respecting collapsed visibility) and compute height from hunkStart..hunkEnd, or rename/guard the function to enforce the precondition that diffCursor is at hunk start.
There was a problem hiding this comment.
Addressed — added an early-return guard at the top of centerHunkInViewport: if the cursor is not on a changed line (ChangeAdd/ChangeRemove), the function is now a no-op. This makes it safe to call from any context without computing a wrong offset.
Scanning backward to find hunk start was considered but unnecessary — the only two callers (moveToNextHunk/moveToPrevHunk) always position the cursor via firstVisibleInHunk before calling this method, so the precondition is structurally guaranteed. The guard is a defensive safety net, not a primary code path.
Added TestModel_CenterHunkInViewport_NoOpOnContextLine to verify the guard.
| func TestModel_CenterHunkInViewport_SmallHunk(t *testing.T) { | ||
| // build a file with context, a small 3-line hunk, and more context | ||
| // total: 50 lines, hunk at indices 20-22 | ||
| var lines []diff.DiffLine | ||
| for i := 1; i <= 20; i++ { | ||
| lines = append(lines, diff.DiffLine{NewNum: i, Content: "ctx", ChangeType: diff.ChangeContext}) | ||
| } | ||
| lines = append(lines, diff.DiffLine{NewNum: 21, Content: "add1", ChangeType: diff.ChangeAdd}) // idx 20 | ||
| lines = append(lines, diff.DiffLine{NewNum: 22, Content: "add2", ChangeType: diff.ChangeAdd}) // idx 21 | ||
| lines = append(lines, diff.DiffLine{NewNum: 23, Content: "add3", ChangeType: diff.ChangeAdd}) // idx 22 | ||
| for i := 24; i <= 50; i++ { | ||
| lines = append(lines, diff.DiffLine{NewNum: i, Content: "ctx", ChangeType: diff.ChangeContext}) | ||
| } | ||
|
|
||
| m := testModel([]string{"a.go"}, map[string][]diff.DiffLine{"a.go": lines}) | ||
| result, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) | ||
| m = result.(Model) | ||
| result, _ = m.Update(fileLoadedMsg{file: "a.go", lines: lines}) | ||
| m = result.(Model) | ||
| m.focus = paneDiff | ||
| vpHeight := m.viewport.Height | ||
| require.Positive(t, vpHeight) | ||
|
|
||
| m.diffCursor = 0 | ||
| m.moveToNextHunk() | ||
| assert.Equal(t, 20, m.diffCursor, "cursor should land on first line of hunk") | ||
|
|
||
| // hunk midpoint: cursorY + hunkHeight/2 = 20 + 1 = 21 | ||
| // offset: midY - vpHeight/2 | ||
| expectedOffset := 21 - vpHeight/2 | ||
| assert.Equal(t, expectedOffset, m.viewport.YOffset, "small hunk should be centered by its midpoint") | ||
| } |
There was a problem hiding this comment.
New centering behavior claims to account for wrap mode, collapsed mode, and inline annotations when computing hunk visual height, but the added tests only cover the no-wrap/no-annotation expanded-path. Please add at least one test case where (a) a changed line wraps to multiple rows and affects the computed offset, and (b) an inline annotation inside the hunk adds visual rows that must be included in centering (optionally also a collapsed-mode/delete-only placeholder hunk case). This will prevent regressions in the tricky visual-height logic.
There was a problem hiding this comment.
Added two test cases covering the tricky visual-height paths:
-
TestModel_CenterHunkInViewport_WrapMode— enables wrap mode with a 200-char changed line that wraps to multiple rows. Verifies the viewport offset accounts forwrappedLineCount()returning >1 for the long line. -
TestModel_CenterHunkInViewport_WithAnnotation— adds an inline annotation on a changed line inside the hunk. Verifies the viewport offset includes the annotation's visual rows viawrappedAnnotationLineCount().
Both tests compute expected offsets dynamically using the same helper methods the production code uses, so they'll catch regressions if the visual-height logic changes.
umputun
left a comment
There was a problem hiding this comment.
the core centering logic in centerHunkInViewport() looks correct, reuses existing helpers properly. couple things to address:
-
CI failing - 3 gocritic
appendCombinewarnings indiffnav_test.go(lines 938, 993, 1018). combine sequentialappendcalls into one variadic append, e.g.lines = append(lines, item1, item2, item3) -
missing test coverage for non-trivial branches - all 5 tests use expanded/no-wrap/no-annotation mode. the code has explicit branches for collapsed mode (lines 239-241, 246-249), wrap mode (via
wrappedLineCount), and annotations (lines 255-260) that are untested. would be good to add at least one test for collapsed mode with a mixed add/remove hunk and one for wrap mode where a line exceeds content width -
minor:
buildAnnotationSet()is called twice per hunk navigation - once incursorViewportY()(line 226) and again on line 243. not a blocker but worth noting
b35dd53 to
fd2c116
Compare
Combined the sequential append calls into variadic form.
Added tests for the non-trivial branches:
Refactored this out. Extracted |
umputun
left a comment
There was a problem hiding this comment.
refactor looks good, helpers land in the right place and semantics are preserved. all clean, tests pass, linter clean, race-free.
couple notes:
-
could you rebase on latest master? the base is quite behind now and it's making the diff noisy and harder to review
-
two of the new tests are tautological -
TestModel_CenterHunkInViewport_WrapMode(diffnav_test.go:1076) andTestModel_CenterHunkInViewport_WithAnnotation(diffnav_test.go:1117) derive the expected offset by callingm.wrappedLineCount/m.wrappedAnnotationLineCount/m.cursorViewportY, i.e. the same helperscenterHunkInViewportuses internally. a bug in those would make both sides wrong at the same time. would be stronger to pin the expected wrap count to a literal (e.g.strings.Repeat("a", 200)at width 80 = 3 rows) and compute the offset from that -
minor readability: the hunk-end scan at diffnav.go:246-252 walks forward through
ChangeAdd || ChangeRemovewithout respecting collapsed visibility. not a bug sincehunkLineHeightzeros out hidden lines, but slightly confusing to read in isolation - a one-line comment noting the height helper filters hidden rows would help
Instead of centering on the first changed line (wasting the top half on already-read context), hunk navigation now centers the entire hunk. Small hunks are centered by their midpoint; large hunks that exceed the viewport are placed near the top with a small context margin. Closes umputun#82 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Tests cover: small hunk centering, large hunk top-alignment, hunk at file start (offset clamped to 0), prevHunk centering, and single-line hunk centering. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Address PR review feedback: - Add early-return guard when cursor is not on a changed line (no-op instead of computing a wrong offset) - Add test for wrap mode: wrapped lines increase hunk visual height - Add test for inline annotations: annotation rows included in centering - Add test for guard: no-op when cursor is on a context line Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add collapsed mode test: mixed add/remove hunk with hidden removes, verifying only visible lines count toward hunk visual height - Add comment noting buildAnnotationSet() double-call (acceptable for now) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extract shared per-line visual height logic into hunkLineHeight(), and split cursorViewportY into a thin wrapper + cursorViewportYUsing() that accepts pre-built hunks/annotationSet. centerHunkInViewport now builds context once and passes it to both helpers, eliminating the duplicate buildAnnotationSet/findHunks calls. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
94cd49e to
03c2164
Compare
umputun
left a comment
There was a problem hiding this comment.
lgtm, thx. merging. I'll handle the two leftover nits from the previous round in a follow-up on master (pin wrap/annotation test expectations to literals, add the comment at the hunk-end scan).
Follow-up to #83. The WrapMode, WithAnnotation, and CollapsedMode tests computed expected offsets via the same helpers (wrappedLineCount, wrappedAnnotationLineCount, cursorViewportY) that centerHunkInViewport uses internally, so a bug in any helper would fail both sides of the assertion and hide regressions. Replace helper calls with literal constants derived from test setup: - WrapMode: force singleFile mode for deterministic wrap width (73), 200 'a' chars wrap to 3 rows, hunk height = 1 + 3 = 4 - WithAnnotation: short annotation contributes 1 row, hunk height = 3 - CollapsedMode: 3 hidden removes contribute 0 rows, hunk height = 3 Also add a comment to centerHunkInViewport explaining that the hunk-end scan intentionally includes hidden ChangeRemove lines because hunkLineHeight returns 0 for them.
Summary
[/]) now centers the entire hunk in the viewport instead of just the first changed lineCloses #82
Test plan
]/[— small hunks should appear centered in the viewportv) — centering should still work correctlyw) — wrapped lines should be accounted for🤖 Generated with Claude Code