Skip to content

fix(ui): center entire hunk in viewport during hunk navigation - #83

Merged
umputun merged 5 commits into
umputun:masterfrom
p4elkin:fix/center-hunk-in-viewport
Apr 11, 2026
Merged

umputun merged 5 commits into
umputun:masterfrom
p4elkin:fix/center-hunk-in-viewport

Conversation

@p4elkin

@p4elkin p4elkin commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Hunk navigation ([/]) now centers the entire hunk in the viewport instead of just the first changed line
  • Small hunks are centered by their midpoint; large hunks (taller than viewport) are placed near the top with a 2-line context margin
  • Accounts for wrap mode, collapsed mode, and inline annotations when calculating hunk visual height

Closes #82

Test plan

  • Navigate hunks with ]/[ — small hunks should appear centered in the viewport
  • Navigate to a large hunk (more lines than viewport height) — first line should appear near the top
  • Test in collapsed mode (v) — centering should still work correctly
  • Test in wrap mode (w) — wrapped lines should be accounted for
  • Cross-file hunk navigation should center on the target hunk in the new file

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/ui/diffnav.go
Comment on lines +225 to +245
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++ {

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.

@p4elkin p4elkin Apr 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/ui/diffnav_test.go
Comment on lines +931 to +962
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")
}

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 for wrappedLineCount() 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 via wrappedAnnotationLineCount().

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 umputun left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the core centering logic in centerHunkInViewport() looks correct, reuses existing helpers properly. couple things to address:

  1. CI failing - 3 gocritic appendCombine warnings in diffnav_test.go (lines 938, 993, 1018). combine sequential append calls into one variadic append, e.g. lines = append(lines, item1, item2, item3)

  2. 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

  3. minor: buildAnnotationSet() is called twice per hunk navigation - once in cursorViewportY() (line 226) and again on line 243. not a blocker but worth noting

@p4elkin
p4elkin force-pushed the fix/center-hunk-in-viewport branch from b35dd53 to fd2c116 Compare April 10, 2026 08:26
@p4elkin

p4elkin commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

the core centering logic in centerHunkInViewport() looks correct, reuses existing helpers properly. couple things to address:

  1. CI failing - 3 gocritic appendCombine warnings in diffnav_test.go (lines 938, 993, 1018). combine sequential append calls into one variadic append, e.g. lines = append(lines, item1, item2, item3)

Combined the sequential append calls into variadic form.

  1. 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

Added tests for the non-trivial branches:
- WrapMode — long line wrapping to multiple visual rows
- WithAnnotation — inline annotation adding rows to hunk height
- CollapsedMode — mixed add/remove hunk where removes are hidden
- NoOpOnContextLine — guard when cursor isn't on a changed line

  1. minor: buildAnnotationSet() is called twice per hunk navigation - once in cursorViewportY() (line 226) and again on line 243. not a blocker but worth noting

Refactored this out. Extracted hunkLineHeight() (shared per-line visual height helper) and cursorViewportYUsing(): accepts pre-built hunks/annotationSet. centerHunkInViewport now builds context once and passes it to both — no more duplicate buildAnnotationSet/findHunks calls.

@umputun umputun left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactor looks good, helpers land in the right place and semantics are preserved. all clean, tests pass, linter clean, race-free.

couple notes:

  1. could you rebase on latest master? the base is quite behind now and it's making the diff noisy and harder to review

  2. two of the new tests are tautological - TestModel_CenterHunkInViewport_WrapMode (diffnav_test.go:1076) and TestModel_CenterHunkInViewport_WithAnnotation (diffnav_test.go:1117) derive the expected offset by calling m.wrappedLineCount / m.wrappedAnnotationLineCount / m.cursorViewportY, i.e. the same helpers centerHunkInViewport uses 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

  3. minor readability: the hunk-end scan at diffnav.go:246-252 walks forward through ChangeAdd || ChangeRemove without respecting collapsed visibility. not a bug since hunkLineHeight zeros out hidden lines, but slightly confusing to read in isolation - a one-line comment noting the height helper filters hidden rows would help

magnolia-integration and others added 5 commits April 11, 2026 00:55
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]>
@p4elkin
p4elkin force-pushed the fix/center-hunk-in-viewport branch from 94cd49e to 03c2164 Compare April 10, 2026 22:00

@umputun umputun left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@umputun
umputun merged commit 135942f into umputun:master Apr 11, 2026
umputun added a commit that referenced this pull request Apr 11, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hunk navigation centers first line instead of entire hunk

4 participants