diff --git a/packages/react/src/runtime/context.ts b/packages/react/src/runtime/context.ts index 7306f9931..cf6feb330 100644 --- a/packages/react/src/runtime/context.ts +++ b/packages/react/src/runtime/context.ts @@ -18,6 +18,10 @@ export const ParamsContext: Context | null> = createConte export const RouterContext: Context = createContext(null); export const NavigationContext: Context = createContext(idleNavigationState()); +// Identifies the router's own value when a server-rendered subtree hydrates during a visit. +export const RouterNavigationContext: Context = + createContext(null); + // Island renderers provide the page's Markdown frontmatter above its layouts. // The `@void/md` runtime re-exports this context for `useFrontmatter()`. export const FrontmatterContext: Context> = createContext< diff --git a/packages/react/src/runtime/link.tsx b/packages/react/src/runtime/link.tsx index 0dcada0da..f3e8a1d2f 100644 --- a/packages/react/src/runtime/link.tsx +++ b/packages/react/src/runtime/link.tsx @@ -13,16 +13,21 @@ import type { } from 'react'; import { handleLinkClick, - getLinkStatus, linkStatusAttributes, - getResolvedLinkStatus, + matchResolvedLink, linkPrefetchStrategies, observeLinkVisible, prefetchLink, resolveLink, } from 'void/pages-client'; -import type { BaseLinkProps, LinkStatus, LinkStatusOptions } from 'void/pages-client'; -import { NavigationContext, RouterContext } from './context.ts'; +import type { + BaseLinkProps, + LinkStatus, + LinkStatusMatch, + LinkStatusOptions, +} from 'void/pages-client'; +import { RouterContext } from './context.ts'; +import { useNavigation } from './use-navigation.ts'; type CommonProps = BaseLinkProps & { children?: ReactNode | ((status: LinkStatus) => ReactNode); @@ -42,20 +47,31 @@ export function useLinkStatus( { method, data, activeMatch }: LinkStatusOptions = {}, ): LinkStatus { const router = useContext(RouterContext); - const navigation = useContext(NavigationContext); - return useStableLinkStatus( - useMemo( - () => getLinkStatus(router, navigation, href, { method, data, activeMatch }), - [activeMatch, data, href, method, navigation, router], - ), + const status = useMemo( + () => matchResolvedLink(router, resolveLink({ href, method, data }), activeMatch), + [activeMatch, data, href, method, router], ); + return useMatchedLinkStatus(status); } /** Keeps one object per status value so memoized children and effects skip unchanged updates. */ -function useStableLinkStatus({ current, active, pending }: LinkStatus): LinkStatus { +function useMatchedLinkStatus(match: LinkStatusMatch): LinkStatus { + const { current, active } = match; + const pending = match.pending(useNavigation()); return useMemo(() => ({ current, active, pending }), [active, current, pending]); } +function LinkContent({ + match, + render, +}: { + match: LinkStatusMatch; + render: (status: LinkStatus) => JSX.Element; +}): JSX.Element { + const status = useMatchedLinkStatus(match); + return useMemo(() => render(status), [render, status]); +} + export function Link({ href, method = 'GET', @@ -80,7 +96,6 @@ export function Link({ ...rest }: LinkProps): JSX.Element { const router = useContext(RouterContext); - const navigation = useContext(NavigationContext); const elementRef = useRef(null); const setElementRef = useCallback((element: HTMLElement | null) => { elementRef.current = element; @@ -96,13 +111,10 @@ export function Link({ () => linkPrefetchStrategies({ prefetch, reloadDocument }, { isGet }, defaultStrategy), [defaultStrategy, isGet, prefetch, reloadDocument], ); - const status = useStableLinkStatus( - useMemo( - () => getResolvedLinkStatus(router, navigation, link, activeMatch), - [activeMatch, link, navigation, router], - ), + const statusMatch = useMemo( + () => matchResolvedLink(router, link, activeMatch), + [activeMatch, link, router], ); - const attributes = linkStatusAttributes(status); const hoverDelay = router?._hoverDelay ?? 75; const doPrefetch = useCallback( @@ -267,32 +279,40 @@ export function Link({ [style], ); - const content = typeof children === 'function' ? children(status) : children; - if (link.isGet) { - return ( - - {content} - - ); - } - return ( - + { + const attributes = linkStatusAttributes(status); + const content = typeof children === 'function' ? children(status) : children; + if (link.isGet) { + return ( + + {content} + + ); + } + + return ( + + ); + }} + /> ); } diff --git a/packages/react/src/runtime/pages-client.ts b/packages/react/src/runtime/pages-client.ts index 99dd4487b..97f6418c4 100644 --- a/packages/react/src/runtime/pages-client.ts +++ b/packages/react/src/runtime/pages-client.ts @@ -41,6 +41,7 @@ import { setActionRouter } from './action.ts'; import { ErrorsContext, NavigationContext, + RouterNavigationContext, ParamsContext, RouterContext, SharedContext, @@ -340,7 +341,8 @@ function createRouter(engine: PageNavigationEngine): VoidRouter return router; } -function RouteResource({ +// Memoized so a navigation state update re-renders only the components that read it. +const RouteResource = React.memo(function RouteResource({ resource, onCommit, config, @@ -445,7 +447,7 @@ function RouteResource({ ), ), ); -} +}); function startViewTransition( resource: ReactPageResource, @@ -789,6 +791,8 @@ function App({ }; }, [isTransitionPending, lastNavigation, state.navigation]); + const onRouteFailure = useCallback((url: string) => engine.flush(url), [engine]); + const routerValue = useMemo( () => createRouterFacade(router, () => @@ -804,19 +808,23 @@ function App({ NavigationContext.Provider, { value: navigationValue }, React.createElement( - Suspense, - { - fallback: - NavigationFallback && state.pendingId !== null - ? React.createElement(NavigationFallback, { initialPageData }) - : null, - }, - React.createElement(RouteResource, { - resource: state.resource, - onCommit: finishNavigation, - config, - onFailure: (url: string) => engine.flush(url), - }), + RouterNavigationContext.Provider, + { value: navigationValue }, + React.createElement( + Suspense, + { + fallback: + NavigationFallback && state.pendingId !== null + ? React.createElement(NavigationFallback, { initialPageData }) + : null, + }, + React.createElement(RouteResource, { + resource: state.resource, + onCommit: finishNavigation, + config, + onFailure: onRouteFailure, + }), + ), ), ), ); diff --git a/packages/react/src/runtime/use-navigation.ts b/packages/react/src/runtime/use-navigation.ts index e967641bd..d92d8a843 100644 --- a/packages/react/src/runtime/use-navigation.ts +++ b/packages/react/src/runtime/use-navigation.ts @@ -1,7 +1,22 @@ -import { useContext } from 'react'; +import { useContext, useSyncExternalStore } from 'react'; +import { idleNavigationState } from 'void/pages-client'; import type { NavigationState } from 'void/pages-client'; -import { NavigationContext } from './context.ts'; +import { NavigationContext, RouterNavigationContext } from './context.ts'; + +const serverIdle = idleNavigationState(); +const subscribeNever = () => () => {}; +const hydrated = () => false; +const hydrating = () => true; export function useNavigation(): NavigationState { - return useContext(NavigationContext); + const navigation = useContext(NavigationContext); + const routerNavigation = useContext(RouterNavigationContext); + // During selective hydration the router's server snapshot is idle. A nested provider + // supplies its own server value, including during a visit to the same destination. + const isServerSnapshot = useSyncExternalStore( + subscribeNever, + hydrated, + navigation === routerNavigation && navigation.state !== 'idle' ? hydrating : hydrated, + ); + return isServerSnapshot ? serverIdle : navigation; } diff --git a/packages/react/test/integration/react-pages-client.test.ts b/packages/react/test/integration/react-pages-client.test.ts index b4a8dd5a7..154b26aab 100644 --- a/packages/react/test/integration/react-pages-client.test.ts +++ b/packages/react/test/integration/react-pages-client.test.ts @@ -30,6 +30,7 @@ declare global { interface Window { __SPA_MARKER?: boolean; __visitAwaitObserved?: string | null; + __visitAwaitRenders?: number; __hashNavigationReady?: boolean; __headRefs?: { font: Element | null; @@ -209,6 +210,41 @@ beforeAll(async () => { REACT_PAGES_ROOT = fixture.root; REACT_PAGES_LAYOUT = join(REACT_PAGES_ROOT, 'pages/layout.tsx'); LATE_WORKER_DEPS_ROOT = join(REACT_PAGES_ROOT, 'node_modules/@void-repro'); + const statusFixture = join(REACT_PAGES_ROOT, 'pages/navigation-status'); + mkdirSync(statusFixture); + writeFileSync( + join(statusFixture, 'index.tsx'), + 'export default function Page() { return null; }', + ); + writeFileSync( + join(statusFixture, 'next.tsx'), + 'export default function Page() { return

