Skip to content

feat: support smooth auto-scroll to active menu item #6102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2025

Conversation

anncwb
Copy link
Collaborator

@anncwb anncwb commented May 3, 2025

Description

close #5944

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features
    • Added an option for the menu to automatically scroll to the active item, improving navigation usability.
  • Refactor
    • Improved route navigation logic with enhanced error handling and centralized decision-making for opening links in new windows.
  • Bug Fixes
    • Ensured menu items are correctly displayed based on visibility settings.
  • Chores
    • Updated tests and internal logic to treat menu generation as a synchronous process.

Copy link

changeset-bot bot commented May 3, 2025

⚠️ No Changeset found

Latest commit: 5276b10

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented May 3, 2025

Walkthrough

This update introduces an automatic scroll-to-active-menu-item feature in the UI kit's menu component. It adds a new boolean prop scrollToActive to the menu, enabling automatic scrolling to the highlighted menu item when active, particularly in vertical and expanded menu modes. A new composable useMenuScroll is implemented to handle the DOM scrolling logic using scrollIntoView. The generateMenus utility is refactored to be synchronous, and related tests and usages are updated accordingly. Additional internal refactoring and error handling improvements are made in navigation helpers.

Changes

File(s) Change Summary
packages/@core/ui-kit/menu-ui/src/components/menu.vue, .../src/types.ts Added scrollToActive prop and logic to trigger scrolling to active menu item.
packages/@core/ui-kit/menu-ui/src/hooks/use-menu-scroll.ts New composable useMenuScroll for handling scroll-to-active logic with debounce and watcher.
packages/effects/layouts/src/basic/menu/menu.vue Enabled the scroll-to-active attribute on the Menu component in the layout.
packages/utils/src/helpers/generate-menus.ts, .../__tests__/generate-menus.test.ts Refactored generateMenus to be synchronous; updated all usages and tests to remove await.
packages/effects/access/src/accessible.ts Internal: Removed await from generateMenus call to match new synchronous signature.
packages/effects/layouts/src/basic/menu/use-navigation.ts Refactored route meta initialization, new window logic, and added error handling in navigation.
packages/@core/ui-kit/menu-ui/src/menu.vue Removed commented-out code for theme prop and event emits.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MenuComponent
    participant useMenuScroll
    participant DOM

    User->>MenuComponent: Set scrollToActive=true
    MenuComponent->>useMenuScroll: Initialize with activePath, enableScroll
    useMenuScroll->>DOM: Watch activePath, scroll to .is-active if enabled
    DOM-->>MenuComponent: Active menu item scrolled into view
Loading

Assessment against linked issues

