Unverified Commit 80671273 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Revert "Remove `next-head-count` (#16758)" (#18713)

Co-authored-by: 's avatarJoe Haddad <joe.haddad@zeit.co>
parent a2bea9b4
...@@ -6,8 +6,6 @@ You have a custom `pages/_document.js` that doesn't have the components required ...@@ -6,8 +6,6 @@ You have a custom `pages/_document.js` that doesn't have the components required
#### Possible Ways to Fix It #### Possible Ways to Fix It
Upgrade Next.js to 9.5.4 or later, which does not require `next-head-count`. Ensure that your `_document.js` is importing and rendering all of the [required components](https://nextjs.org/docs/advanced-features/custom-document).
If you can't upgrade right now, ensure that your `_document.js` is importing and rendering all of the [required components](https://nextjs.org/docs/advanced-features/custom-document).
In this case you are most likely not rendering the `<Head>` component imported from `next/document`. In this case you are most likely not rendering the `<Head>` component imported from `next/document`.
import { createElement } from 'react'
import { HeadEntry } from '../next-server/lib/utils'
const DOMAttributeNames: Record<string, string> = { const DOMAttributeNames: Record<string, string> = {
acceptCharset: 'accept-charset', acceptCharset: 'accept-charset',
className: 'class', className: 'class',
...@@ -35,68 +32,51 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement { ...@@ -35,68 +32,51 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement {
return el return el
} }
function updateElements( function updateElements(type: string, components: JSX.Element[]) {
elements: Set<Element>,
components: JSX.Element[],
removeOldTags: boolean
) {
const headEl = document.getElementsByTagName('head')[0] const headEl = document.getElementsByTagName('head')[0]
const oldTags = new Set(elements) const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]'
components.forEach((tag) => { ) as HTMLMetaElement
if (tag.type === 'title') { if (process.env.NODE_ENV !== 'production') {
let title = '' if (!headCountEl) {
if (tag) { console.error(
const { children } = tag.props 'Warning: next-head-count is missing. https://err.sh/next.js/next-head-count-missing'
title = )
typeof children === 'string'
? children
: Array.isArray(children)
? children.join('')
: ''
}
if (title !== document.title) document.title = title
return return
} }
}
const newTag = reactElementToDOM(tag) const headCount = Number(headCountEl.content)
const elementIter = elements.values() const oldTags: Element[] = []
while (true) {
// Note: We don't use for-of here to avoid needing to polyfill it.
const { done, value } = elementIter.next()
if (value?.isEqualNode(newTag)) {
oldTags.delete(value)
return
}
if (done) { for (
break let i = 0, j = headCountEl.previousElementSibling;
i < headCount;
i++, j = j!.previousElementSibling
) {
if (j!.tagName.toLowerCase() === type) {
oldTags.push(j!)
}
}
const newTags = (components.map(reactElementToDOM) as HTMLElement[]).filter(
(newTag) => {
for (let k = 0, len = oldTags.length; k < len; k++) {
const oldTag = oldTags[k]
if (oldTag.isEqualNode(newTag)) {
oldTags.splice(k, 1)
return false
}
} }
return true
} }
)
elements.add(newTag) oldTags.forEach((t) => t.parentNode!.removeChild(t))
headEl.appendChild(newTag) newTags.forEach((t) => headEl.insertBefore(t, headCountEl))
}) headCountEl.content = (headCount - oldTags.length + newTags.length).toString()
oldTags.forEach((oldTag) => {
if (removeOldTags) {
oldTag.parentNode!.removeChild(oldTag)
}
elements.delete(oldTag)
})
} }
export default function initHeadManager(initialHeadEntries: HeadEntry[]) { export default function initHeadManager() {
const headEl = document.getElementsByTagName('head')[0]
const elements = new Set<Element>(headEl.children)
updateElements(
elements,
initialHeadEntries.map(([type, props]) => createElement(type, props)),
false
)
let updatePromise: Promise<void> | null = null let updatePromise: Promise<void> | null = null
return { return {
...@@ -106,7 +86,29 @@ export default function initHeadManager(initialHeadEntries: HeadEntry[]) { ...@@ -106,7 +86,29 @@ export default function initHeadManager(initialHeadEntries: HeadEntry[]) {
if (promise !== updatePromise) return if (promise !== updatePromise) return
updatePromise = null updatePromise = null
updateElements(elements, head, true) const tags: Record<string, JSX.Element[]> = {}
head.forEach((h) => {
const components = tags[h.type] || []
components.push(h)
tags[h.type] = components
})
const titleComponent = tags.title ? tags.title[0] : null
let title = ''
if (titleComponent) {
const { children } = titleComponent.props
title =
typeof children === 'string'
? children
: Array.isArray(children)
? children.join('')
: ''
}
if (title !== document.title) document.title = title
;['meta', 'base', 'link', 'style', 'script'].forEach((type) => {
updateElements(type, tags[type] || [])
})
})) }))
}, },
} }
......
...@@ -63,7 +63,6 @@ const { ...@@ -63,7 +63,6 @@ const {
runtimeConfig, runtimeConfig,
dynamicIds, dynamicIds,
isFallback, isFallback,
head: initialHeadData,
locales, locales,
} = data } = data
...@@ -144,7 +143,7 @@ if (window.__NEXT_P) { ...@@ -144,7 +143,7 @@ if (window.__NEXT_P) {
window.__NEXT_P = [] window.__NEXT_P = []
;(window.__NEXT_P as any).push = register ;(window.__NEXT_P as any).push = register
const headManager = initHeadManager(initialHeadData) const headManager = initHeadManager()
const appElement = document.getElementById('__next') const appElement = document.getElementById('__next')
let lastAppProps: AppProps let lastAppProps: AppProps
......
...@@ -81,8 +81,6 @@ export type BaseContext = { ...@@ -81,8 +81,6 @@ export type BaseContext = {
[k: string]: any [k: string]: any
} }
export type HeadEntry = [string, { [key: string]: any }]
export type NEXT_DATA = { export type NEXT_DATA = {
props: Record<string, any> props: Record<string, any>
page: string page: string
...@@ -100,7 +98,6 @@ export type NEXT_DATA = { ...@@ -100,7 +98,6 @@ export type NEXT_DATA = {
customServer?: boolean customServer?: boolean
gip?: boolean gip?: boolean
appGip?: boolean appGip?: boolean
head: HeadEntry[]
locale?: string locale?: string
locales?: string[] locales?: string[]
defaultLocale?: string defaultLocale?: string
......
...@@ -259,22 +259,6 @@ function renderDocument( ...@@ -259,22 +259,6 @@ function renderDocument(
locale, locale,
locales, locales,
defaultLocale, defaultLocale,
head: React.Children.toArray(docProps.head || [])
.map((elem) => {
const { children } = elem?.props
return [
elem?.type,
{
...elem?.props,
children: children
? typeof children === 'string'
? children
: children.join('')
: undefined,
},
]
})
.filter(Boolean) as any,
}, },
buildManifest, buildManifest,
docComponentsRendered, docComponentsRendered,
......
...@@ -445,6 +445,10 @@ export class Head extends Component< ...@@ -445,6 +445,10 @@ export class Head extends Component<
)} )}
{children} {children}
{head} {head}
<meta
name="next-head-count"
content={React.Children.count(head || []).toString()}
/>
{inAmpMode && ( {inAmpMode && (
<> <>
<meta <meta
......
...@@ -118,7 +118,7 @@ describe('Build Output', () => { ...@@ -118,7 +118,7 @@ describe('Build Output', () => {
expect(parseFloat(webpackSize) - 753).toBeLessThanOrEqual(0) expect(parseFloat(webpackSize) - 753).toBeLessThanOrEqual(0)
expect(webpackSize.endsWith(' B')).toBe(true) expect(webpackSize.endsWith(' B')).toBe(true)
expect(parseFloat(mainSize) - 7.45).toBeLessThanOrEqual(0) expect(parseFloat(mainSize) - 7.3).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true) expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(frameworkSize) - 42).toBeLessThanOrEqual(0) expect(parseFloat(frameworkSize) - 42).toBeLessThanOrEqual(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