Unverified Commit 57d9076e authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Adopt context based experimental styled-jsx version (#28646)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 13893395
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import '@next/polyfill-module' import '@next/polyfill-module'
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import { StyleRegistry } from 'styled-jsx'
import { HeadManagerContext } from '../shared/lib/head-manager-context' import { HeadManagerContext } from '../shared/lib/head-manager-context'
import mitt, { MittEmitter } from '../shared/lib/mitt' import mitt, { MittEmitter } from '../shared/lib/mitt'
import { RouterContext } from '../shared/lib/router-context' import { RouterContext } from '../shared/lib/router-context'
...@@ -598,7 +599,7 @@ function AppContainer({ ...@@ -598,7 +599,7 @@ function AppContainer({
> >
<RouterContext.Provider value={makePublicRouterInstance(router)}> <RouterContext.Provider value={makePublicRouterInstance(router)}>
<HeadManagerContext.Provider value={headManager}> <HeadManagerContext.Provider value={headManager}>
{children} <StyleRegistry>{children}</StyleRegistry>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</RouterContext.Provider> </RouterContext.Provider>
</Container> </Container>
......
...@@ -106,7 +106,7 @@ ...@@ -106,7 +106,7 @@
"stream-browserify": "3.0.0", "stream-browserify": "3.0.0",
"stream-http": "3.1.1", "stream-http": "3.1.1",
"string_decoder": "1.3.0", "string_decoder": "1.3.0",
"styled-jsx": "4.0.1", "styled-jsx": "5.0.0-beta.1",
"timers-browserify": "2.0.12", "timers-browserify": "2.0.12",
"tty-browserify": "0.0.1", "tty-browserify": "0.0.1",
"use-subscription": "1.5.1", "use-subscription": "1.5.1",
......
import React, { Component, ReactElement, ReactNode, useContext } from 'react' import React, { Component, ReactElement, ReactNode, useContext } from 'react'
import flush from 'styled-jsx/server'
import { import {
BODY_RENDER_TARGET, BODY_RENDER_TARGET,
OPTIMIZED_FONT_PROVIDERS, OPTIMIZED_FONT_PROVIDERS,
...@@ -166,16 +165,8 @@ export default class Document<P = {}> extends Component<DocumentProps & P> { ...@@ -166,16 +165,8 @@ export default class Document<P = {}> extends Component<DocumentProps & P> {
* `getInitialProps` hook returns the context object with the addition of `renderPage`. * `getInitialProps` hook returns the context object with the addition of `renderPage`.
* `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers * `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers
*/ */
static async getInitialProps( static getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
ctx: DocumentContext return ctx.defaultGetInitialProps(ctx)
): Promise<DocumentInitialProps> {
const enhanceApp = (App: any) => {
return (props: any) => <App {...props} />
}
const { html, head } = await ctx.renderPage({ enhanceApp })
const styles = [...flush()]
return { html, head, styles }
} }
render() { render() {
...@@ -213,6 +204,50 @@ export function Html( ...@@ -213,6 +204,50 @@ export function Html(
) )
} }
function AmpStyles({
styles,
}: {
styles?: React.ReactElement[] | React.ReactFragment
}) {
if (!styles) return null
// try to parse styles from fragment for backwards compat
const curStyles: React.ReactElement[] = Array.isArray(styles)
? (styles as React.ReactElement[])
: []
if (
// @ts-ignore Property 'props' does not exist on type ReactElement
styles.props &&
// @ts-ignore Property 'props' does not exist on type ReactElement
Array.isArray(styles.props.children)
) {
const hasStyles = (el: React.ReactElement) =>
el?.props?.dangerouslySetInnerHTML?.__html
// @ts-ignore Property 'props' does not exist on type ReactElement
styles.props.children.forEach((child: React.ReactElement) => {
if (Array.isArray(child)) {
child.forEach((el) => hasStyles(el) && curStyles.push(el))
} else if (hasStyles(child)) {
curStyles.push(child)
}
})
}
/* Add custom styles before AMP styles to prevent accidental overrides */
return (
<style
amp-custom=""
dangerouslySetInnerHTML={{
__html: curStyles
.map((style) => style.props.dangerouslySetInnerHTML.__html)
.join('')
.replace(/\/\*# sourceMappingURL=.*\*\//g, '')
.replace(/\/\*@ sourceURL=.*?\*\//g, ''),
}}
/>
)
}
export class Head extends Component< export class Head extends Component<
OriginProps & OriginProps &
React.DetailedHTMLProps< React.DetailedHTMLProps<
...@@ -555,30 +590,6 @@ export class Head extends Component< ...@@ -555,30 +590,6 @@ export class Head extends Component<
return child return child
}) })
// try to parse styles from fragment for backwards compat
const curStyles: React.ReactElement[] = Array.isArray(styles)
? (styles as React.ReactElement[])
: []
if (
inAmpMode &&
styles &&
// @ts-ignore Property 'props' does not exist on type ReactElement
styles.props &&
// @ts-ignore Property 'props' does not exist on type ReactElement
Array.isArray(styles.props.children)
) {
const hasStyles = (el: React.ReactElement) =>
el?.props?.dangerouslySetInnerHTML?.__html
// @ts-ignore Property 'props' does not exist on type ReactElement
styles.props.children.forEach((child: React.ReactElement) => {
if (Array.isArray(child)) {
child.forEach((el) => hasStyles(el) && curStyles.push(el))
} else if (hasStyles(child)) {
curStyles.push(child)
}
})
}
const files: DocumentFiles = getDocumentFiles( const files: DocumentFiles = getDocumentFiles(
this.context.buildManifest, this.context.buildManifest,
this.context.__NEXT_DATA__.page, this.context.__NEXT_DATA__.page,
...@@ -635,19 +646,7 @@ export class Head extends Component< ...@@ -635,19 +646,7 @@ export class Head extends Component<
as="script" as="script"
href="https://cdn.ampproject.org/v0.js" href="https://cdn.ampproject.org/v0.js"
/> />
{/* Add custom styles before AMP styles to prevent accidental overrides */} <AmpStyles styles={styles} />
{styles && (
<style
amp-custom=""
dangerouslySetInnerHTML={{
__html: curStyles
.map((style) => style.props.dangerouslySetInnerHTML.__html)
.join('')
.replace(/\/\*# sourceMappingURL=.*\*\//g, '')
.replace(/\/\*@ sourceURL=.*?\*\//g, ''),
}}
/>
)}
<style <style
amp-boilerplate="" amp-boilerplate=""
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
......
...@@ -3,7 +3,7 @@ import { ParsedUrlQuery } from 'querystring' ...@@ -3,7 +3,7 @@ import { ParsedUrlQuery } from 'querystring'
import { PassThrough } from 'stream' import { PassThrough } from 'stream'
import React from 'react' import React from 'react'
import * as ReactDOMServer from 'react-dom/server' import * as ReactDOMServer from 'react-dom/server'
import flush from 'styled-jsx/server' import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import Observable from 'next/dist/compiled/zen-observable' import Observable from 'next/dist/compiled/zen-observable'
import { warn } from '../build/output/log' import { warn } from '../build/output/log'
import { UnwrapPromise } from '../lib/coalesced-function' import { UnwrapPromise } from '../lib/coalesced-function'
...@@ -40,6 +40,7 @@ import { ...@@ -40,6 +40,7 @@ import {
ComponentsEnhancer, ComponentsEnhancer,
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
DocumentContext,
HtmlContext, HtmlContext,
HtmlProps, HtmlProps,
getDisplayName, getDisplayName,
...@@ -482,6 +483,7 @@ export async function renderToHTML( ...@@ -482,6 +483,7 @@ export async function renderToHTML(
isPreview, isPreview,
(req as any).__nextIsLocaleDomain (req as any).__nextIsLocaleDomain
) )
const jsxStyleRegistry = createStyleRegistry()
const ctx = { const ctx = {
err, err,
req: isAutoExport ? undefined : req, req: isAutoExport ? undefined : req,
...@@ -499,6 +501,17 @@ export async function renderToHTML( ...@@ -499,6 +501,17 @@ export async function renderToHTML(
</AppContainer> </AppContainer>
) )
}, },
defaultGetInitialProps: async (
docCtx: DocumentContext
): Promise<DocumentInitialProps> => {
const enhanceApp = (AppComp: any) => {
return (props: any) => <AppComp {...props} />
}
const { html, head } = await docCtx.renderPage({ enhanceApp })
const styles = jsxStyleRegistry.styles()
return { html, head, styles }
},
} }
let props: any let props: any
...@@ -536,7 +549,9 @@ export async function renderToHTML( ...@@ -536,7 +549,9 @@ export async function renderToHTML(
<LoadableContext.Provider <LoadableContext.Provider
value={(moduleName) => reactLoadableModules.push(moduleName)} value={(moduleName) => reactLoadableModules.push(moduleName)}
> >
{children} <StyleRegistry registry={jsxStyleRegistry}>
{children}
</StyleRegistry>
</LoadableContext.Provider> </LoadableContext.Provider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</AmpStateContext.Provider> </AmpStateContext.Provider>
...@@ -1018,8 +1033,7 @@ export async function renderToHTML( ...@@ -1018,8 +1033,7 @@ export async function renderToHTML(
documentElement: () => (Document as any)(), documentElement: () => (Document as any)(),
head, head,
headTags: [], headTags: [],
// TODO: Experimental styled-jsx 5 support styles: jsxStyleRegistry.styles(),
styles: [...flush()],
} }
} }
} }
...@@ -1108,7 +1122,7 @@ export async function renderToHTML( ...@@ -1108,7 +1122,7 @@ export async function renderToHTML(
locale, locale,
disableOptimizedLoading, disableOptimizedLoading,
head: documentResult.head, head: documentResult.head,
headTags: documentResult?.headTags, headTags: documentResult.headTags,
styles: documentResult.styles, styles: documentResult.styles,
} }
const documentHTML = ReactDOMServer.renderToStaticMarkup( const documentHTML = ReactDOMServer.renderToStaticMarkup(
......
...@@ -77,7 +77,7 @@ export type RenderPageResult = { ...@@ -77,7 +77,7 @@ export type RenderPageResult = {
export type RenderPage = ( export type RenderPage = (
options?: ComponentsEnhancer options?: ComponentsEnhancer
) => RenderPageResult | Promise<RenderPageResult> ) => DocumentInitialProps | Promise<DocumentInitialProps>
export type BaseContext = { export type BaseContext = {
res?: ServerResponse res?: ServerResponse
...@@ -178,6 +178,7 @@ export type AppPropsType< ...@@ -178,6 +178,7 @@ export type AppPropsType<
export type DocumentContext = NextPageContext & { export type DocumentContext = NextPageContext & {
renderPage: RenderPage renderPage: RenderPage
defaultGetInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps>
} }
export type DocumentInitialProps = RenderPageResult & { export type DocumentInitialProps = RenderPageResult & {
......
...@@ -6,7 +6,6 @@ declare module 'cssnano-simple' { ...@@ -6,7 +6,6 @@ declare module 'cssnano-simple' {
const cssnanoSimple: any const cssnanoSimple: any
export = cssnanoSimple export = cssnanoSimple
} }
declare module 'styled-jsx/server'
declare module 'next/dist/compiled/amphtml-validator' { declare module 'next/dist/compiled/amphtml-validator' {
import m from 'amphtml-validator' import m from 'amphtml-validator'
......
...@@ -18512,10 +18512,10 @@ styled-jsx-plugin-postcss@3.0.2: ...@@ -18512,10 +18512,10 @@ styled-jsx-plugin-postcss@3.0.2:
postcss "^7.0.2" postcss "^7.0.2"
postcss-load-plugins "^2.3.0" postcss-load-plugins "^2.3.0"
styled-jsx@4.0.1: styled-jsx@5.0.0-beta.1:
version "4.0.1" version "5.0.0-beta.1"
resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-4.0.1.tgz#ae3f716eacc0792f7050389de88add6d5245b9e9" resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-5.0.0-beta.1.tgz#159e147ff77cdc7aff7631d248fad649b870b7cd"
integrity sha512-Gcb49/dRB1k8B4hdK8vhW27Rlb2zujCk1fISrizCcToIs+55B4vmUM0N9Gi4nnVfFZWe55jRdWpAqH1ldAKWvQ== integrity sha512-c8pkEyI4J2lNedm/kaurCU/4U+L7Z4XUSzXBXnf0voGFwERgO2LPcKg03oV8xUMdsy0T5ZZSvlMPbNSsSMAxkg==
dependencies: dependencies:
"@babel/plugin-syntax-jsx" "7.14.5" "@babel/plugin-syntax-jsx" "7.14.5"
"@babel/types" "7.15.0" "@babel/types" "7.15.0"
......
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