Skip to content

fix(nuxt): respect the scroll behavior set by scrollToTop #31914

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 4 commits into from
May 1, 2025

Conversation

Mini-ghost
Copy link
Member

@Mini-ghost Mini-ghost commented Apr 27, 2025

🔗 Linked issue

📚 Description

Fix an issue where setting scrollToTop: false did not preserve the current scroll position when navigating within the same page component.

After this PR, #31654, #31638 and #25241 can now be addressed by using the following approach to prevent scrolling to the top when navigating within the same page component:

<script setup lang="ts">
definePageMeta({
  scrollToTop: false,
})
</script>

Additionally, this PR also corrects the registration and invocation order of the page:loading:end hook.

In current, when navigating within the same page component, the first navigation triggers nuxtApp.callHook('page:loading:end') inside page.ts before nuxtApp.hooks.hookOnce('page:loading:end', () => { ... }) is registered in router.options.ts.

This explains why, in the provided minimal reproduction, the page does not scroll to the top on the first navigation but does on the second navigation.

https://stackblitz.com/edit/github-c5oaac3b-jwythaqo?file=pages/foo/%5Bid%5D.vue

Lastly, this PR also updates the hookToWait condition in router.options.ts to ensure that any method of enabling <Transition> is properly recognized.

Thank you very much for your time and review! If there’s anything I might have overlooked, please feel free to let me know.

Copy link

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

Copy link

pkg-pr-new bot commented Apr 27, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/schema

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

@nuxt/rspack-builder

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: fd4da2a

Copy link

codspeed-hq bot commented Apr 27, 2025

CodSpeed Performance Report

Merging #31914 will not alter performance

Comparing Mini-ghost:fix/default-scroll-behaviour (fd4da2a) with main (1e34a9c)

Summary

✅ 10 untouched benchmarks

@Mini-ghost Mini-ghost marked this pull request as ready for review April 27, 2025 14:44
@Mini-ghost Mini-ghost requested a review from danielroe as a code owner April 27, 2025 14:44
Copy link

coderabbitai bot commented Apr 27, 2025

Walkthrough

The changes modify Nuxt's page transition and scroll behaviour handling. In the page runtime code, the page:loading:end hook call is deferred using nextTick, and two new transition lifecycle hooks, onBeforeLeave and onAfterLeave, are added to manage a _runningTransition flag and trigger the page:transition:finish hook. The router options update the scroll behaviour logic by checking the scrollToTop meta property earlier, simplifying the conditions for waiting on transition or loading hooks, and introducing immediate scroll resolution for initial navigation from START_LOCATION. New tests verify scroll-to-top functionality based on route meta flags, including cases where scrolling to top is disabled or enabled. Two new Vue fixture pages support these tests: one provides navigation links with different scrollToTop settings, and the other dynamically defines scrollToTop based on a query parameter. No changes to public API signatures or exported declarations are made.


📜 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 1d098c3 and fd4da2a.

📒 Files selected for processing (1)
  • test/nuxt/loading-indicator.test.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • test/nuxt/loading-indicator.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code
✨ 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.

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.

Copy link

@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: 1

🧹 Nitpick comments (4)
packages/nuxt/src/pages/runtime/page.ts (1)

157-166: Consider using undefined assignment instead of delete operator.

The transition hooks implementation is good, adding proper lifecycle hooks to manage the transition state. However, at line 162, using the delete operator can impact performance.

-                  delete nuxtApp._runningTransition
+                  nuxtApp._runningTransition = undefined
🧰 Tools
🪛 Biome (1.9.4)

[error] 162-162: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

test/fixtures/basic/pages/route-scroll-behavior/scroll-to-top.vue (1)

1-7: Consider translating the console log message to English.

The hook implementation is correct, but the console log message is in a non-English language which might make debugging harder for developers who don't understand it.

- console.log('動畫完成', Data)
+ console.log('Animation complete', Data)
packages/nuxt/src/pages/runtime/router.options.ts (2)

30-33: scrollToTop meta value should be normalised to a strict boolean
routeAllowsScrollToTop may become undefined, null, a truthy string, etc. In that case the comparison === false works, but the variable is later used only for an early return.
For clarity and to avoid subtle truthiness bugs, consider casting to Boolean first:

-const routeAllowsScrollToTop = typeof to.meta.scrollToTop === 'function'
-  ? to.meta.scrollToTop(to, from)
-  : to.meta.scrollToTop
+const routeAllowsScrollToTop = Boolean(
+  typeof to.meta.scrollToTop === 'function'
+    ? to.meta.scrollToTop(to, from)
+    : to.meta.scrollToTop,
+)
+
+if (!routeAllowsScrollToTop) { return false }

This also removes the redundant second if check.


