Commit b4e4bcda authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Clean up AMP logic and naming (#7669)

* Clean up AMP logic

* Tweak AMP logic some more

* Rename hasAmpVersion to hybridAmp
parent 830281fe
import * as React from 'react'
export const AmpStateContext: React.Context<any> = React.createContext({})
import React from 'react'
import { AmpModeContext } from './amphtml-context'
import { AmpStateContext } from './amp-context'
export function isAmp({
enabled = false,
export function isInAmpMode({
ampFirst = false,
hybrid = false,
hasQuery = false,
} = {}) {
return enabled && (!hybrid || (hybrid && hasQuery))
return ampFirst || (hybrid && hasQuery)
}
export function useAmp() {
const ampMode = React.useContext(AmpModeContext)
const ampState = React.useContext(AmpStateContext)
// un-comment below to not be considered AMP in dirty mode
return isAmp(ampMode) // && ampMode.hasQuery
return isInAmpMode(ampState) // && ampMode.hasQuery
}
/**
......@@ -20,9 +20,9 @@ export function useAmp() {
*/
export function withAmp(Component: any, { hybrid = false } = {}): any {
function WithAmpWrapper(props = {}) {
const ampMode = React.useContext(AmpModeContext)
ampMode.enabled = true
ampMode.hybrid = hybrid
const ampState = React.useContext(AmpStateContext)
ampState.ampFirst = !hybrid
ampState.hybrid = hybrid
return React.createElement(Component, props)
}
......
import * as React from 'react'
export const AmpModeContext: React.Context<any> = React.createContext({})
import React from 'react'
import withSideEffect from './side-effect'
import { AmpModeContext } from './amphtml-context'
import { AmpStateContext } from './amp-context'
import { HeadManagerContext } from './head-manager-context'
import { isAmp } from './amp'
import { isInAmpMode } from './amp'
type WithIsAmp = {
isAmp?: boolean
type WithInAmpMode = {
inAmpMode?: boolean
}
export function defaultHead(className = 'next-head', isAmp = false) {
export function defaultHead(className = 'next-head', inAmpMode = false) {
const head = [<meta key="charSet" charSet="utf-8" className={className} />]
if (!isAmp) {
if (!inAmpMode) {
head.push(
<meta
key="viewport"
......@@ -107,7 +107,7 @@ function unique() {
*/
function reduceComponents(
headElements: Array<React.ReactElement<any>>,
props: WithIsAmp
props: WithInAmpMode
) {
return headElements
.reduce(
......@@ -121,7 +121,7 @@ function reduceComponents(
)
.reduce(onlyReactElement, [])
.reverse()
.concat(defaultHead('', props.isAmp))
.concat(defaultHead('', props.inAmpMode))
.filter(unique())
.reverse()
.map((c: React.ReactElement<any>, i: number) => {
......@@ -145,21 +145,21 @@ const Effect = withSideEffect()
*/
function Head({ children }: { children: React.ReactNode }) {
return (
<AmpModeContext.Consumer>
{ampMode => (
<AmpStateContext.Consumer>
{ampState => (
<HeadManagerContext.Consumer>
{updateHead => (
<Effect
reduceComponentsToState={reduceComponents}
handleStateChange={updateHead}
isAmp={isAmp(ampMode)}
inAmpMode={isInAmpMode(ampState)}
>
{children}
</Effect>
)}
</HeadManagerContext.Consumer>
)}
</AmpModeContext.Consumer>
</AmpStateContext.Consumer>
)
}
......
import React, { Component, ReactNode } from 'react'
import React, { Component } from 'react'
const isServer = typeof window === 'undefined'
......@@ -10,7 +10,7 @@ type SideEffectProps = {
props: T
) => State
handleStateChange?: (state: State) => void
isAmp?: boolean
inAmpMode?: boolean
}
export default () => {
......
......@@ -127,8 +127,8 @@ export type DocumentProps = DocumentInitialProps & {
__NEXT_DATA__: NEXT_DATA
dangerousAsPath: string
ampPath: string
amphtml: boolean
hasAmp: boolean
inAmpMode: boolean
hybridAmp: boolean
staticMarkup: boolean
devFiles: string[]
files: string[]
......
......@@ -30,9 +30,9 @@ import {
Manifest as ReactLoadableManifest,
} from './get-dynamic-import-bundles'
import { getPageFiles, BuildManifest } from './get-page-files'
import { AmpModeContext } from '../lib/amphtml-context'
import { AmpStateContext } from '../lib/amp-context'
import optimizeAmp from './optimize-amp'
import { isAmp } from '../lib/amp'
import { isInAmpMode } from '../lib/amp'
import { IPageConfig } from './load-components'
function noRouter() {
......@@ -115,7 +115,7 @@ function render(
try {
html = renderElementToString(element)
} finally {
head = Head.rewind() || defaultHead(undefined, isAmp(ampMode))
head = Head.rewind() || defaultHead(undefined, isInAmpMode(ampMode))
}
return { html, head }
......@@ -135,11 +135,11 @@ type RenderOpts = {
err?: Error | null
nextExport?: boolean
dev?: boolean
ampPath?: string
amphtml?: boolean
hasAmp?: boolean
ampMode?: any
ampPath?: string
dataOnly?: boolean
inAmpMode?: boolean
hybridAmp?: boolean
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
PageConfig: IPageConfig
......@@ -170,9 +170,9 @@ function renderDocument(
err,
dev,
ampPath,
amphtml,
hasAmp,
ampMode,
ampState,
inAmpMode,
hybridAmp,
staticMarkup,
devFiles,
files,
......@@ -184,10 +184,10 @@ function renderDocument(
pathname: string
query: ParsedUrlQuery
dangerousAsPath: string
ampState: any
ampPath: string
amphtml: boolean
hasAmp: boolean
ampMode: any
inAmpMode: boolean
hybridAmp: boolean
dynamicImportsIds: string[]
dynamicImports: ManifestItem[]
files: string[]
......@@ -197,7 +197,7 @@ function renderDocument(
return (
'<!DOCTYPE html>' +
renderToStaticMarkup(
<AmpModeContext.Provider value={ampMode}>
<AmpStateContext.Provider value={ampState}>
<Document
__NEXT_DATA__={{
dataManager: dataManagerData,
......@@ -216,8 +216,8 @@ function renderDocument(
dangerousAsPath={dangerousAsPath}
canonicalBase={canonicalBase}
ampPath={ampPath}
amphtml={amphtml}
hasAmp={hasAmp}
inAmpMode={inAmpMode}
hybridAmp={hybridAmp}
staticMarkup={staticMarkup}
devFiles={devFiles}
files={files}
......@@ -225,7 +225,7 @@ function renderDocument(
assetPrefix={assetPrefix}
{...docProps}
/>
</AmpModeContext.Provider>
</AmpStateContext.Provider>
)
)
}
......@@ -335,6 +335,12 @@ export async function renderToHTML(
dataManager = new DataManager()
}
const ampState = {
ampFirst: PageConfig.amp === true,
hasQuery: Boolean(query.amp),
hybrid: PageConfig.amp === 'hybrid',
}
const reactLoadableModules: string[] = []
const renderElementToString = staticMarkup
? renderToStaticMarkup
......@@ -345,7 +351,7 @@ export async function renderToHTML(
return render(
renderElementToString,
<ErrorDebug error={ctx.err} />,
ampMode
ampState
)
}
......@@ -358,12 +364,6 @@ export async function renderToHTML(
let renderPage: RenderPage
const ampMode = {
enabled: Boolean(PageConfig.amp),
hasQuery: Boolean(query.amp),
hybrid: PageConfig.amp === 'hybrid',
}
if (ampBindInitData) {
const ssrPrepass = require('react-ssr-prepass')
......@@ -382,7 +382,7 @@ export async function renderToHTML(
<RequestContext.Provider value={req}>
<RouterContext.Provider value={router}>
<DataManagerContext.Provider value={dataManager}>
<AmpModeContext.Provider value={ampMode}>
<AmpStateContext.Provider value={ampState}>
<LoadableContext.Provider
value={moduleName => reactLoadableModules.push(moduleName)}
>
......@@ -392,7 +392,7 @@ export async function renderToHTML(
{...props}
/>
</LoadableContext.Provider>
</AmpModeContext.Provider>
</AmpStateContext.Provider>
</DataManagerContext.Provider>
</RouterContext.Provider>
</RequestContext.Provider>
......@@ -401,7 +401,7 @@ export async function renderToHTML(
const element = <Application />
try {
return render(renderElementToString, element, ampMode)
return render(renderElementToString, element, ampState)
} catch (err) {
if (err && typeof err === 'object' && typeof err.then === 'function') {
await ssrPrepass(element)
......@@ -412,7 +412,7 @@ export async function renderToHTML(
dataOnly: true,
}
} else {
return render(renderElementToString, element, ampMode)
return render(renderElementToString, element, ampState)
}
}
throw err
......@@ -434,7 +434,7 @@ export async function renderToHTML(
renderElementToString,
<RequestContext.Provider value={req}>
<RouterContext.Provider value={router}>
<AmpModeContext.Provider value={ampMode}>
<AmpStateContext.Provider value={ampState}>
<LoadableContext.Provider
value={moduleName => reactLoadableModules.push(moduleName)}
>
......@@ -444,10 +444,10 @@ export async function renderToHTML(
{...props}
/>
</LoadableContext.Provider>
</AmpModeContext.Provider>
</AmpStateContext.Provider>
</RouterContext.Provider>
</RequestContext.Provider>,
ampMode
ampState
)
}
}
......@@ -478,31 +478,32 @@ export async function renderToHTML(
const dynamicImportsIds: any = [
...new Set(dynamicImports.map(bundle => bundle.id)),
]
const amphtml = isAmp(ampMode)
const hasAmp = !amphtml && ampMode.enabled
// update renderOpts so export knows it's AMP
renderOpts.amphtml = amphtml
renderOpts.hasAmp = hasAmp
const inAmpMode = isInAmpMode(ampState)
const hybridAmp = ampState.hybrid
// update renderOpts so export knows it's AMP state
renderOpts.inAmpMode = inAmpMode
renderOpts.hybridAmp = hybridAmp
let html = renderDocument(Document, {
...renderOpts,
dangerousAsPath: router.asPath,
dataManagerData,
ampMode,
ampState,
props,
docProps,
pathname,
ampPath,
amphtml,
hasAmp,
query,
inAmpMode,
hybridAmp,
dynamicImportsIds,
dynamicImports,
files,
devFiles,
})
if (amphtml && html) {
if (inAmpMode && html) {
// use replace to allow rendering directly to body in AMP mode
html = html.replace(
'__NEXT_AMP_RENDER_TARGET__',
......@@ -515,7 +516,7 @@ export async function renderToHTML(
}
}
if (amphtml || hasAmp) {
if (inAmpMode || hybridAmp) {
// fix &amp being escaped for amphtml rel link
html = html.replace(/&amp;amp=1/g, '&amp=1')
}
......
......@@ -36,10 +36,6 @@ process.on(
await sema.acquire()
const ampPath = `${path === '/' ? '/index' : path}.amp`
const { page, query = {} } = exportPathMap[path]
delete query.ampOnly
delete query.hasAmp
delete query.ampPath
delete query.amphtml
const headerMocks = {
headers: {},
......@@ -130,10 +126,9 @@ process.on(
}
}
if (curRenderOpts.amphtml && query.amp) {
if (curRenderOpts.inAmpMode) {
await validateAmp(html, path)
}
if (curRenderOpts.hasAmp) {
} else if (curRenderOpts.hybridAmp) {
// we need to render the AMP version
let ampHtmlFilename = `${ampPath}${sep}index.html`
if (!subFolders) {
......
......@@ -105,8 +105,8 @@ export class Html extends Component<
context!: DocumentComponentContext
render() {
const { amphtml } = this.context._documentProps
return <html {...this.props} amp={amphtml ? '' : undefined} />
const { inAmpMode } = this.context._documentProps
return <html {...this.props} amp={inAmpMode ? '' : undefined} />
}
}
......@@ -202,10 +202,10 @@ export class Head extends Component<
render() {
const {
styles,
amphtml,
hasAmp,
ampPath,
inAmpMode,
assetPrefix,
hybridAmp,
canonicalBase,
__NEXT_DATA__,
dangerousAsPath,
......@@ -234,7 +234,7 @@ export class Head extends Component<
}
// show warning and remove conflicting amp head tags
head = !amphtml
head = !inAmpMode
? head
: React.Children.map(head || [], child => {
if (!child) return child
......@@ -279,7 +279,7 @@ export class Head extends Component<
// try to parse styles from fragment for backwards compat
const curStyles: React.ReactElement[] = Array.isArray(styles) ? styles : []
if (
amphtml &&
inAmpMode &&
styles &&
// @ts-ignore Property 'props' does not exist on type ReactElement
styles.props &&
......@@ -305,7 +305,7 @@ export class Head extends Component<
<head {...this.props}>
{children}
{head}
{amphtml && (
{inAmpMode && (
<>
<meta
name="viewport"
......@@ -351,9 +351,9 @@ export class Head extends Component<
<script async src="https://cdn.ampproject.org/v0.js" />
</>
)}
{!amphtml && (
{!inAmpMode && (
<>
{hasAmp && (
{hybridAmp && (
<link
rel="amphtml"
href={canonicalBase + getAmpPath(ampPath, dangerousAsPath)}
......@@ -407,8 +407,8 @@ export class Main extends Component {
context!: DocumentComponentContext
render() {
const { amphtml, html } = this.context._documentProps
if (amphtml) return '__NEXT_AMP_RENDER_TARGET__'
const { inAmpMode, html } = this.context._documentProps
if (inAmpMode) return '__NEXT_AMP_RENDER_TARGET__'
return <div id="__next" dangerouslySetInnerHTML={{ __html: html }} />
}
}
......@@ -491,13 +491,13 @@ export class NextScript extends Component<OriginProps> {
const {
staticMarkup,
assetPrefix,
amphtml,
inAmpMode,
devFiles,
__NEXT_DATA__,
} = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
if (amphtml) {
if (inAmpMode) {
if (process.env.NODE_ENV === 'production') {
return null
}
......
......@@ -34,7 +34,7 @@ describe('AMP Validation on Export', () => {
'// exportPathMap',
`exportPathMap: function(defaultMap) {
return {
'/cat': { page: '/cat', query: { amp: 1 } },
'/cat': { page: '/cat' },
}
},`
)
......@@ -63,7 +63,7 @@ describe('AMP Validation on Export', () => {
'// exportPathMap',
`exportPathMap: function(defaultMap) {
return {
'/dog': { page: '/dog', query: { amp: 1 }},
'/dog': { page: '/dog' },
}
},`
)
......@@ -92,7 +92,7 @@ describe('AMP Validation on Export', () => {
'// exportPathMap',
`exportPathMap: function(defaultMap) {
return {
'/dog-cat': { page: '/dog-cat', query: { amp: 1 } },
'/dog-cat': { page: '/dog-cat' },
}
},`
)
......
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