Skip to content

fix(nuxt): align scroll behavior with page transition completion #32239

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
Jun 10, 2025

Conversation

Mini-ghost
Copy link
Member

@Mini-ghost Mini-ghost commented May 29, 2025

🔗 Linked issue

Related(?) #32053
Resolve #32193

📚 Description

In #31914, we used the <Transition> component’s onBeforeLeave hook to record whether a page transition is in progress, allowing router.options.ts to determine which hook to wait for before performing scroll behavior.

Originally, the sequence of events was as follows:

Suspense onPending → Transition onBeforeLeave → router.options.ts → Suspense onResolve → Transition onAfterLeave

However, when a page component uses <script setup> with top-level await expressions or an async setup() function, the event order changes to:

Suspense onPending → router.options.ts → Transition onBeforeLeave → Suspense onResolve → Transition onAfterLeave

In this case, since <Transition>’s onBeforeLeave is triggered after router.options.ts, make scroll logic cannot correctly determine whether a transition is in progress.

This PR moves the transition state tracking into the onPending hook of <Suspense>. I hope this adjustment ensures that scroll behavior remains correctly.

👉 #32193 fixed reproduction

@Copilot Copilot AI review requested due to automatic review settings May 29, 2025 19:22
@Mini-ghost Mini-ghost requested a review from danielroe as a code owner May 29, 2025 19:22
Copy link

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

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 aligns scroll behavior with page transition completion by moving the transition state flag assignment to an earlier lifecycle hook.

  • Removed the onBeforeLeave hook that previously set nuxtApp._runningTransition.
  • Updated the onPending hook to conditionally set nuxtApp._runningTransition when a transition is present and then call the page:start hook.

