Skip to content

fix: fix upward arrow navigation in virtual scrolling#60

Merged
nyatinte merged 9 commits intomainfrom
fix/cursor-movement
Jul 29, 2025
Merged

fix: fix upward arrow navigation in virtual scrolling#60
nyatinte merged 9 commits intomainfrom
fix/cursor-movement

Conversation

@nyatinte
Copy link
Copy Markdown
Owner

@nyatinte nyatinte commented Jul 27, 2025

Overview

This PR fixes a bug in the virtual scrolling implementation where upward arrow key navigation would incorrectly jump between categories instead of treating category headers as regular list elements.

Changes

  • Fixed upward arrow navigation to properly move from files to their group headers before jumping to previous groups
  • Refactored navigation logic using ts-pattern for better code maintainability
  • Unified the navigation behavior between up and down arrow keys for consistency
  • Removed unused helper functions after refactoring

Implementation

The key fix involves ensuring that when navigating upward from the first file in a group, the selection moves to the group header first (same behavior as downward navigation) instead of jumping directly to the previous group.

Used ts-pattern to replace complex nested if-else chains with declarative pattern matching:

match(currentPosition)
  .with({ type: 'file', hasFileAbove: true }, () => {
    setCurrentFileIndex(prev => prev - 1);
  })
  .with({ type: 'file', isFirstInGroup: true }, () => {
    setIsGroupSelected(true);  // Key fix: move to group header first
  })
  // ... other patterns

Related

Summary by CodeRabbit

  • Refactor
    • Improved keyboard navigation for the file list, providing smoother and more predictable up and down arrow key behavior.
    • Enhanced navigation logic for moving between files and groups within the file list.
    • Optimized file list filtering and flattening for better search and display performance.
    • Added support for customizing viewport height in virtual scrolling during testing.

Fixed a bug where upward arrow key navigation would incorrectly jump between
categories instead of treating category headers as regular list elements.
Refactored navigation logic using ts-pattern for better code maintainability
and consistency between up/down arrow behaviors.
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 27, 2025

"""

Walkthrough

The refactor extracts filtering, flattening, and navigation logic from the FileList component into a new navigation-utils.ts module. Keyboard navigation handling for arrow keys is delegated to dedicated utility functions, centralizing navigation state calculations and simplifying the component's input handling. Additionally, a test was adjusted to fix viewport height for consistent virtual scrolling behavior. Two test cases in sub-agent-scanner.ts were updated to use recursive scanning and more flexible assertions.

Changes

File(s) Change Summary
FileList component
src/components/FileList/FileList.tsx
Removed inline filtering, flattening, and navigation logic; replaced with calls to new utility functions; extracted arrow key handlers to separate functions; added optional testViewportHeight prop passed to useVirtualScroll.
Navigation utilities module
src/components/FileList/navigation-utils.ts
Added new module with functions for filtering file groups, flattening groups, calculating navigation positions, handling arrow key navigation, and retrieving files; includes comprehensive in-source tests.
FileList test
src/components/FileList/FileList.test.tsx
Added testViewportHeight={10} prop to the "Virtual scrolling" test case to fix viewport height for stable test behavior.
Sub-agent scanner tests
src/sub-agent-scanner.ts
Changed scanSubAgents calls to use recursive: true; updated assertions to search results for expected agent by name and scope instead of fixed indexing and length checks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In fields of files where rabbits roam,
Navigation found a brand new home.
With utils to guide each up and down,
The code now wears a cleaner crown.
Hop along keys, no more to stray,
Smooth paths ahead, we leap and play! 🐰🎶
"""

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 eb818e3 and b10792a.

📒 Files selected for processing (1)
  • src/sub-agent-scanner.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: All TypeScript code must use 'type' instead of 'interface' for type definitions.
