Unverified Commit ad981783 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Add render prop support to `<Main>` (#30156)

Adds support for render props to the `<Main>` component, when using the [functional custom `Document`](https://github.com/vercel/next.js/pull/28515) style. This allows you to write something like this:

```tsx
export default function Document() {
  const jsxStyleRegistry = createStyleRegistry()
  return (
    <Html>
      <Head />
      <body>
        <Main>
          {content => (
            <StyledJsxWrapper registry={jsxStyleRegistry}>
              {content}
            </StyledJsxWrapper>
          )}
        </Main>
        <NextScript />
      </body>
    </Html>
  )
}
```

In functional document components, this allows the `<App>` to be wrapped, similar to `enhanceApp` (which is only available via `getInitialProps`, which is not supported by functional document components). The primary use for this is for integrating with 3rd party CSS-in-JS libraries, allowing them to attach an `useFlush` handler to [support React 18](https://github.com/reactwg/react-18/discussions/110):

```tsx
import { unstable_useFlush as useFlush } from 'next/document'

export default function StyledJsxWrapper({ children, registry }) {
  useFlush(() => {
    /* ... */
  })
  return (
    <StyleRegistry registry={registry}>
      {children}
    </StyleRegistry>
  )
}
```

Support for `useFlush` will be added in a follow up PR.
parent f8e66610
import React, { Component, ReactElement, ReactNode, useContext } from 'react' import React, { Component, ReactElement, ReactNode, useContext } from 'react'
import { import { OPTIMIZED_FONT_PROVIDERS } from '../shared/lib/constants'
BODY_RENDER_TARGET,
OPTIMIZED_FONT_PROVIDERS,
} from '../shared/lib/constants'
import { import {
DocumentContext, DocumentContext,
DocumentInitialProps, DocumentInitialProps,
...@@ -763,13 +760,18 @@ export class Head extends Component< ...@@ -763,13 +760,18 @@ export class Head extends Component<
} }
} }
export function Main() { export function Main({
const { inAmpMode, docComponentsRendered } = useContext(HtmlContext) children,
}: {
children?: (content: JSX.Element) => JSX.Element
}) {
const { inAmpMode, docComponentsRendered, useMainContent } =
useContext(HtmlContext)
const content = useMainContent(children)
docComponentsRendered.Main = true docComponentsRendered.Main = true
if (inAmpMode) return <>{BODY_RENDER_TARGET}</> if (inAmpMode) return content
return <div id="__next">{BODY_RENDER_TARGET}</div> return <div id="__next">{content}</div>
} }
export class NextScript extends Component<OriginProps> { export class NextScript extends Component<OriginProps> {
......
...@@ -20,7 +20,6 @@ import { GetServerSideProps, GetStaticProps, PreviewData } from '../types' ...@@ -20,7 +20,6 @@ import { GetServerSideProps, GetStaticProps, PreviewData } from '../types'
import { isInAmpMode } from '../shared/lib/amp' import { isInAmpMode } from '../shared/lib/amp'
import { AmpStateContext } from '../shared/lib/amp-context' import { AmpStateContext } from '../shared/lib/amp-context'
import { import {
BODY_RENDER_TARGET,
SERVER_PROPS_ID, SERVER_PROPS_ID,
STATIC_PROPS_ID, STATIC_PROPS_ID,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
...@@ -935,6 +934,20 @@ export async function renderToHTML( ...@@ -935,6 +934,20 @@ export async function renderToHTML(
} }
} }
const appWrappers: Array<(content: JSX.Element) => JSX.Element> = []
const getWrappedApp = (app: JSX.Element) => {
// Prevent wrappers from reading/writing props by rendering inside an
// opaque component. Wrappers should use context instead.
const InnerApp = () => app
return (
<AppContainer>
{appWrappers.reduce((innerContent, fn) => {
return fn(innerContent)
}, <InnerApp />)}
</AppContainer>
)
}
/** /**
* Rules of Static & Dynamic HTML: * Rules of Static & Dynamic HTML:
* *
...@@ -976,13 +989,13 @@ export async function renderToHTML( ...@@ -976,13 +989,13 @@ export async function renderToHTML(
enhanceComponents(options, App, Component) enhanceComponents(options, App, Component)
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
<AppContainer> getWrappedApp(
<EnhancedApp <EnhancedApp
Component={EnhancedComponent} Component={EnhancedComponent}
router={router} router={router}
{...props} {...props}
/> />
</AppContainer> )
) )
return { html, head } return { html, head }
} }
...@@ -1002,33 +1015,51 @@ export async function renderToHTML( ...@@ -1002,33 +1015,51 @@ export async function renderToHTML(
} }
return { return {
bodyResult: piperFromArray([docProps.html]), bodyResult: () => piperFromArray([docProps.html]),
documentElement: (htmlProps: HtmlProps) => ( documentElement: (htmlProps: HtmlProps) => (
<Document {...htmlProps} {...docProps} /> <Document {...htmlProps} {...docProps} />
), ),
useMainContent: (fn?: (content: JSX.Element) => JSX.Element) => {
if (fn) {
throw new Error(
'The `children` property is not supported by non-functional custom Document components'
)
}
// @ts-ignore
return <next-js-internal-body-render-target />
},
head: docProps.head, head: docProps.head,
headTags: await headTags(documentCtx), headTags: await headTags(documentCtx),
styles: docProps.styles, styles: docProps.styles,
} }
} else { } else {
const content = const bodyResult = async () => {
ctx.err && ErrorDebug ? ( const content =
<ErrorDebug error={ctx.err} /> ctx.err && ErrorDebug ? (
) : ( <ErrorDebug error={ctx.err} />
<AppContainer> ) : (
<App {...props} Component={Component} router={router} /> getWrappedApp(
</AppContainer> <App {...props} Component={Component} router={router} />
) )
)
const bodyResult = concurrentFeatures return concurrentFeatures
? process.browser ? process.browser
? await renderToReadableStream(content) ? await renderToReadableStream(content)
: await renderToNodeStream(content, generateStaticHTML) : await renderToNodeStream(content, generateStaticHTML)
: piperFromArray([ReactDOMServer.renderToString(content)]) : piperFromArray([ReactDOMServer.renderToString(content)])
}
return { return {
bodyResult, bodyResult,
documentElement: () => (Document as any)(), documentElement: () => (Document as any)(),
useMainContent: (fn?: (content: JSX.Element) => JSX.Element) => {
if (fn) {
appWrappers.push(fn)
}
// @ts-ignore
return <next-js-internal-body-render-target />
},
head, head,
headTags: [], headTags: [],
styles: jsxStyleRegistry.styles(), styles: jsxStyleRegistry.styles(),
...@@ -1056,8 +1087,8 @@ export async function renderToHTML( ...@@ -1056,8 +1087,8 @@ export async function renderToHTML(
} }
const hybridAmp = ampState.hybrid const hybridAmp = ampState.hybrid
const docComponentsRendered: DocumentProps['docComponentsRendered'] = {} const docComponentsRendered: DocumentProps['docComponentsRendered'] = {}
const { const {
assetPrefix, assetPrefix,
buildId, buildId,
...@@ -1123,6 +1154,7 @@ export async function renderToHTML( ...@@ -1123,6 +1154,7 @@ export async function renderToHTML(
head: documentResult.head, head: documentResult.head,
headTags: documentResult.headTags, headTags: documentResult.headTags,
styles: documentResult.styles, styles: documentResult.styles,
useMainContent: documentResult.useMainContent,
useMaybeDeferContent, useMaybeDeferContent,
} }
...@@ -1181,20 +1213,20 @@ export async function renderToHTML( ...@@ -1181,20 +1213,20 @@ export async function renderToHTML(
} }
} }
const renderTargetIdx = documentHTML.indexOf(BODY_RENDER_TARGET) const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split(
/<next-js-internal-body-render-target><\/next-js-internal-body-render-target>/
)
const prefix: Array<string> = [] const prefix: Array<string> = []
prefix.push('<!DOCTYPE html>') prefix.push('<!DOCTYPE html>')
prefix.push(documentHTML.substring(0, renderTargetIdx)) prefix.push(renderTargetPrefix)
if (inAmpMode) { if (inAmpMode) {
prefix.push('<!-- __NEXT_DATA__ -->') prefix.push('<!-- __NEXT_DATA__ -->')
} }
let pipers: Array<NodeWritablePiper> = [ let pipers: Array<NodeWritablePiper> = [
piperFromArray(prefix), piperFromArray(prefix),
documentResult.bodyResult, await documentResult.bodyResult(),
piperFromArray([ piperFromArray([renderTargetSuffix]),
documentHTML.substring(renderTargetIdx + BODY_RENDER_TARGET.length),
]),
] ]
const postProcessors: Array<((html: string) => Promise<string>) | null> = ( const postProcessors: Array<((html: string) => Promise<string>) | null> = (
......
...@@ -23,7 +23,6 @@ export const BLOCKED_PAGES = ['/_document', '/_app', '/_error'] ...@@ -23,7 +23,6 @@ export const BLOCKED_PAGES = ['/_document', '/_app', '/_error']
export const CLIENT_PUBLIC_FILES_PATH = 'public' export const CLIENT_PUBLIC_FILES_PATH = 'public'
export const CLIENT_STATIC_FILES_PATH = 'static' export const CLIENT_STATIC_FILES_PATH = 'static'
export const CLIENT_STATIC_FILES_RUNTIME = 'runtime' export const CLIENT_STATIC_FILES_RUNTIME = 'runtime'
export const BODY_RENDER_TARGET = '__NEXT_BODY_RENDER_TARGET__'
export const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__' export const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
// server/middleware-flight-manifest.js // server/middleware-flight-manifest.js
......
...@@ -221,6 +221,7 @@ export type HtmlProps = { ...@@ -221,6 +221,7 @@ export type HtmlProps = {
styles?: React.ReactElement[] | React.ReactFragment styles?: React.ReactElement[] | React.ReactFragment
head?: Array<JSX.Element | null> head?: Array<JSX.Element | null>
useMaybeDeferContent: MaybeDeferContentHook useMaybeDeferContent: MaybeDeferContentHook
useMainContent: (fn?: (content: JSX.Element) => JSX.Element) => JSX.Element
} }
/** /**
......
import { createContext } from 'react'
export default createContext(null)
import { Html, Head, Main, NextScript } from 'next/document'
import Context from '../lib/context'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main>
{(children) => (
<Context.Provider value="from render prop">
{children}
</Context.Provider>
)}
</Main>
<NextScript />
</body>
</Html>
)
}
import { useContext } from 'react'
import Context from '../lib/context'
export default function MainRenderProp() {
const value = useContext(Context)
return <span>{value}</span>
}
/* eslint-env jest */
import { join } from 'path'
import { findPort, launchApp, killApp, renderViaHTTP } from 'next-test-utils'
const appDir = join(__dirname, '..')
let appPort
let app
describe('Functional Custom Document', () => {
describe('development mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
it('supports render props', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/<span>from render prop<\/span>/)
})
})
})
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