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,18 +1328,8 @@ export async function renderToHTML( ...@@ -1323,18 +1328,8 @@ 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 = () => { const renderContent = () => {
return ctx.err && ErrorDebug ? ( return ctx.err && ErrorDebug ? (
...@@ -1355,7 +1350,44 @@ export async function renderToHTML( ...@@ -1355,7 +1350,44 @@ export async function renderToHTML(
) )
} }
if (hasConcurrentFeatures) { if (!hasConcurrentFeatures) {
if (Document.getInitialProps) {
const documentInitialPropsRes = await documentInitialProps()
if (documentInitialPropsRes === null) return null
const { docProps, documentCtx } = documentInitialPropsRes
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 {
const content = renderContent()
// for non-concurrent rendering we need to ensure App is rendered
// before _document so that updateHead is called/collected before
// rendering _document's head
const result = ReactDOMServer.renderToString(content)
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 let renderStream: any
// We start rendering the shell earlier, before returning the head tags // We start rendering the shell earlier, before returning the head tags
...@@ -1398,21 +1430,28 @@ export async function renderToHTML( ...@@ -1398,21 +1430,28 @@ export async function renderToHTML(
flushEffectHandler, flushEffectHandler,
}) })
} }
} else {
const content = renderContent()
// for non-concurrent rendering we need to ensure App is rendered
// before _document so that updateHead is called/collected before
// rendering _document's head
const result = ReactDOMServer.renderToString(content)
bodyResult = (suffix: string) => streamFromArray([result, suffix])
}
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) => {
if (env === 'dev') {
it('should error when custom _document has getInitialProps method', async () => { it('should error when custom _document has getInitialProps method', async () => {
const res = await fetchViaHTTP(context.appPort, '/') const res = await fetchViaHTTP(context.appPort, '/')
expect(res.status).toBe(500) 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