Regular (non-component) functions must be defined using arrow function syntax.
Avoid default exports except for page components.
Never use the 'any' type; it is strictly forbidden.
Avoid 'as' type assertions; use proper type guards instead.
Remove unused imports and exports immediately to keep dependencies clean.
All TypeScript code must pass with zero type errors (strict mode enforced).
All code must pass Biome lint/format checks with zero errors.
All code must have zero unused dependencies, exports, or types (enforced by Knip).
All code must use immutable design with 'readonly' properties throughout TypeScript code.
All optional properties in TypeScript must use 'exactOptionalPropertyTypes: true' (no '| undefined' on optional props).
Array access in TypeScript must account for 'noUncheckedIndexedAccess: true' (array access returns 'T | undefined').
All code paths in TypeScript functions must return a value ('noImplicitReturns: true').

Files:

  • src/sub-agent-scanner.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to src/_utils.ts : Tests for utility functions must be defined using the InSource Testing pattern (tests live alongside the source code in the same file).
Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to **/*.{ts,tsx} : Remove unused imports and exports immediately to keep dependencies clean.
src/sub-agent-scanner.ts (1)

Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to src/_utils.ts : Tests for utility functions must be defined using the InSource Testing pattern (tests live alongside the source code in the same file).

🔇 Additional comments (4)
src/sub-agent-scanner.ts (4)

96-96: LGTM: Recursive scanning improves test accuracy.

Enabling recursive scanning ensures the test properly finds sub-agent files in nested directory structures, making it more representative of real-world usage.


99-107: Excellent improvement in test robustness.

The refactored assertions are much more reliable:

  • Searches for the specific agent by name and scope instead of assuming array order
  • Uses proper TypeScript optional chaining with null checks
  • Tests individual properties granularly for better failure diagnostics

This change eliminates brittleness from array ordering assumptions.


133-133: LGTM: Consistent with first test case.

Enabling recursive scanning maintains consistency between test cases and ensures proper file discovery in nested directory structures.


136-144: Consistent improvement in test reliability.

The refactored assertions mirror the improvements in the first test case:

  • Order-independent agent lookup by name and scope
  • Proper validation of error handling behavior (undefined description/tools for invalid frontmatter)
  • Consistent use of TypeScript optional chaining

Both test cases now follow the same robust pattern.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/cursor-movement

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
🪧 Tips

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR 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 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 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 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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @nyatinte, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

I've addressed a bug in the virtual scrolling implementation where upward arrow key navigation would incorrectly jump between categories. This PR ensures a smoother user experience by correctly handling transitions between files and group headers, and I've also refactored the navigation logic for better maintainability and consistency.

Highlights

  • Fixed Upward Arrow Navigation: The upward arrow navigation in the virtual scrolling component now correctly moves from files to their group headers before transitioning to previous groups, ensuring a more intuitive user experience.
  • Refactored Navigation Logic: The existing navigation logic has been refactored to utilize the "ts-pattern" library, replacing complex nested if-else chains with a more declarative and maintainable pattern matching approach.
  • Unified Navigation Behavior: The behavior for both up and down arrow key navigation has been unified, providing consistent movement within the file list.
  • Removed Unused Helper Functions: Several helper functions that became redundant after the navigation logic refactoring have been removed, cleaning up the codebase.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Jul 27, 2025

Open in StackBlitz

npm i https://pkg.pr.new/nyatinte/ccexp@60

commit: b10792a

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great improvement, successfully fixing the upward arrow key navigation in the virtual scrolling list. The refactoring of the navigation logic using ts-pattern has significantly enhanced code readability and maintainability by replacing complex conditional chains with a declarative pattern matching approach. My review includes one suggestion to further simplify the new handleUpArrow function by removing a redundant check, which is possible thanks to the guarantees provided by the pattern matching.

Comment thread src/components/FileList/FileList.tsx Outdated
- Create navigation-utils.ts with pure functions for file list navigation
- Extract filterFileGroups for search filtering logic
- Extract flattenFileGroups for hierarchy flattening
- Extract navigation position calculation and arrow key handling
- Add comprehensive InSource tests for all extracted functions
- Improve code maintainability and testability
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59f4c1b and 1dffd60.

📒 Files selected for processing (2)
  • src/components/FileList/FileList.tsx (4 hunks)
  • src/components/FileList/navigation-utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/FileList/FileList.tsx
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: All TypeScript code must use 'type' instead of 'interface' for type definitions.
Regular (non-component) functions must be defined using arrow function syntax.
Avoid default exports except for page components.
Never use the 'any' type; it is strictly forbidden.
Avoid 'as' type assertions; use proper type guards instead.
Remove unused imports and exports immediately to keep dependencies clean.
All TypeScript code must pass with zero type errors (strict mode enforced).
All code must pass Biome lint/format checks with zero errors.
All code must have zero unused dependencies, exports, or types (enforced by Knip).
All code must use immutable design with 'readonly' properties throughout TypeScript code.
All optional properties in TypeScript must use 'exactOptionalPropertyTypes: true' (no '| undefined' on optional props).
Array access in TypeScript must account for 'noUncheckedIndexedAccess: true' (array access returns 'T | undefined').
All code paths in TypeScript functions must return a value ('noImplicitReturns: true').

Files:

  • src/components/FileList/navigation-utils.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to **/*.{ts,tsx} : Remove unused imports and exports immediately to keep dependencies clean.
Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to **/*.{ts,tsx} : Avoid default exports except for page components.
src/components/FileList/navigation-utils.ts (1)

Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to src/_utils.ts : Tests for utility functions must be defined using the InSource Testing pattern (tests live alongside the source code in the same file).

🧬 Code Graph Analysis (1)
src/components/FileList/navigation-utils.ts (1)
src/_types.ts (2)
  • FlatItem (75-81)
  • ClaudeFileInfo (28-35)
🔇 Additional comments (7)
src/components/FileList/navigation-utils.ts (7)

7-25: Well-implemented filtering logic with proper immutability

The function correctly handles immutability by creating new arrays and objects, and the case-insensitive search on both filename and full path provides good user experience.


30-41: Efficient flattening implementation

Good use of flatMap for performance and proper handling of expanded/collapsed states.


46-62: Well-structured navigation position type

Comprehensive type definition with proper readonly properties and appropriate nullable handling.


106-110: Clean result type definition

Simple and effective type with proper readonly properties.


115-166: Comprehensive upward navigation handling

The implementation correctly handles all navigation cases, including the fix for moving from first file to group header as mentioned in the PR objectives.


242-541: Excellent test coverage

Comprehensive in-source tests following the required pattern, with good coverage of edge cases and proper test data setup.


237-239: Ensure safe array access

Add explicit null check for array access:

-  const group = filteredGroups[currentGroupIndex];
-  if (!group || !group.isExpanded || group.files.length === 0) return null;
+  const group = filteredGroups[currentGroupIndex] ?? null;
+  if (group == null || !group.isExpanded || group.files.length === 0) return null;
⛔ Skipped due to learnings
Learnt from: CR
PR: nyatinte/ccexp#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-27T15:51:39.320Z
Learning: Applies to **/*.{ts,tsx} : Array access in TypeScript must account for 'noUncheckedIndexedAccess: true' (array access returns 'T | undefined').

