Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/react/src/runtime/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export const ParamsContext: Context<Record<string, string> | null> = createConte
export const RouterContext: Context<VoidRouter | null> = createContext<VoidRouter | null>(null);
export const NavigationContext: Context<NavigationState> =
createContext<NavigationState>(idleNavigationState());
// Identifies the router's own value when a server-rendered subtree hydrates during a visit.
export const RouterNavigationContext: Context<NavigationState | null> =
createContext<NavigationState | null>(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<Record<string, unknown>> = createContext<
Expand Down
108 changes: 64 additions & 44 deletions packages/react/src/runtime/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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',
Expand All @@ -80,7 +96,6 @@ export function Link({
...rest
}: LinkProps): JSX.Element {
const router = useContext(RouterContext);
const navigation = useContext(NavigationContext);
const elementRef = useRef<HTMLElement | null>(null);
const setElementRef = useCallback((element: HTMLElement | null) => {
elementRef.current = element;
Expand All @@ -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(
Expand Down Expand Up @@ -267,32 +279,40 @@ export function Link({
[style],
);

const content = typeof children === 'function' ? children(status) : children;
if (link.isGet) {
return (
<a
ref={setElementRef}
href={link.href}
style={resolvedStyle}
{...attributes}
{...rest}
{...eventHandlers}
>
{content}
</a>
);
}

return (
<button
ref={setElementRef}
type="button"
style={resolvedStyle}
{...attributes}
{...rest}
{...eventHandlers}
>
{content}
</button>
<LinkContent
match={statusMatch}
render={(status) => {
const attributes = linkStatusAttributes(status);
const content = typeof children === 'function' ? children(status) : children;
if (link.isGet) {
return (
<a
ref={setElementRef}
href={link.href}
style={resolvedStyle}
{...attributes}
{...rest}
{...eventHandlers}
>
{content}
</a>
);
}

return (
<button
ref={setElementRef}
type="button"
style={resolvedStyle}
{...attributes}
{...rest}
{...eventHandlers}
>
{content}
</button>
);
}}
/>
);
}
38 changes: 23 additions & 15 deletions packages/react/src/runtime/pages-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import { setActionRouter } from './action.ts';
import {
ErrorsContext,
NavigationContext,
RouterNavigationContext,
ParamsContext,
RouterContext,
SharedContext,
Expand Down Expand Up @@ -340,7 +341,8 @@ function createRouter(engine: PageNavigationEngine<ReactComponent>): 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,
Expand Down Expand Up @@ -445,7 +447,7 @@ function RouteResource({
),
),
);
}
});

function startViewTransition(
resource: ReactPageResource,
Expand Down Expand Up @@ -789,6 +791,8 @@ function App({
};
}, [isTransitionPending, lastNavigation, state.navigation]);

const onRouteFailure = useCallback((url: string) => engine.flush(url), [engine]);

const routerValue = useMemo(
() =>
createRouterFacade(router, () =>
Expand All @@ -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,
}),
),
),
),
);
Expand Down
21 changes: 18 additions & 3 deletions packages/react/src/runtime/use-navigation.ts
Original file line number Diff line number Diff line change
@@ -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;
}
101 changes: 101 additions & 0 deletions packages/react/test/integration/react-pages-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ declare global {
interface Window {
__SPA_MARKER?: boolean;
__visitAwaitObserved?: string | null;
__visitAwaitRenders?: number;
__hashNavigationReady?: boolean;
__headRefs?: {
font: Element | null;
Expand Down Expand Up @@ -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 <h1>Arrived</h1>; }',
);
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<HTMLOutputElement>(null);
useLayoutEffect(() => {
commits.current!.textContent += state + '/' + pending + ' ';
}, [state, pending]);
return <section id={id}><output ref={commits} /><Link href={href} prefetch={false}>
{({ pending }) => pending ? 'pending' : 'idle'}
</Link></section>;
}
export default function Layout({ children }: { children: React.ReactNode }) {
const url = useRouter().url;
return <><Reader id="outer" /><NavigationContext.Provider
value={{ state: 'loading', method: 'GET', location: new URL(href, url) }}>
<Reader id="scoped" />
</NavigationContext.Provider>{children}</>;
}`,
);
browser = await launchPagesBrowser();
});

Expand Down Expand Up @@ -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<void>((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<string> = [];
page.on('pageerror', (error) => errors.push(error.message));
let release = () => {};
const waiting = new Promise<void>((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<string> = [];
Expand Down
Loading