Reuse prerendered variant shells for partially resolved routes

parent 21336477
...@@ -317,13 +317,14 @@ export function createAppPageEntrypoint({ ...@@ -317,13 +317,14 @@ export function createAppPageEntrypoint({
const outputPathname = toOutputPathname(resolvedPathname) const outputPathname = toOutputPathname(resolvedPathname)
// Select the matched shell's combination-specific entry. The canonical page
// can name a broader fallback.
const matchedVariantsPrerenderInfo = matchedVariants const matchedVariantsPrerenderInfo = matchedVariants
? prerenderManifest.dynamicRoutes[toOutputPathname(normalizedSrcPage)] ? prerenderManifest.dynamicRoutes[
toOutputPathname(prerenderMatch?.source ?? normalizedSrcPage)
]
: undefined : undefined
// This reads the entry directly by key. Route matching here runs on the
// pathname with the prefix already removed, while this entry's key and
// `routeRegex` describe the prefixed path, so matching would not find it.
const prerenderInfo = const prerenderInfo =
matchedVariantsPrerenderInfo ?? prerenderMatch?.route ?? null matchedVariantsPrerenderInfo ?? prerenderMatch?.route ?? null
......
import { Suspense, type JSX } from 'react'
import { lang } from 'next/root-params'
import { connection } from 'next/server'
import { PHASE_PRODUCTION_BUILD } from 'next/constants'
import { theme } from '../../../variants'
export function unstable_generateStaticVariants(): [typeof theme, string][][] {
return [[[theme, 'dark']], [[theme, 'light']]]
}
async function VariantShell(): Promise<JSX.Element> {
const language = await lang()
const currentTheme = await theme()
const phase =
process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD ? 'buildtime' : 'runtime'
return (
<p id="variant-shell" data-language={language} data-theme={currentTheme}>
{`shell:${language}:${currentTheme}:${phase}`}
</p>
)
}
async function Slug({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}): Promise<JSX.Element> {
await connection()
const { slug } = await params
return <p id="slug">{slug}</p>
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; slug: string }>
}): JSX.Element {
return (
<>
<Suspense fallback={<p id="variant-fallback">pending variant</p>}>
<VariantShell />
</Suspense>
<Suspense fallback={<p id="slug-fallback">pending slug</p>}>
<Slug params={params} />
</Suspense>
</>
)
}
import type { JSX, ReactNode } from 'react'
import { lang } from 'next/root-params'
export function generateStaticParams(): Array<{ lang: string }> {
return [{ lang: 'en' }, { lang: 'de' }]
}
export default async function RootLayout({
children,
}: {
children: ReactNode
}): Promise<JSX.Element> {
const language = await lang()
return (
<html lang={language}>
<body>
<p id="layout-language">{language}</p>
{children}
</body>
</html>
)
}
import type { JSX } from 'react'
import { lang } from 'next/root-params'
import { LinkAccordion } from '../link-accordion'
export default async function Page(): Promise<JSX.Element> {
return <LinkAccordion href={`/${await lang()}/prefetched`} />
}
'use client'
import Link from 'next/link'
import { useState, type JSX } from 'react'
export function LinkAccordion({ href }: { href: string }): JSX.Element {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? <Link href={href}>Partial shell</Link> : null}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
partialPrefetching: true,
experimental: {
variants: true,
},
}
if (process.env.BASE_PATH) {
nextConfig.basePath = process.env.BASE_PATH
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
export const proxy = wrapProxy({ '/[lang]/[slug]': [theme] })
export const config = {
matcher: ['/((?!_next/|favicon\\.ico$).*)'],
}
process.env.BASE_PATH = '/base'
require('./variants-partial-shells.test')
import { nextTestSetup } from 'e2e-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
import { load } from 'cheerio'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { basePath, url } from '../variants/base-path'
// The assertions distinguish build-time preludes from request-time rendering.
// TODO(variants): Add deployment coverage for partially resolved shells.
// @force-gate start && turbopack
describe('Variants on partially resolved shells', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
env: {
BASE_PATH: basePath,
},
})
if (skipped) {
return
}
async function fetchShell(pathname: string, theme: string) {
const [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(
async () => {
const response = await next.fetch(url(pathname), {
headers: { cookie: `theme=${theme}` },
})
expect(response.status).toBe(200)
if (!response.body) {
throw new Error('Expected a streamed response body.')
}
return response.body
}
)
expect(dynamicPart).not.toBe('')
return { static$: load(staticPart), dynamic$: load(dynamicPart) }
}
it('should serve the build-time shell for each resolved root and combination', async () => {
for (const language of ['de', 'en']) {
for (const theme of ['dark', 'light']) {
for (const slug of ['first', 'second']) {
const { static$, dynamic$ } = await fetchShell(
`/${language}/${slug}`,
theme
)
expect(static$('html').attr('lang')).toBe(language)
expect(static$('#layout-language').text()).toBe(language)
expect(static$('#variant-shell').text()).toBe(
`shell:${language}:${theme}:buildtime`
)
expect(static$('#variant-fallback').length).toBe(0)
expect(static$('#slug-fallback').text()).toBe('pending slug')
expect(static$('#slug').length).toBe(0)
expect(dynamic$('#slug').text()).toBe(slug)
}
}
}
})
it('should leave an undeclared combination in the dynamic response', async () => {
const { static$, dynamic$ } = await fetchShell('/en/undeclared', 'blue')
expect(static$('#layout-language').text()).toBe('en')
expect(static$('#variant-shell').length).toBe(0)
expect(static$('#variant-fallback').text()).toBe('pending variant')
expect(dynamic$('#variant-shell').text()).toBe('shell:en:blue:runtime')
expect(dynamic$('#slug').text()).toBe('undeclared')
})
it('should prefetch the build-time variant shell before resolving the slug', async () => {
for (const language of ['de', 'en']) {
for (const theme of ['dark', 'light']) {
const pathname = `/${language}/prefetched`
let page: Playwright.Page | undefined
const browser = await next.browser(url(`/${language}`), {
async beforePageLoad(capturedPage: Playwright.Page) {
page = capturedPage
await capturedPage
.context()
.addCookies([{ name: 'theme', value: theme, url: next.url }])
},
})
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
if (!page) {
throw new Error('The page was not captured before it loaded.')
}
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${pathname}"]`)
.click()
}, [
{ includes: `shell:${language}:${theme}:buildtime`, kind: 'static' },
{ includes: `shell:${language}:${theme}:runtime`, block: 'reject' },
{ includes: '"id":"slug","children":"prefetched"', block: 'reject' },
])
await act(
async () => {
await browser.elementByCss(`a[href="${url(pathname)}"]`).click()
},
{ includes: '"id":"slug","children":"prefetched"' }
)
expect(await browser.elementByCss('#slug').text()).toBe('prefetched')
expect(
await browser
.elementByCss('#variant-shell')
.getAttribute('data-language')
).toBe(language)
expect(
await browser
.elementByCss('#variant-shell')
.getAttribute('data-theme')
).toBe(theme)
expect(await browser.eval('location.pathname')).toBe(url(pathname))
}
}
})
})
function defer(callback: () => Promise<void>) {
return { [Symbol.asyncDispose]: callback }
}
'use variants'
import { unstable_variant } from 'next/variants'
export const theme = unstable_variant(
(request) => request.cookies.get('theme')?.value ?? 'light',
'theme@variants.ts'
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment