diff --git a/packages/vinext/src/shims/router.ts b/packages/vinext/src/shims/router.ts index 0e4527b4be..a2300bc187 100644 --- a/packages/vinext/src/shims/router.ts +++ b/packages/vinext/src/shims/router.ts @@ -169,6 +169,7 @@ function renderPagesRouterElement( } cancelPreviousRenderCommit(); + commitRouterSnapshot(); return new Promise((resolve, reject) => { const cancel = () => { @@ -443,6 +444,12 @@ type PagesRouterRuntimeState = { routerDidNavigate: boolean; deprecatedEventBridgeInstalled: boolean; pagesRouterReady: boolean; + /** + * The router snapshot of the last committed router state change (see + * `commitRouterSnapshot`). `token` grows by one per commit, so the provider + * can tell a newer commit from the state it already holds. + */ + committedRouterSnapshot: CommittedRouterSnapshot | null; publicRouter?: Record; }; @@ -473,6 +480,7 @@ function createPagesRouterRuntimeState(): PagesRouterRuntimeState { routerDidNavigate: false, deprecatedEventBridgeInstalled: false, pagesRouterReady: typeof window === "undefined" || !shouldDeferInitialPagesRouterReady(), + committedRouterSnapshot: null, }; } @@ -3218,10 +3226,21 @@ function stripHash(url: string): string { return i === -1 ? url : url.slice(0, i); } +/** + * `detail` of the `vinext:navigate` events the router dispatches. Every such + * navigation has already committed its router snapshot (`commitRouterSnapshot`). + * A string, not an object: the client entry and page chunks can each evaluate + * their own `next/router` instance, and the provider must recognise an event + * dispatched by any of them. + */ +const ROUTER_NAVIGATE_EVENT_DETAIL = "vinext.routerStateCommitted"; + /** Notify in-page listeners (e.g. useRouter hooks) that navigation occurred. */ function dispatchNavigateEvent(): void { notifyNextNavigationPagesContext(); - window.dispatchEvent(new CustomEvent("vinext:navigate")); + window.dispatchEvent( + new CustomEvent("vinext:navigate", { detail: ROUTER_NAVIGATE_EVENT_DETAIL }), + ); } /** @@ -3701,6 +3720,7 @@ async function performNavigation( : (redirectBrowserHref ?? credentialedDisplayHref ?? full), navState, ); + commitRouterSnapshot(); if (doScroll) scrollToHashTarget(extractHash(resolved)); onStateUpdate?.(); routerEvents.emit("hashChangeComplete", eventUrl, { shallow }); @@ -3831,6 +3851,7 @@ async function performNavigation( if (result === "failed") return false; } else { emitBeforeHistoryChange(); + commitRouterSnapshot(); // Shallow navigations skip the render-commit path, so apply the scroll // reset synchronously here — before routeChangeComplete. This matches the // non-shallow path, where the x/y reset runs inside the render-commit @@ -3935,8 +3956,62 @@ export function useRouter(): NextRouter { ); } +type RouterSnapshot = ReturnType; + +type CommittedRouterSnapshot = { + token: number; + snapshot: RouterSnapshot; +}; + +type RouterSnapshotState = { + snapshot: RouterSnapshot; + // The `committedRouterSnapshot` token this state already accounts for. + commitToken: number; +}; + +function getCommittedRouterSnapshotToken(): number { + return routerRuntimeState.committedRouterSnapshot?.token ?? 0; +} + +/** + * Record the router state at the moment a change commits, like Next.js's + * `Router#set()` assigning `this.state` (packages/next/src/shared/lib/router/router.ts). + * A render-backed navigation calls this once its history entry and + * `__NEXT_DATA__` are committed, right before `root.render()`; shallow and + * hash-only changes call it after their history update, and the ready + * transition when it flips the ready bit. The provider only ever shows a + * committed snapshot, never the live location: on popstate the browser moves + * `location` before the route is resolved, a traversal rejected by + * `beforePopState` never commits, and the location may move again before a + * completed navigation dispatches `vinext:navigate`. + */ +function commitRouterSnapshot(): void { + routerRuntimeState.committedRouterSnapshot = { + token: getCommittedRouterSnapshotToken() + 1, + snapshot: getRouterSnapshot(), + }; +} + +function takeRouterSnapshot(): RouterSnapshotState { + return { snapshot: getRouterSnapshot(), commitToken: getCommittedRouterSnapshotToken() }; +} + +/** Adopt a router state commit newer than the provider's state, if there is one. */ +function adoptCommittedRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { + const committed = routerRuntimeState.committedRouterSnapshot; + if (committed === null || committed.token === prev.commitToken) return prev; + return { snapshot: committed.snapshot, commitToken: committed.token }; +} + function PagesRouterProvider({ children }: { children: ReactNode }): ReactElement { - const [{ pathname, query, asPath, isReady }, setState] = useState(getRouterSnapshot); + const [routerState, setState] = useState(takeRouterSnapshot); + // A client navigation records its route snapshot and then calls + // root.render(), which re-renders this provider with its old state. Adopt the + // committed snapshot during render, before any child reads the context, so + // the new page's first render already sees its route, as in Next.js. + const currentRouterState = adoptCommittedRouterSnapshot(routerState); + if (currentRouterState !== routerState) setState(currentRouterState); + const { pathname, query, asPath, isReady } = currentRouterState.snapshot; // Popstate is handled by the Pages Router client entry via // installPagesRouterRuntime() so beforePopState() is consistently enforced @@ -3944,8 +4019,14 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen // provider boundary so many useRouter() calls share one router state and one // vinext:navigate listener. useEffect(() => { - const onNavigate = ((_e: CustomEvent) => { - setState(getRouterSnapshot()); + // The router's own navigations committed their snapshot already (a + // render-backed one was adopted during render, so this only picks up + // shallow and hash-only changes). Never re-read the live location for + // them: it may have moved since. An event dispatched outside the router + // has no commit, so it records the live state, as before. + const onNavigate = ((e: CustomEvent) => { + if (e.detail !== ROUTER_NAVIGATE_EVENT_DETAIL) commitRouterSnapshot(); + setState(adoptCommittedRouterSnapshot); }) as EventListener; window.addEventListener("vinext:navigate", onNavigate); let cancelled = false; @@ -3954,7 +4035,8 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen const becameReady = markPagesRouterReady(); if (becameReady) { - setState(getRouterSnapshot()); + commitRouterSnapshot(); + setState(adoptCommittedRouterSnapshot); notifyNextNavigationPagesContext(); } }, 0); @@ -4192,6 +4274,7 @@ function handlePagesRouterPopState(e: PopStateEvent): void { // L1381-1403 and L1780). The snapshot stays in sessionStorage, so a later // non-hash popstate to this entry still restores the saved position. const hashUrl = browserUrl + window.location.hash; + commitRouterSnapshot(); routerEvents.emit("hashChangeStart", hashUrl, { shallow: false }); scrollToHashTarget(window.location.hash); routerEvents.emit("hashChangeComplete", hashUrl, { shallow: false }); diff --git a/tests/e2e/pages-router/first-render-router.spec.ts b/tests/e2e/pages-router/first-render-router.spec.ts new file mode 100644 index 0000000000..aa413ede71 --- /dev/null +++ b/tests/e2e/pages-router/first-render-router.spec.ts @@ -0,0 +1,132 @@ +import { test, expect, type Page } from "@playwright/test"; + +const BASE = "http://localhost:4173"; + +type RenderRecord = { + query: Record; + pathname: string; + asPath: string; + location: string; +}; + +async function takeRenders(page: Page): Promise { + return page.evaluate(() => { + const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] }; + const renders = w.__FIRST_RENDER_ROUTER__ ?? []; + w.__FIRST_RENDER_ROUTER__ = []; + return renders; + }); +} + +function expectEveryRenderToSee(renders: RenderRecord[], id: string): void { + expect(renders.length).toBeGreaterThan(0); + for (const render of renders) { + expect(render).toEqual({ + query: { id }, + pathname: "/first-render-router/[id]", + asPath: `/first-render-router/${id}`, + location: `/first-render-router/${id}`, + }); + } +} + +// Next.js assigns router state before rendering the new page (Router#set() +// in packages/next/src/shared/lib/router/router.ts), so the first render after +// a client navigation already sees the destination route. +test("useRouter() returns the new route on the first render after client navigation", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + + // from a static page to a dynamic one. + await page.click('[data-testid="first-render-link"]'); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1"); + expectEveryRenderToSee(await takeRenders(page), "1"); + + // router.push between two params of the same dynamic page, which stays mounted. + await page.click('[data-testid="first-render-push"]'); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2"); + expectEveryRenderToSee(await takeRenders(page), "2"); + + // Back (popstate) to the previous param. + await page.goBack(); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1"); + expectEveryRenderToSee(await takeRenders(page), "1"); +}); + +// The provider renders the route the navigation committed, not whatever the +// browser location is when React renders or when the navigation completes. On +// popstate the browser moves `location` before the route is resolved, so the +// live URL must never be mixed with the committed page. +test("useRouter() keeps the committed route if location moves after the commit", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router/1`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + await takeRenders(page); + + await page.evaluate(() => { + const w = window as any; + w.__FIRST_RENDER_NAVIGATED__ = false; + w.next.router.events.on("routeChangeComplete", () => { + // vinext:navigate is dispatched right after routeChangeComplete; let the + // provider's listener run and React commit before declaring it done. + setTimeout(() => { + w.__FIRST_RENDER_NAVIGATED__ = true; + }, 50); + }); + const root = w.__VINEXT_ROOT__; + const render = root.render.bind(root); + root.render = (element: unknown) => { + root.render = render; + render(element); + // React renders later, in its own task. Move the URL before it does and + // keep it moved through the navigation's completion. + window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1"); + }; + }); + await page.click('[data-testid="first-render-push"]'); + await page.waitForFunction(() => (window as any).__FIRST_RENDER_NAVIGATED__ === true); + + const renders = await takeRenders(page); + expect(renders.length).toBeGreaterThan(0); + for (const render of renders) { + expect({ query: render.query, pathname: render.pathname, asPath: render.asPath }).toEqual({ + query: { id: "2" }, + pathname: "/first-render-router/[id]", + asPath: "/first-render-router/2", + }); + } + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2"); +}); + +// The client entry and page chunks can each evaluate their own `next/router` +// instance, so the provider may receive `vinext:navigate` from a router module +// other than its own. Such an event carries the router's marker as a value +// created outside the provider's module, and must still count as a committed +// navigation, never a cue to re-read the live location. +test("useRouter() treats vinext:navigate from another router instance as committed", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router/1`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + await takeRenders(page); + + await page.evaluate(async () => { + window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1"); + window.dispatchEvent( + new CustomEvent("vinext:navigate", { detail: "vinext.routerStateCommitted" }), + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + // Nothing was committed, so the provider has no reason to re-render; any + // render that does happen must still see the committed route. + for (const render of await takeRenders(page)) { + expect({ query: render.query, asPath: render.asPath }).toEqual({ + query: { id: "1" }, + asPath: "/first-render-router/1", + }); + } +}); diff --git a/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx b/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx new file mode 100644 index 0000000000..ca56312b70 --- /dev/null +++ b/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx @@ -0,0 +1,34 @@ +import { useRouter } from "next/router"; + +type RenderRecord = { + query: Record; + pathname: string; + asPath: string; + location: string; +}; + +export const getServerSideProps = async () => ({ props: {} }); + +export default function FirstRenderRouterItem() { + const router = useRouter(); + if (typeof window !== "undefined") { + const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] }; + (w.__FIRST_RENDER_ROUTER__ ??= []).push({ + query: { ...router.query }, + pathname: router.pathname, + asPath: router.asPath, + location: window.location.pathname, + }); + } + return ( +
+

{String(router.query.id)}

+ +
+ ); +} diff --git a/tests/fixtures/pages-basic/pages/first-render-router/index.tsx b/tests/fixtures/pages-basic/pages/first-render-router/index.tsx new file mode 100644 index 0000000000..283da82473 --- /dev/null +++ b/tests/fixtures/pages-basic/pages/first-render-router/index.tsx @@ -0,0 +1,9 @@ +import Link from "next/link"; + +export default function FirstRenderRouterHome() { + return ( + + go to /first-render-router/1 + + ); +}