Arrived

; }', + ); + writeFileSync( + join(statusFixture, 'layout.tsx'), + ` +import { useLayoutEffect, useRef } from 'react'; +import { Link, NavigationContext, useLinkStatus, useNavigation, useRouter } from '@void/react'; +const href = '/navigation-status/next'; +function Reader({ id }: { id: string }) { + const { state } = useNavigation(); + const { pending } = useLinkStatus(href); + const commits = useRef(null); + useLayoutEffect(() => { + commits.current!.textContent += state + '/' + pending + ' '; + }, [state, pending]); + return
+ {({ pending }) => pending ? 'pending' : 'idle'} +
; +} +export default function Layout({ children }: { children: React.ReactNode }) { + const url = useRouter().url; + return <> + + {children}; +}`, + ); browser = await launchPagesBrowser(); }); @@ -538,6 +574,71 @@ function registerClientTests(getBase: () => string, coverage: 'smoke' | 'full') }, ); + it('keeps the current page from re-rendering while a visit loads', async () => { + const page = await newPage(); + let release = () => {}; + const released = new Promise((resolve) => { + release = resolve; + }); + + try { + await page.route('**/users', async (route) => { + if (route.request().headers().accept === 'application/json') { + await released; + } + await route.continue(); + }); + await page.goto(BASE + '/visit-await'); + await waitForHydration(page); + const renders = await page.evaluate(() => window.__visitAwaitRenders); + + await page.click('nav a[href="/users"]'); + await page.waitForSelector('nav a[href="/users"][data-void-pending]'); + expect(await page.evaluate(() => window.__visitAwaitRenders)).toBe(renders); + + release(); + await page.waitForFunction(() => + document.querySelector('h1')?.textContent?.includes('Users'), + ); + } finally { + release(); + await page.context().close(); + } + }); + + it('hydrates scoped Links and commits pending status together with navigation', async () => { + const page = await newPage(); + const errors: Array = []; + page.on('pageerror', (error) => errors.push(error.message)); + let release = () => {}; + const waiting = new Promise((resolve) => { + release = resolve; + }); + try { + await page.route('**/navigation-status/next', async (route) => { + await waiting; + await route.continue(); + }); + await page.goto(BASE + '/navigation-status'); + await waitForHydration(page); + expect(await page.locator('#scoped a').textContent()).toBe('pending'); + expect(await page.locator('#outer a').textContent()).toBe('idle'); + expect(errors).toEqual([]); + await page.click('#outer a'); + await page.waitForSelector('#outer a[data-void-pending]'); + const commits = await page.locator('#outer output').textContent(); + expect(commits).toContain('loading/true'); + expect(commits).not.toContain('loading/false'); + release(); + await page.waitForURL('**/navigation-status/next'); + await page.waitForSelector('#outer a:not([data-void-pending])'); + expect(await page.locator('#outer output').textContent()).not.toContain('idle/true'); + } finally { + release(); + await page.context().close(); + } + }); + it('router.visit works from an initial layout effect', async () => { const page = await newPage(); const errors: Array = []; diff --git a/packages/react/test/unit/link-status.test.ts b/packages/react/test/unit/link-status.test.ts index 6d0913132..3cbbac88d 100644 --- a/packages/react/test/unit/link-status.test.ts +++ b/packages/react/test/unit/link-status.test.ts @@ -1,11 +1,16 @@ // @vitest-environment happy-dom -import { act, createElement } from 'react'; -import { createRoot } from 'react-dom/client'; -import { expect, it } from 'vite-plus/test'; -import { createSsrRouter } from 'void/pages-client'; +import { act, createElement, Fragment, useLayoutEffect } from 'react'; +import { createRoot, hydrateRoot } from 'react-dom/client'; +import { renderToString } from 'react-dom/server'; +import { expect, it, vi } from 'vite-plus/test'; +import { createSsrRouter, idleNavigationState } from 'void/pages-client'; import type { LinkStatus, NavigationState } from 'void/pages-client'; -import { NavigationContext, RouterContext } from '../../src/runtime/context.ts'; +import { + NavigationContext, + RouterContext, + RouterNavigationContext, +} from '../../src/runtime/context.ts'; import { Link, useLinkStatus } from '../../src/runtime/link.tsx'; import type { LinkProps } from '../../src/runtime/link.tsx'; @@ -58,3 +63,102 @@ it('keeps the status object until current, active or pending changes', () => { act(() => root.unmount()); } }); + +it('re-renders only the Link contents whose pending state a visit changes', () => { + const router = createSsrRouter('/posts'); + const hrefs = ['/posts/1', '/posts/2', '/posts/3']; + const renders = new Map(); + const hookStatuses: Array = []; + function PendingProbe() { + const status = useLinkStatus('/posts/2'); + useLayoutEffect(() => { + hookStatuses.push(status); + }, [status]); + return null; + } + const countedLink = (href: string): LinkProps => ({ + href, + children: () => { + renders.set(href, (renders.get(href) ?? 0) + 1); + return href; + }, + }); + const container = document.createElement('div'); + const root = createRoot(container); + const pendingHrefs = () => + Array.from(container.querySelectorAll('[data-void-pending]'), (el) => el.getAttribute('href')); + const contents = createElement( + Fragment, + null, + createElement(PendingProbe), + hrefs.map((href) => createElement(Link, { key: href, ...countedLink(href) })), + ); + const render = (navigation: NavigationState) => + act(() => { + root.render( + createElement( + RouterContext.Provider, + { value: router }, + createElement(NavigationContext.Provider, { value: navigation }, contents), + ), + ); + }); + try { + render(idleNavigationState()); + render({ state: 'loading', location: new URL('/posts/2', router.url), method: 'GET' }); + expect(pendingHrefs()).toEqual(['/posts/2']); + expect(Object.fromEntries(renders)).toEqual({ '/posts/1': 1, '/posts/2': 2, '/posts/3': 1 }); + + render({ state: 'loading', location: new URL('/posts/3', router.url), method: 'GET' }); + render(idleNavigationState()); + expect(pendingHrefs()).toEqual([]); + expect(Object.fromEntries(renders)).toEqual({ '/posts/1': 1, '/posts/2': 3, '/posts/3': 3 }); + expect(hookStatuses.map((status) => status.pending)).toEqual([false, true, false]); + } finally { + act(() => root.unmount()); + } +}); + +it('hydrates Links as the server rendered them while a visit is loading', () => { + const router = createSsrRouter('/posts'); + const props: LinkProps = { href: '/posts/2', children: 'Post 2' }; + const container = document.createElement('div'); + container.innerHTML = renderToString( + createElement(RouterContext.Provider, { value: router }, createElement(Link, props)), + ); + const navigation: NavigationState = { + state: 'loading', + location: new URL('/posts/2', router.url), + method: 'GET', + }; + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + const recoverableErrors: Array = []; + let root: ReturnType | undefined; + try { + act(() => { + root = hydrateRoot( + container, + createElement( + RouterContext.Provider, + { value: router }, + createElement( + RouterNavigationContext.Provider, + { value: navigation }, + createElement( + NavigationContext.Provider, + { value: navigation }, + createElement(Link, props), + ), + ), + ), + { onRecoverableError: (error) => recoverableErrors.push(error) }, + ); + }); + expect(recoverableErrors).toEqual([]); + expect(consoleError).not.toHaveBeenCalled(); + expect(container.querySelector('a')?.hasAttribute('data-void-pending')).toBe(true); + } finally { + consoleError.mockRestore(); + act(() => root?.unmount()); + } +}); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 3e30f079b..62d0a5f0e 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -39,6 +39,7 @@ export { prefetchLink, resolveLink, getResolvedLinkStatus, + matchResolvedLink, type BaseLinkProps, type LinkActiveAttributes, type LinkActiveMatch, @@ -47,6 +48,7 @@ export { type LinkPrefetchValue, type LinkPrefetchStrategy, type LinkStatus, + type LinkStatusMatch, type LinkStatusOptions, type ResolvedLink, } from './link.ts'; diff --git a/packages/void/src/pages/link.ts b/packages/void/src/pages/link.ts index 881ad6972..6c31d9b8b 100644 --- a/packages/void/src/pages/link.ts +++ b/packages/void/src/pages/link.ts @@ -201,16 +201,36 @@ export function getResolvedLinkStatus( link: ResolvedLink, match: LinkActiveMatch = 'exact', ): LinkStatus { + const status = matchResolvedLink(router, link, match); + return { current: status.current, active: status.active, pending: status.pending(navigation) }; +} + +/** The current and active state of a resolved link, and a check for its pending state. */ +export type LinkStatusMatch = { + readonly current: boolean; + readonly active: boolean; + /** Matches without parsing URLs, so adapters can call it for every navigation update. */ + pending(navigation: NavigationState | null | undefined): boolean; +}; + +const NEVER_PENDING = () => false; + +/** Resolves the link against the current page once, for adapters that track pending separately. */ +export function matchResolvedLink( + router: VoidRouter | null | undefined, + link: ResolvedLink, + match: LinkActiveMatch = 'exact', +): LinkStatusMatch { const current = router?.url; const target = current && resolveSameOrigin(link.href, current); if (!current || !target) { - return { current: false, active: false, pending: false }; + return { current: false, active: false, pending: NEVER_PENDING }; } const active = link.isGet ? matchActive(current, target, match) : undefined; return { current: active === 'current', active: active !== undefined, - pending: matchPending(navigation, link.method, target), + pending: (navigation) => matchPending(navigation, link.method, target), }; } diff --git a/playground/react-pages/pages/visit-await.tsx b/playground/react-pages/pages/visit-await.tsx index c4de5c9e5..e682cae4d 100644 --- a/playground/react-pages/pages/visit-await.tsx +++ b/playground/react-pages/pages/visit-await.tsx @@ -4,12 +4,18 @@ import type { Props } from './visit-await.server.ts'; declare global { interface Window { __visitAwaitObserved?: string | null; + __visitAwaitRenders?: number; } } export default function VisitAwaitPage({ title }: Props) { const router = useRouter(); + if (typeof window !== 'undefined') { + // oxlint-disable-next-line react-hooks-js/immutability -- The client test counts this page's renders. + window.__visitAwaitRenders = (window.__visitAwaitRenders ?? 0) + 1; + } + return (

{title}