Unverified Commit ec4f96c9 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Simplify the App and Component handling in render (#36395)

Make the render procedure of `App` and `Component` more explict and clear
parent 42c01ddc
...@@ -41,16 +41,13 @@ export default class Error<P = {}> extends React.Component<P & ErrorProps> { ...@@ -41,16 +41,13 @@ export default class Error<P = {}> extends React.Component<P & ErrorProps> {
return ( return (
<div style={styles.error}> <div style={styles.error}>
{/* TODO: remove this once RSC supports next/head */} <Head>
{!process.env.__NEXT_RSC && ( <title>
<Head> {statusCode
<title> ? `${statusCode}: ${title}`
{statusCode : 'Application error: a client-side exception has occurred'}
? `${statusCode}: ${title}` </title>
: 'Application error: a client-side exception has occurred'} </Head>
</title>
</Head>
)}
<div> <div>
<style <style
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
......
...@@ -18,7 +18,7 @@ import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plug ...@@ -18,7 +18,7 @@ import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plug
import type { BaseNextRequest, BaseNextResponse } from './base-http' import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { PayloadOptions } from './send-payload' import type { PayloadOptions } from './send-payload'
import { join, resolve } from 'path' import pathMod from '../shared/lib/isomorphic/path'
import { parse as parseQs } from 'querystring' import { parse as parseQs } from 'querystring'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/load-custom-routes' import { getRedirectStatus } from '../lib/load-custom-routes'
...@@ -66,6 +66,8 @@ import { PrerenderManifest } from '../build' ...@@ -66,6 +66,8 @@ import { PrerenderManifest } from '../build'
import { ImageConfigComplete } from '../shared/lib/image-config' import { ImageConfigComplete } from '../shared/lib/image-config'
import { replaceBasePath } from './router-utils' import { replaceBasePath } from './router-utils'
const { join, resolve } = pathMod
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
query: NextParsedUrlQuery query: NextParsedUrlQuery
......
...@@ -196,20 +196,19 @@ function enhanceComponents( ...@@ -196,20 +196,19 @@ function enhanceComponents(
} }
} }
function renderFlight(AppMod: any, ComponentMod: any, props: any) { function renderPageTree(
const isServerComponent = !!ComponentMod.__next_rsc__ App: any,
const App = interopDefault(AppMod) Component: any,
const Component = interopDefault(ComponentMod) props: any,
const AppServer = isServerComponent isServerComponent: boolean
? (App as React.ComponentType) ) {
: React.Fragment
const { router: _, ...rest } = props const { router: _, ...rest } = props
if (isServerComponent) { if (isServerComponent) {
return ( return (
<AppServer> <App>
<Component {...rest} /> <Component {...rest} />
</AppServer> </App>
) )
} }
...@@ -395,6 +394,7 @@ const useFlightResponse = createFlightHook() ...@@ -395,6 +394,7 @@ const useFlightResponse = createFlightHook()
// Create the wrapper component for a Flight stream. // Create the wrapper component for a Flight stream.
function createServerComponentRenderer( function createServerComponentRenderer(
App: any,
ComponentMod: any, ComponentMod: any,
{ {
cachePrefix, cachePrefix,
...@@ -414,7 +414,7 @@ function createServerComponentRenderer( ...@@ -414,7 +414,7 @@ function createServerComponentRenderer(
globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__ globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__
const Component = interopDefault(ComponentMod) const Component = interopDefault(ComponentMod)
function ServerComponentWrapper({ App, router, ...props }: any) { function ServerComponentWrapper({ router, ...props }: any) {
const id = (React as any).useId() const id = (React as any).useId()
const reqStream: ReadableStream<Uint8Array> = renderToReadableStream( const reqStream: ReadableStream<Uint8Array> = renderToReadableStream(
...@@ -489,7 +489,7 @@ export async function renderToHTML( ...@@ -489,7 +489,7 @@ export async function renderToHTML(
reactRoot, reactRoot,
runtime: globalRuntime, runtime: globalRuntime,
ComponentMod, ComponentMod,
AppMod: AppClientMod, AppMod,
AppServerMod, AppServerMod,
} = renderOpts } = renderOpts
...@@ -503,11 +503,12 @@ export async function renderToHTML( ...@@ -503,11 +503,12 @@ export async function renderToHTML(
!!serverComponentManifest && !!serverComponentManifest &&
!!ComponentMod.__next_rsc__?.server !!ComponentMod.__next_rsc__?.server
// Component will be wrapped by ServerComponentWrapper for RSC
let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) = let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =
renderOpts.Component renderOpts.Component
const OriginComponent = Component
const AppMod = isServerComponent ? AppServerMod : AppClientMod const App = interopDefault(isServerComponent ? AppServerMod : AppMod)
const App = interopDefault(AppMod)
let serverComponentsInlinedTransformStream: TransformStream< let serverComponentsInlinedTransformStream: TransformStream<
Uint8Array, Uint8Array,
...@@ -522,7 +523,7 @@ export async function renderToHTML( ...@@ -522,7 +523,7 @@ export async function renderToHTML(
if (isServerComponent) { if (isServerComponent) {
serverComponentsInlinedTransformStream = new TransformStream() serverComponentsInlinedTransformStream = new TransformStream()
const search = urlQueryToSearchParams(query).toString() const search = urlQueryToSearchParams(query).toString()
Component = createServerComponentRenderer(ComponentMod, { Component = createServerComponentRenderer(App, ComponentMod, {
cachePrefix: pathname + (search ? `?${search}` : ''), cachePrefix: pathname + (search ? `?${search}` : ''),
inlinedTransformStream: serverComponentsInlinedTransformStream, inlinedTransformStream: serverComponentsInlinedTransformStream,
staticTransformStream: serverComponentsPageDataTransformStream, staticTransformStream: serverComponentsPageDataTransformStream,
...@@ -743,7 +744,12 @@ export async function renderToHTML( ...@@ -743,7 +744,12 @@ export async function renderToHTML(
AppTree: (props: any) => { AppTree: (props: any) => {
return ( return (
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
{renderFlight(AppMod, ComponentMod, { ...props, router })} {renderPageTree(
App,
OriginComponent,
{ ...props, router },
isServerComponent
)}
</AppContainerWithIsomorphicFiberStructure> </AppContainerWithIsomorphicFiberStructure>
) )
}, },
...@@ -1235,10 +1241,15 @@ export async function renderToHTML( ...@@ -1235,10 +1241,15 @@ export async function renderToHTML(
if (renderServerComponentData) { if (renderServerComponentData) {
return new RenderResult( return new RenderResult(
renderToReadableStream( renderToReadableStream(
renderFlight(AppMod, ComponentMod, { renderPageTree(
...props.pageProps, App,
...serverComponentProps, OriginComponent,
}), {
...props.pageProps,
...serverComponentProps,
},
isServerComponent
),
serverComponentManifest serverComponentManifest
).pipeThrough(createBufferedTransformStream()) ).pipeThrough(createBufferedTransformStream())
) )
...@@ -1323,13 +1334,10 @@ export async function renderToHTML( ...@@ -1323,13 +1334,10 @@ export async function renderToHTML(
} }
async function documentInitialProps( async function documentInitialProps(
renderShell?: ({ renderShell?: (
EnhancedApp, _App: AppType,
EnhancedComponent, _Component: NextComponentType
}: { ) => Promise<void>
EnhancedApp?: AppType
EnhancedComponent?: NextComponentType
}) => Promise<void>
) { ) {
const renderPage: RenderPage = ( const renderPage: RenderPage = (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
...@@ -1337,7 +1345,7 @@ export async function renderToHTML( ...@@ -1337,7 +1345,7 @@ export async function renderToHTML(
if (ctx.err && ErrorDebug) { if (ctx.err && ErrorDebug) {
// Always start rendering the shell even if there's an error. // Always start rendering the shell even if there's an error.
if (renderShell) { if (renderShell) {
renderShell({}) renderShell(App, Component)
} }
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
...@@ -1358,7 +1366,7 @@ export async function renderToHTML( ...@@ -1358,7 +1366,7 @@ export async function renderToHTML(
enhanceComponents(options, App, Component) enhanceComponents(options, App, Component)
if (renderShell) { if (renderShell) {
return renderShell({ EnhancedApp, EnhancedComponent }).then(() => { return renderShell(EnhancedApp, EnhancedComponent).then(() => {
// When using concurrent features, we don't have or need the full // When using concurrent features, we don't have or need the full
// html so it's fine to return nothing here. // html so it's fine to return nothing here.
return { html: '', head } return { html: '', head }
...@@ -1368,11 +1376,12 @@ export async function renderToHTML( ...@@ -1368,11 +1376,12 @@ export async function renderToHTML(
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
<Body> <Body>
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
<EnhancedApp {renderPageTree(
Component={EnhancedComponent} EnhancedApp,
router={router} EnhancedComponent,
{...props} { ...props, router },
/> false
)}
</AppContainerWithIsomorphicFiberStructure> </AppContainerWithIsomorphicFiberStructure>
</Body> </Body>
) )
...@@ -1396,13 +1405,10 @@ export async function renderToHTML( ...@@ -1396,13 +1405,10 @@ export async function renderToHTML(
return { docProps, documentCtx } return { docProps, documentCtx }
} }
const renderContent = ({ const renderContent = (_App: AppType, _Component: NextComponentType) => {
EnhancedApp, const EnhancedApp = _App || App
EnhancedComponent, const EnhancedComponent = _Component || Component
}: {
EnhancedApp?: AppType
EnhancedComponent?: NextComponentType
} = {}) => {
return ctx.err && ErrorDebug ? ( return ctx.err && ErrorDebug ? (
<Body> <Body>
<ErrorDebug error={ctx.err} /> <ErrorDebug error={ctx.err} />
...@@ -1410,16 +1416,12 @@ export async function renderToHTML( ...@@ -1410,16 +1416,12 @@ export async function renderToHTML(
) : ( ) : (
<Body> <Body>
<AppContainerWithIsomorphicFiberStructure> <AppContainerWithIsomorphicFiberStructure>
{isServerComponent {renderPageTree(
? React.createElement(EnhancedComponent || Component, { EnhancedApp,
App: EnhancedApp || App, EnhancedComponent,
...props.pageProps, { ...(isServerComponent ? props.pageProps : props), router },
}) isServerComponent
: React.createElement(EnhancedApp || App, { )}
...props,
Component: EnhancedComponent || Component,
router,
})}
</AppContainerWithIsomorphicFiberStructure> </AppContainerWithIsomorphicFiberStructure>
</Body> </Body>
) )
...@@ -1442,7 +1444,7 @@ export async function renderToHTML( ...@@ -1442,7 +1444,7 @@ export async function renderToHTML(
styles: docProps.styles, styles: docProps.styles,
} }
} else { } else {
const content = renderContent() const content = renderContent(App, Component)
// for non-concurrent rendering we need to ensure App is rendered // for non-concurrent rendering we need to ensure App is rendered
// before _document so that updateHead is called/collected before // before _document so that updateHead is called/collected before
// rendering _document's head // rendering _document's head
...@@ -1465,14 +1467,11 @@ export async function renderToHTML( ...@@ -1465,14 +1467,11 @@ export async function renderToHTML(
allReady?: Promise<void> | undefined allReady?: Promise<void> | undefined
} }
const renderShell = async ({ const renderShell = async (
EnhancedApp, EnhancedApp: AppType,
EnhancedComponent, EnhancedComponent: NextComponentType
}: { ) => {
EnhancedApp?: AppType const content = renderContent(EnhancedApp, EnhancedComponent)
EnhancedComponent?: NextComponentType
} = {}) => {
const content = renderContent({ EnhancedApp, EnhancedComponent })
renderStream = await renderToInitialStream({ renderStream = await renderToInitialStream({
ReactDOMServer, ReactDOMServer,
element: content, element: content,
...@@ -1555,7 +1554,7 @@ export async function renderToHTML( ...@@ -1555,7 +1554,7 @@ export async function renderToHTML(
documentInitialPropsRes = await documentInitialProps(renderShell) documentInitialPropsRes = await documentInitialProps(renderShell)
if (documentInitialPropsRes === null) return null if (documentInitialPropsRes === null) return null
} else { } else {
await renderShell() await renderShell(App, Component)
documentInitialPropsRes = {} documentInitialPropsRes = {}
} }
......
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