Comment thread src/components/FileList/navigation-utils.ts Outdated
Comment thread src/components/FileList/navigation-utils.ts Outdated
nyatinte added 7 commits July 28, 2025 02:17
…mments

- Cache lowercase search query to avoid repeated conversions
- Remove verbose JSDoc comments that were redundant with function names
- Follow project's comment guidelines (only keep 'why' comments)
…ssary comments

- Use es-toolkit/compat's filter function for better performance
- Cache file path toLowerCase to avoid repeated conversions
- Remove redundant inline comments that were self-explanatory
- Follow project's comment guidelines (only keep 'why' comments)
Set consistent terminal height (24 rows) in the test to ensure predictable
viewport calculations across different environments. The test was failing
in CI due to different terminal dimensions affecting virtual scroll behavior.
- Add nullish coalescing for array access in calculateNavigationPosition
- Fix potential undefined array access in handleDownArrowNavigation
- Update getFileAtPosition with proper null checks
- Ensures compliance with noUncheckedIndexedAccess TypeScript setting
- Filter test results by name and scope to avoid conflicts with user agents
- Change to recursive scanning to ensure nested test files are found
- Tests now properly isolate project-scoped agents from user-level ones
@nyatinte nyatinte merged commit e6cf83d into main Jul 29, 2025
9 checks passed
@nyatinte nyatinte deleted the fix/cursor-movement branch July 29, 2025 11:18
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.

1 participant