Skip to content

fix(nuxt): scroll to anchor if present when changing page without saved position #32376

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 6 commits into from
Jul 10, 2025

Conversation

DamianGlowala
Copy link
Member

🔗 Linked issue

resolves #32366

📚 Description

Moved logic which decides on scroll position to a single function for better readability. It now scrolls to hash if present when changing page without saved position. Removed explicit instant behavior as this appears to be the default one anyway.

@Copilot Copilot AI review requested due to automatic review settings June 12, 2025 19:50
@DamianGlowala DamianGlowala requested a review from danielroe as a code owner June 12, 2025 19:50
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the scroll position logic in the router options to improve code readability and to scroll to the hash element when present, while removing an unnecessary explicit 'instant' behavior parameter.

  • Refactored the logic that determines the scroll position on page navigation
  • Adjusted the _calculatePosition function signature and its usage in the scroll handler

Copy link

codspeed-hq bot commented Jun 12, 2025

CodSpeed Performance Report

Merging #32376 will not alter performance

Comparing fix/router-scroll-position (c3efb76) with main (5146bed)

Summary

✅ 10 untouched benchmarks

Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

pkg-pr-new bot commented Jun 12, 2025

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@32376

nuxt

npm i https://pkg.pr.new/nuxt@32376

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@32376

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@32376

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@32376

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@32376

commit: c3efb76

Copy link

coderabbitai bot commented Jul 10, 2025

Walkthrough

The scroll behaviour logic in the router options file was refactored. The intermediate variable for scroll position was removed, and the parameters passed to the internal _calculatePosition function were unified. The _calculatePosition function signature was updated to accept from, savedPosition, and defaultBehaviour parameters. The function now explicitly checks for savedPosition and determines scroll behaviour based on whether the navigation is a page change. The logic for setting scroll position was consolidated inside _calculatePosition, and the calling code was updated to match the new function signature. The timing and hook logic for resolving the scroll position promise was unchanged.


📜 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 5146bed and c3efb76.

📒 Files selected for processing (1)
  • packages/nuxt/src/pages/runtime/router.options.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.{ts,tsx}`: Follow standard TypeScript conventions and best practices

**/*.{ts,tsx}: Follow standard TypeScript conventions and best practices

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • packages/nuxt/src/pages/runtime/router.options.ts
`**/*.{ts,tsx,vue}`: Use clear, descriptive variable and function names Add comm...

**/*.{ts,tsx,vue}: Use clear, descriptive variable and function names
Add comments only to explain complex logic or non-obvious implementations
Keep functions focused and manageable (generally under 50 lines), and extract complex logic into separate domain-specific files
Remove code that is not used or needed
Use error handling patterns consistently

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • packages/nuxt/src/pages/runtime/router.options.ts
🧠 Learnings (1)
packages/nuxt/src/pages/runtime/router.options.ts (2)
Learnt from: huang-julien
PR: nuxt/nuxt#29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In `packages/nuxt/src/app/components/nuxt-root.vue`, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

```js
const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null
```

instead of wrapping the import in a computed property or importing the component unconditionally.
Learnt from: GalacticHypernova
PR: nuxt/nuxt#26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In `packages/nuxt/src/components/plugins/loader.ts`, the references to `resolve` and `distDir` are legacy code from before Nuxt used the new unplugin VFS and will be removed.
🧬 Code Graph Analysis (1)
packages/nuxt/src/pages/runtime/router.options.ts (1)
packages/nuxt/src/app/components/utils.ts (1)
  • isChangingPage (34-47)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: code
  • GitHub Check: build
  • GitHub Check: codeql (actions)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: lint-docs
🔇 Additional comments (7)
packages/nuxt/src/pages/runtime/router.options.ts (7)

35-35: Minor formatting change.

The empty line change appears to be a formatting adjustment.


38-38: Function call updated with new consolidated parameters.

The function calls to _calculatePosition have been updated to pass the new parameter set (to, from, savedPosition, behavior). This matches the refactored function signature and consolidates the scroll position logic.

Also applies to: 43-43


61-66: Function signature refactored for better parameter clarity.

The _calculatePosition function signature has been updated to accept more explicit parameters: from, savedPosition, and defaultBehavior instead of the previous scrollBehaviorType and optional position. This makes the function's requirements clearer and consolidates the scroll logic.


67-71: Correct handling of saved position for browser history navigation.

The early return for savedPosition is correct - when there's a saved position from browser history (back/forward navigation), it should be used immediately without further processing.


73-73: Appropriate use of utility function for page navigation detection.

Using isChangingPage to determine if the navigation results in a page change is the correct approach. This utility function properly handles route key differences and component changes.


80-80: Conditional scroll behavior logic is sound.

The conditional behavior (isPageNavigation ? defaultBehavior : 'instant') correctly applies the default behavior for page navigation and instant behavior for non-page navigation (e.g., hash-only changes within the same page). This maintains the expected user experience whilst addressing the previous concern about instant behavior when needed.


84-88: Consolidated scroll-to-top logic with appropriate behavior.

The default scroll-to-top behavior now uses the same conditional logic as the hash scrolling, ensuring consistent behavior across different scroll scenarios. The { left: 0, top: 0 } positioning with conditional behavior is correct for the default case.

✨ 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/router-scroll-position

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

@danielroe danielroe merged commit 5abd6bc into main Jul 10, 2025
155 of 158 checks passed
@danielroe danielroe deleted the fix/router-scroll-position branch July 10, 2025 13:50
@github-actions github-actions bot mentioned this pull request Jul 10, 2025
@github-actions github-actions bot mentioned this pull request Jul 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

NuxtLink with anchor (hash) doesn't jump to element unless defined as external
2 participants