Unverified Commit 600e0b3e authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix _document and getInitialProps with React 18 (#35736)

* wip

* update test

* fix _document logic for edge runtime and rsc

* revert deleted file

* fix lint error

* fix

* remove doc gip test

* Revert "remove doc gip test"

This reverts commit a5fd1d7e58463b8dd92df111bc2ae71a34224ad1.

* fix test
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent cae9506f
...@@ -1268,12 +1268,17 @@ export async function renderToHTML( ...@@ -1268,12 +1268,17 @@ export async function renderToHTML(
} }
} }
// We make it a function component to enable streaming. if ((isServerComponent || process.browser) && Document.getInitialProps) {
if (hasConcurrentFeatures && builtinDocument) { if (builtinDocument) {
Document = builtinDocument Document = builtinDocument
} else {
throw new Error(
'`getInitialProps` in Document component is not supported with React Server Components.'
)
}
} }
if (!hasConcurrentFeatures && Document.getInitialProps) { async function documentInitialProps() {
const renderPage: RenderPage = ( const renderPage: RenderPage = (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
): RenderPageResult | Promise<RenderPageResult> => { ): RenderPageResult | Promise<RenderPageResult> => {
...@@ -1323,80 +1328,43 @@ export async function renderToHTML( ...@@ -1323,80 +1328,43 @@ export async function renderToHTML(
throw new Error(message) throw new Error(message)
} }
return { return { docProps, documentCtx }
bodyResult: (suffix: string) => }
streamFromArray([docProps.html, suffix]),
documentElement: (htmlProps: HtmlProps) => (
<Document {...htmlProps} {...docProps} />
),
head: docProps.head,
headTags: await headTags(documentCtx),
styles: docProps.styles,
}
} else {
let bodyResult
const renderContent = () => {
return ctx.err && ErrorDebug ? (
<Body>
<ErrorDebug error={ctx.err} />
</Body>
) : (
<Body>
<AppContainerWithIsomorphicFiberStructure>
{isServerComponent && AppMod.__next_rsc__ ? (
// _app.server.js is used.
<Component {...props.pageProps} router={router} />
) : (
<App {...props} Component={Component} router={router} />
)}
</AppContainerWithIsomorphicFiberStructure>
</Body>
)
}
if (hasConcurrentFeatures) {
let renderStream: any
// We start rendering the shell earlier, before returning the head tags
// to `documentResult`.
const content = renderContent()
renderStream = await renderToInitialStream({
ReactDOMServer,
element: content,
})
bodyResult = async (suffix: string) => { const renderContent = () => {
// this must be called inside bodyResult so appWrappers is return ctx.err && ErrorDebug ? (
// up to date when getWrappedApp is called <Body>
<ErrorDebug error={ctx.err} />
const flushEffectHandler = async () => { </Body>
const allFlushEffects = [ ) : (
styledJsxFlushEffect, <Body>
...(flushEffects || []), <AppContainerWithIsomorphicFiberStructure>
] {isServerComponent && AppMod.__next_rsc__ ? (
const flushEffectStream = await renderToStream({ // _app.server.js is used.
ReactDOMServer, <Component {...props.pageProps} router={router} />
element: ( ) : (
<> <App {...props} Component={Component} router={router} />
{allFlushEffects.map((flushEffect, i) => ( )}
<React.Fragment key={i}>{flushEffect()}</React.Fragment> </AppContainerWithIsomorphicFiberStructure>
))} </Body>
</> )
), }
generateStaticHTML: true,
})
const flushed = await streamToString(flushEffectStream)
return flushed
}
return await continueFromInitialStream({ if (!hasConcurrentFeatures) {
renderStream, if (Document.getInitialProps) {
suffix, const documentInitialPropsRes = await documentInitialProps()
dataStream: serverComponentsInlinedTransformStream?.readable, if (documentInitialPropsRes === null) return null
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures, const { docProps, documentCtx } = documentInitialPropsRes
flushEffectHandler,
}) return {
bodyResult: (suffix: string) =>
streamFromArray([docProps.html, suffix]),
documentElement: (htmlProps: HtmlProps) => (
<Document {...htmlProps} {...docProps} />
),
head: docProps.head,
headTags: await headTags(documentCtx),
styles: docProps.styles,
} }
} else { } else {
const content = renderContent() const content = renderContent()
...@@ -1404,15 +1372,86 @@ export async function renderToHTML( ...@@ -1404,15 +1372,86 @@ export async function renderToHTML(
// 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
const result = ReactDOMServer.renderToString(content) const result = ReactDOMServer.renderToString(content)
bodyResult = (suffix: string) => streamFromArray([result, suffix]) const bodyResult = (suffix: string) => streamFromArray([result, suffix])
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return {
bodyResult,
documentElement: () => (Document as any)(),
head,
headTags: [],
styles,
}
}
} else {
let bodyResult
let renderStream: any
// We start rendering the shell earlier, before returning the head tags
// to `documentResult`.
const content = renderContent()
renderStream = await renderToInitialStream({
ReactDOMServer,
element: content,
})
bodyResult = async (suffix: string) => {
// this must be called inside bodyResult so appWrappers is
// up to date when getWrappedApp is called
const flushEffectHandler = async () => {
const allFlushEffects = [
styledJsxFlushEffect,
...(flushEffects || []),
]
const flushEffectStream = await renderToStream({
ReactDOMServer,
element: (
<>
{allFlushEffects.map((flushEffect, i) => (
<React.Fragment key={i}>{flushEffect()}</React.Fragment>
))}
</>
),
generateStaticHTML: true,
})
const flushed = await streamToString(flushEffectStream)
return flushed
}
return await continueFromInitialStream({
renderStream,
suffix,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures,
flushEffectHandler,
})
} }
const styles = jsxStyleRegistry.styles() const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush() jsxStyleRegistry.flush()
const documentInitialPropsRes =
isServerComponent || process.browser || !Document.getInitialProps
? {}
: await documentInitialProps()
if (documentInitialPropsRes === null) return null
const documentElement = () => {
if (isServerComponent || process.browser) {
return (Document as any)()
}
const { docProps } = (documentInitialPropsRes as any) || {}
return <Document {...htmlProps} {...docProps} />
}
return { return {
bodyResult, bodyResult,
documentElement: () => (Document as any)(), documentElement,
head, head,
headTags: [], headTags: [],
styles, styles,
......
...@@ -17,6 +17,8 @@ describe('styled-components SWC transform', () => { ...@@ -17,6 +17,8 @@ describe('styled-components SWC transform', () => {
}, },
dependencies: { dependencies: {
'styled-components': '5.3.3', 'styled-components': '5.3.3',
react: 'latest',
'react-dom': 'latest',
}, },
}) })
}) })
...@@ -34,6 +36,7 @@ describe('styled-components SWC transform', () => { ...@@ -34,6 +36,7 @@ describe('styled-components SWC transform', () => {
}) })
return foundLog return foundLog
} }
it('should not have hydration mismatch with styled-components transform enabled', async () => { it('should not have hydration mismatch with styled-components transform enabled', async () => {
let browser let browser
try { try {
...@@ -56,4 +59,14 @@ describe('styled-components SWC transform', () => { ...@@ -56,4 +59,14 @@ describe('styled-components SWC transform', () => {
} }
} }
}) })
it('should render the page with correct styles', async () => {
const browser = await webdriver(next.appPort, '/')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#btn')).color`
)
).toBe('rgb(255, 255, 255)')
})
}) })
module.exports = { const path = require('path')
let withReact18 = (config) => config
try {
// only used when running inside of the monorepo not when isolated
withReact18 = require(path.join(
__dirname,
'../../../integration/react-18/test/with-react-18'
))
} catch (_) {}
module.exports = withReact18({
compiler: { compiler: {
styledComponents: true, styledComponents: true,
}, },
} })
...@@ -32,7 +32,9 @@ export default function Home() { ...@@ -32,7 +32,9 @@ export default function Home() {
GitHub GitHub
</Button> </Button>
<Button href="/docs">Documentation</Button> <Button id="btn" href="/docs">
Documentation
</Button>
</div> </div>
) )
} }
...@@ -241,11 +241,17 @@ const cssSuite = { ...@@ -241,11 +241,17 @@ const cssSuite = {
} }
const documentSuite = { const documentSuite = {
runTests: (context) => { runTests: (context, env) => {
it('should error when custom _document has getInitialProps method', async () => { if (env === 'dev') {
const res = await fetchViaHTTP(context.appPort, '/') it('should error when custom _document has getInitialProps method', async () => {
expect(res.status).toBe(500) const res = await fetchViaHTTP(context.appPort, '/')
}) expect(res.status).toBe(500)
})
} else {
it('should failed building', async () => {
expect(context.code).toBe(1)
})
}
}, },
beforeAll: () => documentPage.write(documentWithGip), beforeAll: () => documentPage.write(documentWithGip),
afterAll: () => documentPage.delete(), afterAll: () => documentPage.delete(),
...@@ -270,7 +276,7 @@ function runSuite(suiteName, env, options) { ...@@ -270,7 +276,7 @@ function runSuite(suiteName, env, options) {
options.beforeAll?.() options.beforeAll?.()
if (env === 'prod') { if (env === 'prod') {
context.appPort = await findPort() context.appPort = await findPort()
await nextBuild(context.appDir) context.code = (await nextBuild(context.appDir)).code
context.server = await nextStart(context.appDir, context.appPort) context.server = await nextStart(context.appDir, context.appPort)
} }
if (env === 'dev') { if (env === 'dev') {
......
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