Makes the first render match the prerendered HTML
Search values, the 404 buttons and the footer year now apply after hydration. The e-mail address stays out of the HTML behind a placeholder, and all review texts are in the page, so crawlers can read them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import type { ReactElement, ReactNode } from 'react';
|
||||
import { ChakraProvider } from '@chakra-ui/react';
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRoute,
|
||||
createRootRoute,
|
||||
createRouter,
|
||||
HeadContent,
|
||||
RouterContextProvider,
|
||||
RouterProvider,
|
||||
rootRouteId,
|
||||
} from '@tanstack/react-router';
|
||||
import { act } from '@testing-library/react';
|
||||
import { hydrateRoot } from 'react-dom/client';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { afterEach } from 'vitest';
|
||||
import { routerOptions } from '../router';
|
||||
import system from '../theme';
|
||||
|
||||
// Roots still mounted at the end of a test: Testing Library does not know them
|
||||
const mounted = new Set<() => void>();
|
||||
afterEach(() => {
|
||||
for (const unmount of [...mounted]) unmount();
|
||||
});
|
||||
|
||||
// Plays what the browser does with a prerendered page: the server markup goes
|
||||
// into a container and React hydrates it. `errors` collects what React
|
||||
// reports as a mismatch (it recovers by client rendering and calls
|
||||
// onRecoverableError), so tests can state that there was none (BR-HYD-20).
|
||||
// The first render of the hydrating pass uses the server snapshots; the
|
||||
// effects and store updates that follow run inside act.
|
||||
export function hydrate(ui: ReactElement, markup = renderToString(ui)) {
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = markup;
|
||||
document.body.append(container);
|
||||
const errors: unknown[] = [];
|
||||
let root!: ReturnType<typeof hydrateRoot>;
|
||||
act(() => {
|
||||
root = hydrateRoot(container, ui, {
|
||||
onRecoverableError: (error) => errors.push(error),
|
||||
});
|
||||
});
|
||||
const unmount = () => {
|
||||
mounted.delete(unmount);
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
};
|
||||
mounted.add(unmount);
|
||||
return { container, errors, unmount };
|
||||
}
|
||||
|
||||
export { renderToString };
|
||||
|
||||
// A server router at the path of the prerendered file, a browser router at
|
||||
// the URL the visitor opened: `/404` for the 404 page, the page itself with
|
||||
// the query stripped for the others. Same test shell as renderApp.
|
||||
const TestShell = ({ children }: { children: ReactNode }) => (
|
||||
<>
|
||||
<HeadContent />
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
async function appRouterAt(path: string) {
|
||||
const router = createRouter({
|
||||
...routerOptions(),
|
||||
history: createMemoryHistory({ initialEntries: [path] }),
|
||||
});
|
||||
const rootOptions = router.routesById[rootRouteId].options as {
|
||||
shellComponent?: typeof TestShell;
|
||||
};
|
||||
rootOptions.shellComponent = TestShell;
|
||||
await router.load();
|
||||
return (
|
||||
<ChakraProvider value={system}>
|
||||
<RouterProvider router={router} />
|
||||
</ChakraProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// renderToString cannot wait for a lazy component: it emits the fallback and a
|
||||
// client-render marker. The real prerender waits, so render again until every
|
||||
// lazy chunk (the form, the dev-only devtools) has loaded.
|
||||
async function serverMarkup(ui: ReactElement) {
|
||||
let markup = renderToString(ui);
|
||||
for (
|
||||
let attempt = 0;
|
||||
markup.includes('<!--$!-->') && attempt < 100;
|
||||
attempt++
|
||||
) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
markup = renderToString(ui);
|
||||
}
|
||||
return markup;
|
||||
}
|
||||
|
||||
export async function hydrateApp(serverPath: string, clientPath: string) {
|
||||
const [server, client] = await Promise.all([
|
||||
appRouterAt(serverPath),
|
||||
appRouterAt(clientPath),
|
||||
]);
|
||||
return hydrate(client, await serverMarkup(server));
|
||||
}
|
||||
|
||||
// A component alone, inside the Chakra theme and a router that matches every
|
||||
// path (like renderWithProviders), for components that only need Link
|
||||
async function withProviders(ui: ReactElement, path: string) {
|
||||
const rootRoute = createRootRoute();
|
||||
const splat = createRoute({ getParentRoute: () => rootRoute, path: '$' });
|
||||
const router = createRouter({
|
||||
routeTree: rootRoute.addChildren([splat]),
|
||||
history: createMemoryHistory({ initialEntries: [path] }),
|
||||
});
|
||||
await router.load();
|
||||
return (
|
||||
<ChakraProvider value={system}>
|
||||
<RouterContextProvider router={router}>{ui}</RouterContextProvider>
|
||||
</ChakraProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// The HTML the prerender would write for this component
|
||||
export async function serverHtml(ui: ReactElement, path = '/') {
|
||||
return serverMarkup(await withProviders(ui, path));
|
||||
}
|
||||
|
||||
// Hydrates that HTML, as the browser does
|
||||
export async function hydratePage(ui: ReactElement, path = '/') {
|
||||
return hydrate(await withProviders(ui, path), await serverHtml(ui, path));
|
||||
}
|
||||
Reference in New Issue
Block a user