@@ -169,7 +166,10 @@ export default defineComponent({
vnode = _wrapInTransition(hasTransition && transitionProps,
wrapInKeepAlive(keepaliveConfig, h(Suspense, {
suspensible: true,
onPending: () => nuxtApp.callHook('page:start', routeProps.Component),
onPending: () => {
Copy link
Preview

Copilot AI May 29, 2025

Choose a reason for hiding this comment

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

Consider adding an inline comment that explains the rationale for conditionally setting nuxtApp._runningTransition in the onPending hook based on the hasTransition flag, to improve maintainability.

Copilot uses AI. Check for mistakes.

Copy link

coderabbitai bot commented May 29, 2025

Walkthrough

The update modifies the handling of the internal _runningTransition flag within the Nuxt page runtime. Previously, this flag was set to true during the onBeforeLeave phase of a transition. With the change, the flag is now set within the onPending callback of the Suspense component, and only if a transition is active. The removal of the onBeforeLeave hook and the conditional setting of the flag in onPending alter the timing and conditions under which _runningTransition is activated. The logic for clearing the flag in onAfterLeave remains unchanged. Additionally, a new test suite was introduced to verify router scroll behaviour during page transitions, including tests for both asynchronous and synchronous route components. No exported or public entity declarations were altered.

✨ 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.
    • 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 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

pkg-pr-new bot commented May 29, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 89a7046

Copy link

codspeed-hq bot commented May 29, 2025

CodSpeed Performance Report

Merging #32239 will not alter performance

Comparing Mini-ghost:fix/align-scroll-behavior (89a7046) with main (294f95a)

Summary

✅ 10 untouched benchmarks

@florian-strasser
Copy link

Looks promising - hope it will finally fix the issue :-)

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.

I would love to have a test for this... (as there is a matrix of scroll behaviour and I'd like this not to break again)

ideally a nuxt runtime test rather than an e2e test (which can be notoriously flaky on scroll).

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: 0

🧹 Nitpick comments (5)
test/nuxt/router.option.test.ts (5)

13-24: Consider making the sleep duration configurable and increasing the waitFor timeout.

The hardcoded 10ms sleep duration may be insufficient for testing realistic async behaviour, and the 1000ms timeout could cause flaky tests in CI environments.

-const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+const sleep = (ms: number = 50) => new Promise(resolve => setTimeout(resolve, ms))

-const waitFor = async (condition: () => boolean, timeout = 1000) => {
+const waitFor = async (condition: () => boolean, timeout = 5000) => {

32-52: Extract component definitions to improve test readability.

The inline component definitions make the addRoute function complex. Consider extracting them for better maintainability.

+const createSyncComponent = () => defineComponent({
+  name: '~/pages/[...slug].vue',
+  setup: () => () => h('div'),
+})
+
+const createAsyncComponent = () => defineComponent({
+  name: '~/pages/[...slug].vue',
+  async setup() {
+    await sleep(50)
+    return () => h('div')
+  },
+})

 const addRoute = (sync: boolean) => {
   router.addRoute({
     name: 'slug',
     path: '/:slug(.*)*',
-    component: defineComponent({
-      name: '~/pages/[...slug].vue',
-      ...(sync
-        ? {
-            setup: () => () => h('div'),
-          }
-        : {
-            async setup () {
-              await sleep(10)
-              return () => h('div')
-            },
-          }
-      ),
-    }),
+    component: sync ? createSyncComponent() : createAsyncComponent(),
   })
 }

58-62: Enhance cleanup to prevent test interference.

The current cleanup may not fully reset the router state, potentially causing test interference.

 afterEach(() => {
+  // Clear any pending navigation
+  router.replace('/')
   router.removeRoute('slug')
   vi.clearAllMocks()
   scrollTo.mockClear()
+  // Clear any registered hooks
+  nuxtApp.hooks.clear()
 })

96-126: Consider consolidating duplicate test logic.

Both test cases share nearly identical setup and assertions. Extract common logic to reduce duplication.

+const runScrollBehaviorTest = async (useAsyncComponent: boolean) => {
+  addRoute(!useAsyncComponent)
+
+  await mountSuspended({
+    setup: () => () => h(NuxtPage, {
+      transition: {
+        name: 'fade',
+        mode: 'out-in',
+        duration: 10,
+      },
+    }),
+  })
+
+  await flushPromises()
+
+  const pageTransitionFinish = vi.fn()
+  const pageLoadingEnd = vi.fn()
+
+  nuxtApp.hook('page:transition:finish', pageTransitionFinish)
+  nuxtApp.hook('page:loading:end', pageLoadingEnd)
+
+  await router.push('/page')
+  await waitFor(() => pageTransitionFinish.mock.calls.length > 0)
+
+  expect(pageTransitionFinish).toHaveBeenCalled()
+  expect(pageLoadingEnd).toHaveBeenCalled()
+  expect(scrollTo).toHaveBeenCalled()
+  expect(pageTransitionFinish).toHaveBeenCalledBefore(scrollTo)
+}

 it('should call scrollTo after page transition is finished with async component', async () => {
-  addRoute(false)
-  // ... rest of test logic
+  await runScrollBehaviorTest(true)
 })

 it('should call scrollTo after page transition is finished with sync component', async () => {
-  addRoute(true)
-  // ... rest of test logic
+  await runScrollBehaviorTest(false)
 })

67-75: Transition duration may be too short for reliable testing.

The 10ms transition duration could cause timing issues in slower test environments.

       transition: {
         name: 'fade',
         mode: 'out-in',
-        duration: 10,
+        duration: 100,
       },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2aa870c and 89a7046.

📒 Files selected for processing (1)
  • test/nuxt/router.option.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: code
  • GitHub Check: semantic-pr
🔇 Additional comments (2)
test/nuxt/router.option.test.ts (2)

1-11: Test configuration and imports look appropriate.

The imports correctly include the necessary testing utilities and the transition stub configuration properly allows actual transition behaviour to be tested.


64-94: Test correctly validates async component scroll behaviour.

The test properly verifies that scrollTo is called after page transition completion, which aligns with the PR objective of fixing scroll behaviour timing with async components.

@danielroe danielroe merged commit 017d1be into nuxt:main Jun 10, 2025
118 of 120 checks passed
@github-actions github-actions bot mentioned this pull request Jun 10, 2025
@Mini-ghost Mini-ghost deleted the fix/align-scroll-behavior branch June 11, 2025 09:27
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.

Scroll behaviour timing is not properly aligned to page transition duration
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