Unverified Commit 08a24780 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Clean up `Document` in preparation for streaming (#28032)

We generate the HTML for a document in two steps: First, we generate the body (i.e. everything under `<div id="__next">`). Then we generate the rest of the document and embed the body in it.

This doesn't work when the body is a stream, because React can't render the body for us unless we buffer it, and buffering it means not streaming. This PR takes the existing approach for AMP and uses it for all scenarios: instead of rendering HTML, we just render a placeholder that we can replace with HTML later. This will be used in a follow-up PR to let us know where to concatenate the body stream.

I also used the opportunity to split out `HtmlContext` from `DocumentProps`, as these will not be the same thing with functional document components.
parent c8be62c8
import React, { Component, ReactElement, ReactNode, useContext } from 'react' import React, { Component, ReactElement, ReactNode, useContext } from 'react'
import flush from 'styled-jsx/server' import flush from 'styled-jsx/server'
import { import {
AMP_RENDER_TARGET, BODY_RENDER_TARGET,
OPTIMIZED_FONT_PROVIDERS, OPTIMIZED_FONT_PROVIDERS,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { DocumentContext as DocumentComponentContext } from '../shared/lib/document-context'
import { import {
DocumentContext, DocumentContext,
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
HtmlContext,
HtmlProps,
} from '../shared/lib/utils' } from '../shared/lib/utils'
import { BuildManifest, getPageFiles } from '../server/get-page-files' import { BuildManifest, getPageFiles } from '../server/get-page-files'
import { cleanAmpPath } from '../server/utils' import { cleanAmpPath } from '../server/utils'
...@@ -45,7 +46,7 @@ function getDocumentFiles( ...@@ -45,7 +46,7 @@ function getDocumentFiles(
} }
} }
function getPolyfillScripts(context: DocumentProps, props: OriginProps) { function getPolyfillScripts(context: HtmlProps, props: OriginProps) {
// polyfills.js has to be rendered as nomodule without async // polyfills.js has to be rendered as nomodule without async
// It also has to be the first script to load // It also has to be the first script to load
const { const {
...@@ -71,7 +72,7 @@ function getPolyfillScripts(context: DocumentProps, props: OriginProps) { ...@@ -71,7 +72,7 @@ function getPolyfillScripts(context: DocumentProps, props: OriginProps) {
)) ))
} }
function getPreNextScripts(context: DocumentProps, props: OriginProps) { function getPreNextScripts(context: HtmlProps, props: OriginProps) {
const { scriptLoader, disableOptimizedLoading } = context const { scriptLoader, disableOptimizedLoading } = context
return (scriptLoader.beforeInteractive || []).map( return (scriptLoader.beforeInteractive || []).map(
...@@ -91,7 +92,7 @@ function getPreNextScripts(context: DocumentProps, props: OriginProps) { ...@@ -91,7 +92,7 @@ function getPreNextScripts(context: DocumentProps, props: OriginProps) {
} }
function getDynamicChunks( function getDynamicChunks(
context: DocumentProps, context: HtmlProps,
props: OriginProps, props: OriginProps,
files: DocumentFiles files: DocumentFiles
) { ) {
...@@ -122,7 +123,7 @@ function getDynamicChunks( ...@@ -122,7 +123,7 @@ function getDynamicChunks(
} }
function getScripts( function getScripts(
context: DocumentProps, context: HtmlProps,
props: OriginProps, props: OriginProps,
files: DocumentFiles files: DocumentFiles
) { ) {
...@@ -176,17 +177,6 @@ export default class Document<P = {}> extends Component<DocumentProps & P> { ...@@ -176,17 +177,6 @@ export default class Document<P = {}> extends Component<DocumentProps & P> {
return { html, head, styles } return { html, head, styles }
} }
static renderDocument<Y>(
DocumentComponent: new () => Document<Y>,
props: DocumentProps & Y
): React.ReactElement {
return (
<DocumentComponentContext.Provider value={props}>
<DocumentComponent {...props} />
</DocumentComponentContext.Provider>
)
}
render() { render() {
return ( return (
<Html> <Html>
...@@ -206,9 +196,7 @@ export function Html( ...@@ -206,9 +196,7 @@ export function Html(
HTMLHtmlElement HTMLHtmlElement
> >
) { ) {
const { inAmpMode, docComponentsRendered, locale } = useContext( const { inAmpMode, docComponentsRendered, locale } = useContext(HtmlContext)
DocumentComponentContext
)
docComponentsRendered.Html = true docComponentsRendered.Html = true
...@@ -231,9 +219,9 @@ export class Head extends Component< ...@@ -231,9 +219,9 @@ export class Head extends Component<
HTMLHeadElement HTMLHeadElement
> >
> { > {
static contextType = DocumentComponentContext static contextType = HtmlContext
context!: React.ContextType<typeof DocumentComponentContext> context!: React.ContextType<typeof HtmlContext>
getCssLinks(files: DocumentFiles): JSX.Element[] | null { getCssLinks(files: DocumentFiles): JSX.Element[] | null {
const { const {
...@@ -738,20 +726,18 @@ export class Head extends Component< ...@@ -738,20 +726,18 @@ export class Head extends Component<
} }
export function Main() { export function Main() {
const { inAmpMode, html, docComponentsRendered } = useContext( const { inAmpMode, docComponentsRendered } = useContext(HtmlContext)
DocumentComponentContext
)
docComponentsRendered.Main = true docComponentsRendered.Main = true
if (inAmpMode) return <>{AMP_RENDER_TARGET}</> if (inAmpMode) return <>{BODY_RENDER_TARGET}</>
return <div id="__next" dangerouslySetInnerHTML={{ __html: html }} /> return <div id="__next">{BODY_RENDER_TARGET}</div>
} }
export class NextScript extends Component<OriginProps> { export class NextScript extends Component<OriginProps> {
static contextType = DocumentComponentContext static contextType = HtmlContext
context!: React.ContextType<typeof DocumentComponentContext> context!: React.ContextType<typeof HtmlContext>
// Source: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc // Source: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
static safariNomoduleFix = static safariNomoduleFix =
...@@ -773,8 +759,8 @@ export class NextScript extends Component<OriginProps> { ...@@ -773,8 +759,8 @@ export class NextScript extends Component<OriginProps> {
return getPolyfillScripts(this.context, this.props) return getPolyfillScripts(this.context, this.props)
} }
static getInlineScriptSource(documentProps: Readonly<DocumentProps>): string { static getInlineScriptSource(context: Readonly<HtmlProps>): string {
const { __NEXT_DATA__ } = documentProps const { __NEXT_DATA__ } = context
try { try {
const data = JSON.stringify(__NEXT_DATA__) const data = JSON.stringify(__NEXT_DATA__)
return htmlEscapeJsonString(data) return htmlEscapeJsonString(data)
......
...@@ -20,7 +20,7 @@ import { GetServerSideProps, GetStaticProps, PreviewData } from '../types' ...@@ -20,7 +20,7 @@ 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 {
AMP_RENDER_TARGET, BODY_RENDER_TARGET,
SERVER_PROPS_ID, SERVER_PROPS_ID,
STATIC_PROPS_ID, STATIC_PROPS_ID,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
...@@ -39,6 +39,7 @@ import { ...@@ -39,6 +39,7 @@ import {
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
DocumentType, DocumentType,
HtmlContext,
getDisplayName, getDisplayName,
isResSent, isResSent,
loadGetInitialProps, loadGetInitialProps,
...@@ -264,11 +265,7 @@ function renderDocument( ...@@ -264,11 +265,7 @@ function renderDocument(
autoExport?: boolean autoExport?: boolean
} }
): string { ): string {
return ( const htmlProps = {
'<!DOCTYPE html>' +
ReactDOMServer.renderToStaticMarkup(
<AmpStateContext.Provider value={ampState}>
{Document.renderDocument(Document, {
__NEXT_DATA__: { __NEXT_DATA__: {
props, // The result of getInitialProps props, // The result of getInitialProps
page: pathname, // The rendered page page: pathname, // The rendered page
...@@ -310,8 +307,16 @@ function renderDocument( ...@@ -310,8 +307,16 @@ function renderDocument(
scriptLoader, scriptLoader,
locale, locale,
disableOptimizedLoading, disableOptimizedLoading,
...docProps, styles: docProps.styles,
})} head: docProps.head,
}
return (
'<!DOCTYPE html>' +
ReactDOMServer.renderToStaticMarkup(
<AmpStateContext.Provider value={ampState}>
<HtmlContext.Provider value={htmlProps}>
<Document {...htmlProps} {...docProps} />
</HtmlContext.Provider>
</AmpStateContext.Provider> </AmpStateContext.Provider>
) )
) )
...@@ -1155,16 +1160,15 @@ export async function renderToHTML( ...@@ -1155,16 +1160,15 @@ export async function renderToHTML(
} }
} }
if (inAmpMode && html) { const bodyRenderIdx = html.indexOf(BODY_RENDER_TARGET)
// inject HTML to AMP_RENDER_TARGET to allow rendering
// directly to body in AMP mode
const ampRenderIndex = html.indexOf(AMP_RENDER_TARGET)
html = html =
html.substring(0, ampRenderIndex) + html.substring(0, bodyRenderIdx) +
`<!-- __NEXT_DATA__ -->${docProps.html}` + (inAmpMode ? '<!-- __NEXT_DATA__ -->' : '') +
html.substring(ampRenderIndex + AMP_RENDER_TARGET.length) docProps.html +
html = await optimizeAmp(html, renderOpts.ampOptimizerConfig) html.substring(bodyRenderIdx + BODY_RENDER_TARGET.length)
if (inAmpMode) {
html = await optimizeAmp(html, renderOpts.ampOptimizerConfig)
if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) { if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) {
await renderOpts.ampValidator(html, pathname) await renderOpts.ampValidator(html, pathname)
} }
......
...@@ -21,7 +21,7 @@ export const BLOCKED_PAGES = ['/_document', '/_app', '/_error'] ...@@ -21,7 +21,7 @@ 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 AMP_RENDER_TARGET = '__NEXT_AMP_RENDER_TARGET__' 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__'
// static/runtime/main.js // static/runtime/main.js
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main` export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`
......
import React from 'react'
import { DocumentProps } from './utils'
export const DocumentContext = React.createContext<DocumentProps>(null as any)
if (process.env.NODE_ENV !== 'production') {
DocumentContext.displayName = 'DocumentContext'
}
...@@ -8,6 +8,7 @@ import type { NextRouter } from './router/router' ...@@ -8,6 +8,7 @@ import type { NextRouter } from './router/router'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { PreviewData } from 'next/types' import type { PreviewData } from 'next/types'
import type { UrlObject } from 'url' import type { UrlObject } from 'url'
import { createContext } from 'react'
export type NextComponentType< export type NextComponentType<
C extends BaseContext = NextPageContext, C extends BaseContext = NextPageContext,
...@@ -26,12 +27,7 @@ export type DocumentType = NextComponentType< ...@@ -26,12 +27,7 @@ export type DocumentType = NextComponentType<
DocumentContext, DocumentContext,
DocumentInitialProps, DocumentInitialProps,
DocumentProps DocumentProps
> & { >
renderDocument(
Document: DocumentType,
props: DocumentProps
): React.ReactElement
}
export type AppType = NextComponentType< export type AppType = NextComponentType<
AppContextType, AppContextType,
...@@ -188,7 +184,9 @@ export type DocumentInitialProps = RenderPageResult & { ...@@ -188,7 +184,9 @@ export type DocumentInitialProps = RenderPageResult & {
styles?: React.ReactElement[] | React.ReactFragment styles?: React.ReactElement[] | React.ReactFragment
} }
export type DocumentProps = DocumentInitialProps & { export type DocumentProps = DocumentInitialProps & HtmlProps
export type HtmlProps = {
__NEXT_DATA__: NEXT_DATA __NEXT_DATA__: NEXT_DATA
dangerousAsPath: string dangerousAsPath: string
docComponentsRendered: { docComponentsRendered: {
...@@ -212,6 +210,8 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -212,6 +210,8 @@ export type DocumentProps = DocumentInitialProps & {
scriptLoader: { afterInteractive?: string[]; beforeInteractive?: any[] } scriptLoader: { afterInteractive?: string[]; beforeInteractive?: any[] }
locale?: string locale?: string
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
styles?: React.ReactElement[] | React.ReactFragment
head?: Array<JSX.Element | null>
} }
/** /**
...@@ -432,3 +432,8 @@ export const ST = ...@@ -432,3 +432,8 @@ export const ST =
typeof performance.measure === 'function' typeof performance.measure === 'function'
export class DecodeError extends Error {} export class DecodeError extends Error {}
export const HtmlContext = createContext<HtmlProps>(null as any)
if (process.env.NODE_ENV !== 'production') {
HtmlContext.displayName = 'HtmlContext'
}
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