43-43: Type-safety for the _runningTransition flag
nuxtApp._runningTransition is accessed without declaration. To aid IDEs and TS users, augment NuxtApp’s type via module-augmentation so the property is no longer any.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9996f06 and 1d098c3.

📒 Files selected for processing (5)
  • packages/nuxt/src/pages/runtime/page.ts (1 hunks)
  • packages/nuxt/src/pages/runtime/router.options.ts (2 hunks)
  • test/basic.test.ts (1 hunks)
  • test/fixtures/basic/pages/route-scroll-behavior/scroll-to-top.vue (1 hunks)
  • test/fixtures/basic/pages/route-scroll-behavior/scroll-to-top/[id].vue (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/nuxt/src/pages/runtime/router.options.ts (1)
packages/nuxt/src/app/components/utils.ts (1)
  • isChangingPage (34-47)
test/basic.test.ts (1)
test/utils.ts (1)
  • renderPage (11-50)
🪛 Biome (1.9.4)
packages/nuxt/src/pages/runtime/page.ts

[error] 162-162: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (7)
test/fixtures/basic/pages/route-scroll-behavior/scroll-to-top/[id].vue (2)

1-9: Looks good - dynamic route with scrollToTop metadata defined correctly.

The implementation correctly defines the page metadata with a dynamic scrollToTop function that reads from the route query parameters. This pattern allows for conditional scroll behavior based on URL parameters.


11-15: Clean and straightforward template.

The template simply renders the route parameter in an h2 element, which is appropriate for testing the scroll behavior functionality.

packages/nuxt/src/pages/runtime/page.ts (1)

144-148: Good improvement by wrapping in nextTick.

Deferring the page loading end hook into the next tick ensures the DOM is updated before declaring the page as loaded, which helps with proper timing of scroll behavior.

test/basic.test.ts (1)

3020-3046: Well-written tests for scroll behavior verification.

These tests properly verify the scroll behavior functionality:

  1. First test confirms that when scrollToTop is false, the scroll position is preserved
  2. Second test confirms that when scrollToTop is true, the page scrolls back to the top

The tests include proper scrolling of elements into view, waiting for scroll position changes, and verifying the final scroll position.

test/fixtures/basic/pages/route-scroll-behavior/scroll-to-top.vue (1)

9-43: Good test page setup with clear navigation options.

The template effectively sets up a test environment for scroll behavior:

  1. Includes a large spacer div to enable scrolling
  2. Provides clearly labeled navigation links that test different scroll behaviors
  3. Sets appropriate IDs on the links for test selection

The links are properly configured with different route parameters and query parameters to test the various scroll behavior scenarios.

packages/nuxt/src/pages/runtime/router.options.ts (2)

1-1: Confirm compatibility of START_LOCATION import with supported Vue-Router versions
START_LOCATION is only exported in Vue-Router ≥ 4.2.0.
If Nuxt still allows installing an older minor (e.g. 4.1.x) the build will break at compile-time.
Please double-check the vue-router peer-dependency range or guard the import with a re-export/polyfill.


34-41: ⚠️ Potential issue

Saved position 0,0 is currently discarded
let position: ScrollPosition = savedPosition || undefined treats { left: 0, top: 0 } as falsy, so a browser back-navigation that legitimately stored (0,0) will be overwritten by the automatic “scroll-to-top on page change” block below.

A safer guard:

-let position: ScrollPosition = savedPosition || undefined
+let position: ScrollPosition = savedPosition ?? undefined

The nullish coalescing operator preserves { left: 0, top: 0 }.

Likely an incorrect or invalid review comment.

@danielroe
Copy link
Member

did you take a look at the test failure?

@serkodev
Copy link

Thanks for the PR!

I believe that when changing routes without the need for a rerender, the default scroll behavior should not scroll to the top, which would be more reasonable.

In the example I provided in the #31654, a page key has already been defined, so rerendering won’t occur. Theoretically, page hooks won’t be triggered either, so I think it’s reasonable to not scrolling by default, instead of adding scrollToTop: false.

Copy link
Member

@danielroe danielroe left a comment

Choose a reason for hiding this comment

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

fantastic! ❤️

@danielroe
Copy link
Member

I agree with @serkodev that we also should know not to scroll to the top if there's no rerender (for example, when the page key is provided and does not change), so I've marked those issues as not (yet) resolved but this does give a workaround for them in the mean time.

@danielroe danielroe merged commit 084f47e into nuxt:main May 1, 2025
51 checks passed
@github-actions github-actions bot mentioned this pull request May 1, 2025
@github-actions github-actions bot mentioned this pull request Apr 30, 2025
@Mini-ghost Mini-ghost deleted the fix/default-scroll-behaviour branch May 1, 2025 22:17
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.

Page scroll to top before transition has started using NuxtPage transition definePageMeta({ scrollToTop: false }); not working for nested pages
3 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy