Skip to content

Remove next-head-count #16758

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion errors/next-head-count-missing.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ You have a custom `pages/_document.js` that doesn't have the components required

#### Possible Ways to Fix It

Ensure that your `_document.js` is importing and rendering all of the [required components](https://nextjs.org/docs/advanced-features/custom-document).
Upgrade Next.js to 9.5.4 or later, which does not require `next-head-count`.

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`.
104 changes: 51 additions & 53 deletions packages/next/client/head-manager.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { createElement } from 'react'
import { HeadEntry } from '../next-server/lib/utils'

const DOMAttributeNames: Record<string, string> = {
acceptCharset: 'accept-charset',
className: 'class',
Expand Down Expand Up @@ -27,51 +30,63 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement {
return el
}

function updateElements(type: string, components: JSX.Element[]) {
function updateElements(
elements: Set<Element>,
components: JSX.Element[],
removeOldTags: boolean
) {
const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]'
) as HTMLMetaElement
if (process.env.NODE_ENV !== 'production') {
if (!headCountEl) {
console.error(
'Warning: next-head-count is missing. https://err.sh/next.js/next-head-count-missing'
)
const oldTags = new Set(elements)

components.forEach((tag) => {
if (tag.type === 'title') {
let title = ''
if (tag) {
const { children } = tag.props
title = typeof children === 'string' ? children : children.join('')
}
if (title !== document.title) document.title = title
return
}
}

const headCount = Number(headCountEl.content)
const oldTags: Element[] = []
const newTag = reactElementToDOM(tag)
const elementIter = elements.values()

for (
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
}
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) {
break
}
return true
}
)

oldTags.forEach((t) => t.parentNode!.removeChild(t))
newTags.forEach((t) => headEl.insertBefore(t, headCountEl))
headCountEl.content = (headCount - oldTags.length + newTags.length).toString()
elements.add(newTag)
headEl.appendChild(newTag)
})

oldTags.forEach((oldTag) => {
if (removeOldTags) {
oldTag.parentNode!.removeChild(oldTag)
}
elements.delete(oldTag)
})
}

export default function initHeadManager() {
export default function initHeadManager(initialHeadEntries: HeadEntry[]) {
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

return {
Expand All @@ -81,24 +96,7 @@ export default function initHeadManager() {
if (promise !== updatePromise) return

updatePromise = null
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 : children.join('')
}
if (title !== document.title) document.title = title
;['meta', 'base', 'link', 'style', 'script'].forEach((type) => {
updateElements(type, tags[type] || [])
})
updateElements(elements, head, true)
}))
},
}
Expand Down
3 changes: 2 additions & 1 deletion packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const {
runtimeConfig,
dynamicIds,
isFallback,
head: initialHeadData,
} = data

const prefix = assetPrefix || ''
Expand Down Expand Up @@ -94,7 +95,7 @@ if (window.__NEXT_P) {
window.__NEXT_P = []
;(window.__NEXT_P as any).push = register

const headManager = initHeadManager()
const headManager = initHeadManager(initialHeadData)
const appElement = document.getElementById('__next')

let lastAppProps: AppProps
Expand Down
3 changes: 3 additions & 0 deletions packages/next/next-server/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ export type BaseContext = {
[k: string]: any
}

export type HeadEntry = [string, { [key: string]: any }]

export type NEXT_DATA = {
props: Record<string, any>
page: string
Expand All @@ -98,6 +100,7 @@ export type NEXT_DATA = {
customServer?: boolean
gip?: boolean
appGip?: boolean
head: HeadEntry[]
}

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/next/next-server/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,22 @@ function renderDocument(
customServer, // whether the user is using a custom server
gip, // whether the page has getInitialProps
appGip, // whether the _app has getInitialProps
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,
docComponentsRendered,
Expand Down
4 changes: 0 additions & 4 deletions packages/next/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -441,10 +441,6 @@ export class Head extends Component<
)}
{children}
{head}
<meta
name="next-head-count"
content={React.Children.count(head || []).toString()}
/>
{inAmpMode && (
<>
<meta
Expand Down
2 changes: 1 addition & 1 deletion test/integration/build-output/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ describe('Build Output', () => {
expect(parseFloat(webpackSize) - 752).toBeLessThanOrEqual(0)
expect(webpackSize.endsWith(' B')).toBe(true)

expect(parseFloat(mainSize) - 7.1).toBeLessThanOrEqual(0)
expect(parseFloat(mainSize) - 7.44).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true)

expect(parseFloat(frameworkSize) - 41).toBeLessThanOrEqual(0)
Expand Down