Objective Addressed Explanation
Automatically scroll to the highlighted (active) menu item when menu is long (#5944)

Suggested reviewers

  • mynetfan
  • vince292007
  • jinmao88

Poem

A menu hops with joy anew,
Now scrolls to active—right on cue!
No more search, no more strife,
The highlight jumps into your life.
With every click and every view,
The rabbit cheers, "This one's for you!"
🐇✨


📜 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 17a18fc and 5276b10.

📒 Files selected for processing (9)
  • packages/@core/ui-kit/menu-ui/src/components/menu.vue (4 hunks)
  • packages/@core/ui-kit/menu-ui/src/hooks/use-menu-scroll.ts (1 hunks)
  • packages/@core/ui-kit/menu-ui/src/menu.vue (0 hunks)
  • packages/@core/ui-kit/menu-ui/src/types.ts (1 hunks)
  • packages/effects/access/src/accessible.ts (1 hunks)
  • packages/effects/layouts/src/basic/menu/menu.vue (1 hunks)
  • packages/effects/layouts/src/basic/menu/use-navigation.ts (1 hunks)
  • packages/utils/src/helpers/__tests__/generate-menus.test.ts (6 hunks)
  • packages/utils/src/helpers/generate-menus.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • packages/@core/ui-kit/menu-ui/src/menu.vue
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/effects/layouts/src/basic/menu/use-navigation.ts (2)
packages/@core/base/shared/src/utils/inference.ts (1)
  • isHttpUrl (157-157)
packages/@core/base/shared/src/utils/window.ts (2)
  • openWindow (37-37)
  • openRouteInNewWindow (37-37)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
🔇 Additional comments (32)
packages/utils/src/helpers/generate-menus.ts (8)

3-7: Enhanced type imports for better specificity.

The changes improve type definitions by explicitly importing specific types rather than using a broader import. This enhances type safety and makes dependencies clearer.


11-16: Updated JSDoc to reflect new parameter.

The documentation has been correctly updated to include the new router parameter in the function signature.


17-20: Function refactored from async to sync.

The function signature has been changed from asynchronous to synchronous, removing the Promise return type. This is a good optimization since the function doesn't perform any asynchronous operations.


27-28: Improved route path extraction with fallback.

Added a fallback using the nullish coalescing operator for cases where the route name isn't found in the finalRoutesMap, enhancing robustness.


30-35: Enhanced destructuring with proper type defaults.

The destructuring now includes default values for meta (properly typed as RouteMeta) and children, improving type safety and preventing potential null/undefined errors.


56-62: Improved parent-child relationship handling.

Added nullish coalescing for the parents array, ensuring that the parent-child relationship is properly maintained even when parent data is missing.


77-79: Simplified property assignments in return object.

The return object properties have been simplified and reordered for better readability. The show property now directly uses the inverse of meta.hideInMenu for clarity.


86-87: Simplified menu filtering logic.

The function now directly returns the filtered tree, making the code more concise and easier to understand.

packages/effects/layouts/src/basic/menu/menu.vue (1)

40-40: Added auto-scroll functionality to active menu items.

The scroll-to-active attribute has been added to the Menu component, enabling automatic scrolling to highlight the active menu item. This improves user experience by making the active item more visible, especially in large menus.

packages/@core/ui-kit/menu-ui/src/types.ts (1)

45-49: Added new scrollToActive property to MenuProps interface.

The new property properly follows the existing documentation pattern with JSDoc comments that include a description and default value. This type definition supports the new auto-scrolling feature.

packages/effects/access/src/accessible.ts (1)

69-69: Updated generateMenus call to be synchronous.

Removed the await keyword from the call to generateMenus, reflecting its new synchronous implementation. This change maintains consistency with the updated function signature in generate-menus.ts.

packages/utils/src/helpers/__tests__/generate-menus.test.ts (6)

72-72: Code updated to reflect synchronous function usage

The test has been correctly updated to remove await for generateMenus calls, reflecting the function's change from asynchronous to synchronous.


85-85: Properly updated to use synchronous API

The await keyword has been correctly removed to match the synchronous implementation of generateMenus.


112-112: Consistent synchronous usage applied

Good job maintaining consistency by removing await in all calls to the now-synchronous generateMenus function.


144-144: Synchronous function call updated correctly

The removal of await is consistent with the function's new synchronous nature.


195-195: Test updated correctly for synchronous execution

The test has been properly updated to use generateMenus as a synchronous function.


230-230: Final test updated for synchronous execution

The test for empty routes has been correctly updated to match the synchronous implementation.

packages/effects/layouts/src/basic/menu/use-navigation.ts (4)

11-24: Good route metadata management implementation

The introduction of initRouteMetaMap function improves organization by centralizing the route metadata initialization logic. The function is also properly called both initially and on route changes, ensuring the metadata is always up-to-date.


26-33: Well-designed utility function for window opening logic

The shouldOpenInNewWindow function nicely encapsulates the decision logic for determining if a path should open in a new window, making the code more maintainable and easier to test.


35-53: Improved navigation with better error handling

The refactored navigation function is more robust with:

  1. Proper error handling via try-catch
  2. Better handling of HTTP URLs
  3. Clearer conditional logic for different navigation types

This improves maintainability and makes debugging easier if navigation fails.


56-58: Consistent implementation using the helper function

Good job reusing the shouldOpenInNewWindow helper in willOpenedByWindow, which promotes code reuse and maintainability.

packages/@core/ui-kit/menu-ui/src/hooks/use-menu-scroll.ts (5)

1-11: Well-structured composable hook interface

The hook has a clean interface with good TypeScript typing. The use of optional parameters with defaults is a good practice for composables.


12-17: Good parameter defaults and TypeScript typing

The function signature properly uses TypeScript types and provides sensible defaults for the options.


18-32: Effective implementation of scroll functionality

The scrollToActiveItem function:

  1. Properly checks if scrolling is enabled
  2. Uses a precise DOM selector to find the active menu item
  3. Implements smooth scrolling with centered positioning

This approach ensures a good user experience when navigating between menu items.


34-41: Smart debounce implementation for scroll events

Using useDebounceFn from @vueuse/core is excellent for preventing excessive scroll operations during rapid path changes, improving performance and user experience.


43-46: Clean API exposure

The hook exports only what's needed - the scrollToActiveItem function - keeping the API minimal and focused.

packages/@core/ui-kit/menu-ui/src/components/menu.vue (6)

34-34: Properly imported new hook

The new useMenuScroll hook is correctly imported to implement the auto-scrolling functionality.


48-48: Feature toggle added with sensible default

Adding the scrollToActive prop with default false is a good approach as it:

  1. Makes the new feature opt-in rather than disruptively changing existing behavior
  2. Follows best practices for backward compatibility

211-213: Smart activation logic for scroll feature

The enableScroll computed property has good conditional logic that only enables scrolling when:

  1. The scrollToActive prop is true
  2. The menu is in vertical mode
  3. The menu is not collapsed

This prevents unnecessary scroll operations in contexts where they don't make sense.


215-218: Well-configured hook integration

The hook is properly configured with:

  1. The active path reference
  2. The computed enable property
  3. A sensible delay for debouncing

This ensures the scroll functionality works correctly within the menu component.


220-223: Reactive scroll trigger implementation

The watcher on activePath ensures that scrolling is triggered whenever the active menu item changes, creating a smooth and intuitive user experience.


328-336: Well-structured helper function

The getActivePaths function is clean and properly handles edge cases like missing active items or horizontal/collapsed modes. It's positioned correctly in the component flow.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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 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.

@anncwb anncwb merged commit 045bc4e into main May 3, 2025
14 checks passed
@anncwb anncwb deleted the feature/menu-scroll branch May 3, 2025 10:05
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.

FEATURE: 期望自动滚动到 高亮的菜单位置
1 participant