Skip to content

feat: add Ctrl+D & Ctrl+U keys for scroll#42

Merged
plutov merged 2 commits into
plutov:mainfrom
olexsmir:ctrl-d-and-u
Sep 24, 2025
Merged

feat: add Ctrl+D & Ctrl+U keys for scroll#42
plutov merged 2 commits into
plutov:mainfrom
olexsmir:ctrl-d-and-u

Conversation

@olexsmir

@olexsmir olexsmir commented Sep 23, 2025

Copy link
Copy Markdown
Contributor

The number of lines to scroll with Ctrl-D and Ctrl-U is the default vim's value of scroll option.

Summary by CodeRabbit

  • New Features

    • Added half-page scrolling with keyboard shortcuts: Ctrl-D (down) and Ctrl-U (up) across all lists.
  • Bug Fixes

    • Consistent navigation across views; prevents cursor overshoot and keeps selection visible when paging.
    • Down/j navigation refined to maintain selection visibility.
    • Improved “G” behavior to reliably jump to the true end of the list.
  • Documentation

    • Help modal updated to include Ctrl-U and Ctrl-D shortcuts for half-page scrolling.

@coderabbitai

coderabbitai Bot commented Sep 23, 2025

Copy link
Copy Markdown

Walkthrough

Centralizes cursor-bound calculations via a new Model.getMaxItems() and standardizes half-screen paging with an unexported constant scrollHalfScreenLines. Rewires navigation handlers (down, Ctrl‑D, Ctrl‑U, G) to clamp cursor with getMaxItems() and call ensureCursorVisible. Adds help entries for "Ctrl-U" and "Ctrl-D".

Changes

Cohort / File(s) Summary of Changes
Navigation bounds & paging refactor
model.go
Added unexported constant scrollHalfScreenLines and Model.getMaxItems() int. Reworked down/j navigation, Ctrl‑D, Ctrl‑U, and G handlers to use getMaxItems() for clamping, advance/retreat by half-screen increments, and call ensureCursorVisible.
Help modal updates
view.go
Inserted help entries for Ctrl-U and Ctrl-D describing half-screen scrolling; no other public API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Model
  participant View

  rect rgba(230,240,255,0.6)
  note over User,Model: Keypress (j / down / Ctrl-D / Ctrl-U / G)
  User->>Model: key event
  Model->>Model: getMaxItems()
  Model->>Model: compute new cursor (clamp to [0, max])
  Model->>Model: ensureCursorVisible()
  Model->>View: render updated view
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • plutov

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title concisely and accurately summarizes the primary change—adding Ctrl+D and Ctrl+U scroll keybindings—and is specific and clear without extraneous detail while using the conventional "feat:" prefix.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94f127e and 67cb5f1.

📒 Files selected for processing (2)
  • model.go (3 hunks)
  • view.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • view.go
🔇 Additional comments (6)
model.go (6)

120-131: Function implementation is correct.

The getMaxItems() function properly computes the maximum valid cursor index for each view mode by returning len(slice) - 1, which correctly handles the zero-based indexing used throughout the codebase.


306-312: Implementation uses new centralized logic correctly.

The refactor to use getMaxItems() instead of inline per-view calculations is consistent and appropriate.


314-326: Potential negative cursor assignment still exists.

Despite the past review discussion, the issue remains: when any list is empty, getMaxItems() returns -1, and if newCursorPos > maxItems (which is true when maxItems = -1), the code assigns m.cursor = maxItems, setting the cursor to -1. This contradicts the developer's claim that the function returns 0 for empty lists.

Apply the guard as suggested in the previous review:

-            maxItems := m.getMaxItems()
-            newCursorPos := m.cursor + scrollHalfScreenLines
-
-            if newCursorPos > maxItems {
-                m.cursor = maxItems
-            } else {
-                m.cursor += scrollHalfScreenLines
-            }
-
-            m.ensureCursorVisible()
+            maxItems := m.getMaxItems()
+            if maxItems >= 0 {
+                halfLines := max(1, calculateContentHeight(m.height)/2)
+                if m.cursor+halfLines > maxItems {
+                    m.cursor = maxItems
+                } else {
+                    m.cursor += halfLines
+                }
+                m.ensureCursorVisible()
+            }

328-338: Implementation is correct and well-structured.

The Ctrl+U implementation properly calculates dynamic half-screen scrolling and handles boundary conditions by clamping the cursor to 0 when scrolling would go negative.


340-347: Guard against empty lists is appropriate.

The check if maxItems >= 0 properly prevents cursor assignment when lists are empty, avoiding the negative cursor issue.


21-21: Use dynamic half-screen calculation instead of hardcoded constant.

The hardcoded value of 21 lines doesn't adapt to different terminal sizes or viewport dimensions. This could result in inconsistent scrolling behavior across different screen sizes. The existing calculateContentHeight(m.height) function should be used to compute half-screen scrolling dynamically.

Replace the constant with a dynamic calculation:

-const scrollHalfScreenLines = 21

And update the usage sites to use max(1, calculateContentHeight(m.height)/2) instead.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@olexsmir olexsmir marked this pull request as ready for review September 23, 2025 13:20
@olexsmir

Copy link
Copy Markdown
Contributor Author

@coderabbitai help

@coderabbitai

coderabbitai Bot commented Sep 23, 2025

Copy link
Copy Markdown

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
    • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
    • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit configuration file (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@olexsmir

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Sep 23, 2025

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
model.go (3)

21-22: Avoid hardcoding 21; compute half-screen dynamically.

Vim’s default scroll is half the window, not a fixed count. Use calculateContentHeight(m.height)/2 at runtime, and drop this constant.

Apply this diff to remove the constant:

-const scrollHalfScreenLines = 21

120-131: Return -1 in default branch to reflect “no items.”

More precise contract; prevents accidental non-negative values leaking into callers if mode expands in future.

  default:
-    return 0
+    return -1

328-338: Compute half-screen dynamically for ctrl+u and simplify clamping.

Aligns with Vim semantics and removes duplication.

-            newCursorPos := m.cursor - scrollHalfScreenLines
-            if newCursorPos < 0 {
-                m.cursor = 0
-                m.ensureCursorVisible()
-            } else {
-                m.cursor -= scrollHalfScreenLines
-                m.ensureCursorVisible()
-            }
+            halfLines := max(1, calculateContentHeight(m.height)/2)
+            if m.cursor < halfLines {
+                m.cursor = 0
+            } else {
+                m.cursor -= halfLines
+            }
+            m.ensureCursorVisible()
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 139b1ca and 2eb9353.

📒 Files selected for processing (1)
  • model.go (3 hunks)
🔇 Additional comments (2)
model.go (2)

308-313: LGTM: unified max bound check for down/j.

Clean bound check via getMaxItems() and ensureCursorVisible() after change.


340-347: LGTM: “G” clamps to last item via getMaxItems().

Good guard on empty lists (>=0) and consistent ensureCursorVisible().

Comment thread model.go

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
view.go (1)

389-390: Use Ctrl+U/Ctrl+D notation to match existing style

Elsewhere you use "Ctrl+C" with a plus. Keep key notation consistent.

-        {"Ctrl-U", "Scroll up by half a screen"},
-        {"Ctrl-D", "Scroll down by half a screen"},
+        {"Ctrl+U", "Scroll up by half a screen"},
+        {"Ctrl+D", "Scroll down by half a screen"},
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2eb9353 and e54fb1d.

📒 Files selected for processing (1)
  • view.go (1 hunks)

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
view.go (1)

389-390: Use “Ctrl+U”/“Ctrl+D” for consistency with other shortcuts.

Align with “Ctrl+C” and “Shift+Tab/H”.

-        {"Ctrl-U", "Scroll up by half a screen"},
-        {"Ctrl-D", "Scroll down by half a screen"},
+        {"Ctrl+U", "Scroll up by half a screen"},
+        {"Ctrl+D", "Scroll down by half a screen"},
model.go (1)

21-22: Consider dynamic half-screen instead of a fixed 21 lines.

Viewport-aware scrolling feels more Vim-like on varying terminal sizes.

Example:

halfLines := max(1, calculateContentHeight(m.height)/2)

Use halfLines in ctrl+d/ctrl+u.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 139b1ca and e54fb1d.

📒 Files selected for processing (2)
  • model.go (3 hunks)
  • view.go (1 hunks)
🔇 Additional comments (6)
model.go (6)

120-132: LGTM: centralized max-index helper.

Good unification across modes.


308-312: LGTM: down-navigation now uses unified max boundary.


328-338: LGTM: ctrl+u clamps to zero safely.

No negative cursor risk here.


340-347: LGTM: G navigation clamps to valid end.


366-374: Harden bounds before indexing on Enter/Space.

Add non-negativity to prevent panic when cursor becomes -1.

-                if m.mode == viewEndpoints && m.cursor < len(m.endpoints) {
+                if m.mode == viewEndpoints && m.cursor >= 0 && m.cursor < len(m.endpoints) {
                     m.endpoints[m.cursor].folded = !m.endpoints[m.cursor].folded
-                } else if m.mode == viewComponents && m.cursor < len(m.components) {
+                } else if m.mode == viewComponents && m.cursor >= 0 && m.cursor < len(m.components) {
                     m.components[m.cursor].folded = !m.components[m.cursor].folded
-                } else if m.mode == viewWebhooks && m.cursor < len(m.webhooks) {
+                } else if m.mode == viewWebhooks && m.cursor >= 0 && m.cursor < len(m.webhooks) {
                     m.webhooks[m.cursor].folded = !m.webhooks[m.cursor].folded
                 }

314-326: Fix: ctrl+d can set cursor to -1 on empty lists → panic risk on Enter/Space.

Guard when maxItems < 0 and avoid assigning -1.

-        maxItems := m.getMaxItems()
-        newCursorPos := m.cursor + scrollHalfScreenLines
-
-        if newCursorPos > maxItems {
-            m.cursor = maxItems
-            m.ensureCursorVisible()
-        } else {
-            m.cursor += scrollHalfScreenLines
-            m.ensureCursorVisible()
-        }
+        maxItems := m.getMaxItems()
+        if maxItems >= 0 {
+            newCursorPos := m.cursor + scrollHalfScreenLines
+            if newCursorPos > maxItems {
+                m.cursor = maxItems
+            } else {
+                m.cursor += scrollHalfScreenLines
+            }
+            m.ensureCursorVisible()
+        }

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (3)
model.go (3)

21-21: Avoid hardcoded 21; compute half-screen dynamically

Vim’s default ‘scroll’ is half the current window height, not a fixed number. Compute the step from viewport height instead of using a magic constant.

Consider deriving the step at use sites with:

  • step := max(1, calculateContentHeight(m.height)/2)

120-131: getMaxItems() returns -1 on empty lists; default case should be consistent

Default currently returns 0, which is inconsistent with the -1 semantics for “no items”. Either make default -1 or ensure all call sites handle both -1 and 0 consistently.

Apply for consistency:

-    default:
-        return 0
+    default:
+        return -1

328-339: Make ctrl+u step dynamic (half the content height)

Mirror Vim semantics and adapt to the current viewport instead of a fixed step.

Apply:

 case "ctrl+u":
     if !m.showHelp {
-        newCursorPos := m.cursor - scrollHalfScreenLines
+        step := max(1, calculateContentHeight(m.height)/2)
+        newCursorPos := m.cursor - step
         if newCursorPos < 0 {
             m.cursor = 0
         } else {
-            m.cursor -= scrollHalfScreenLines
+            m.cursor -= step
         }
 
         m.ensureCursorVisible()
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e54fb1d and 94f127e.

📒 Files selected for processing (2)
  • model.go (3 hunks)
  • view.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • view.go
🔇 Additional comments (4)
model.go (4)

306-312: LGTM: ‘down’ now guards with getMaxItems()

Boundary check prevents overruns; cursor remains stable at end of list.


340-347: LGTM: ‘G’ clamps only when there are items

The maxItems >= 0 guard avoids negative cursor.


366-374: Prevent panic: add non‑negative cursor guard before indexing on Enter

If ctrl+d sets m.cursor = -1, the conditions here pass (−1 < len(...)) and indexing panics. Require m.cursor >= 0 at each branch.

Apply:

-                if m.mode == viewEndpoints && m.cursor < len(m.endpoints) {
+                if m.mode == viewEndpoints && m.cursor >= 0 && m.cursor < len(m.endpoints) {
                     m.endpoints[m.cursor].folded = !m.endpoints[m.cursor].folded
-                } else if m.mode == viewComponents && m.cursor < len(m.components) {
+                } else if m.mode == viewComponents && m.cursor >= 0 && m.cursor < len(m.components) {
                     m.components[m.cursor].folded = !m.components[m.cursor].folded
-                } else if m.mode == viewWebhooks && m.cursor < len(m.webhooks) {
+                } else if m.mode == viewWebhooks && m.cursor >= 0 && m.cursor < len(m.webhooks) {
                     m.webhooks[m.cursor].folded = !m.webhooks[m.cursor].folded
                 }

314-327: Bug: ctrl+d can set cursor = -1 when list is empty

If getMaxItems() == -1, this path sets m.cursor = -1, leading to potential panics when indexing elsewhere (e.g., enter toggles). Guard against empty lists before clamping/moving.

Apply this minimal fix:

 case "ctrl+d":
     if !m.showHelp {
-        maxItems := m.getMaxItems()
-        newCursorPos := m.cursor + scrollHalfScreenLines
-
-        if newCursorPos > maxItems {
-            m.cursor = maxItems
-        } else {
-            m.cursor += scrollHalfScreenLines
-        }
-
-        m.ensureCursorVisible()
+        maxItems := m.getMaxItems()
+        if maxItems >= 0 {
+            newCursorPos := m.cursor + scrollHalfScreenLines
+            if newCursorPos > maxItems {
+                m.cursor = maxItems
+            } else {
+                m.cursor = newCursorPos
+            }
+            m.ensureCursorVisible()
+        }
     }

@plutov plutov 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.

Nice

@plutov plutov merged commit 6b049b6 into plutov:main Sep 24, 2025
3 checks passed
@olexsmir olexsmir deleted the ctrl-d-and-u branch September 24, 2025 09:37
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.

2 participants