Unverified Commit 89d2abdf authored by Sebastian Silbermann's avatar Sebastian Silbermann Committed by GitHub

Pages router: Use attribute-based head children reconciler when `strictNextHead`…

Pages router: Use attribute-based head children reconciler when `strictNextHead` is enabled (#65408)

Closes NEXT-3326
parent ddc507fe
...@@ -51,62 +51,56 @@ export function isEqualNode(oldTag: Element, newTag: Element) { ...@@ -51,62 +51,56 @@ export function isEqualNode(oldTag: Element, newTag: Element) {
let updateElements: (type: string, components: JSX.Element[]) => void let updateElements: (type: string, components: JSX.Element[]) => void
if (process.env.__NEXT_STRICT_NEXT_HEAD) { if (process.env.__NEXT_STRICT_NEXT_HEAD) {
updateElements = (type: string, components: JSX.Element[]) => { updateElements = (type, components) => {
const headEl = document.querySelector('head') const headEl = document.querySelector('head')
if (!headEl) return if (!headEl) return
const headMetaTags = headEl.querySelectorAll('meta[name="next-head"]') || [] const oldTags = new Set(headEl.querySelectorAll(`${type}[data-next-head]`))
const oldTags: Element[] = []
if (type === 'meta') { if (type === 'meta') {
const metaCharset = headEl.querySelector('meta[charset]') const metaCharset = headEl.querySelector('meta[charset]')
if (metaCharset) { if (metaCharset !== null) {
oldTags.push(metaCharset) oldTags.add(metaCharset)
} }
} }
for (let i = 0; i < headMetaTags.length; i++) { const newTags: Element[] = []
const metaTag = headMetaTags[i] for (let i = 0; i < components.length; i++) {
const headTag = metaTag.nextSibling as Element const component = components[i]
const newTag = reactElementToDOM(component)
if (headTag?.tagName?.toLowerCase() === type) { newTag.setAttribute('data-next-head', '')
oldTags.push(headTag)
} let isNew = true
} for (const oldTag of oldTags) {
const newTags = (components.map(reactElementToDOM) as HTMLElement[]).filter( if (isEqualNode(oldTag, newTag)) {
(newTag) => { oldTags.delete(oldTag)
for (let k = 0, len = oldTags.length; k < len; k++) { isNew = false
const oldTag = oldTags[k] break
if (isEqualNode(oldTag, newTag)) {
oldTags.splice(k, 1)
return false
}
} }
return true
} }
)
oldTags.forEach((t) => { if (isNew) {
const metaTag = t.previousSibling as Element newTags.push(newTag)
if (metaTag && metaTag.getAttribute('name') === 'next-head') {
t.parentNode?.removeChild(metaTag)
} }
t.parentNode?.removeChild(t) }
})
newTags.forEach((t) => { for (const oldTag of oldTags) {
const meta = document.createElement('meta') oldTag.parentNode?.removeChild(oldTag)
meta.name = 'next-head' }
meta.content = '1'
for (const newTag of newTags) {
// meta[charset] must be first element so special case // meta[charset] must be first element so special case
if (!(t.tagName?.toLowerCase() === 'meta' && t.getAttribute('charset'))) { if (
headEl.appendChild(meta) newTag.tagName.toLowerCase() === 'meta' &&
newTag.getAttribute('charset') !== null
) {
headEl.prepend(newTag)
} }
headEl.appendChild(t) headEl.appendChild(newTag)
}) }
} }
} else { } else {
updateElements = (type: string, components: JSX.Element[]) => { updateElements = (type, components) => {
const headEl = document.getElementsByTagName('head')[0] const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector( const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]' 'meta[name=next-head-count]'
......
...@@ -682,30 +682,29 @@ export class Head extends React.Component<HeadProps> { ...@@ -682,30 +682,29 @@ export class Head extends React.Component<HeadProps> {
let cssPreloads: Array<JSX.Element> = [] let cssPreloads: Array<JSX.Element> = []
let otherHeadElements: Array<JSX.Element> = [] let otherHeadElements: Array<JSX.Element> = []
if (head) { if (head) {
head.forEach((c) => { head.forEach((child) => {
let metaTag
if (this.context.strictNextHead) {
metaTag = React.createElement('meta', {
name: 'next-head',
content: '1',
})
}
if ( if (
c && child &&
c.type === 'link' && child.type === 'link' &&
c.props['rel'] === 'preload' && child.props['rel'] === 'preload' &&
c.props['as'] === 'style' child.props['as'] === 'style'
) { ) {
metaTag && cssPreloads.push(metaTag) if (this.context.strictNextHead) {
cssPreloads.push(c) cssPreloads.push(
React.cloneElement(child, { 'data-next-head': '' })
)
} else {
cssPreloads.push(child)
}
} else { } else {
if (c) { if (child) {
if (metaTag && (c.type !== 'meta' || !c.props['charSet'])) { if (this.context.strictNextHead) {
otherHeadElements.push(metaTag) otherHeadElements.push(
React.cloneElement(child, { 'data-next-head': '' })
)
} else {
otherHeadElements.push(child)
} }
otherHeadElements.push(c)
} }
} }
}) })
......
...@@ -1683,6 +1683,9 @@ describe.each([[false], [true]])( ...@@ -1683,6 +1683,9 @@ describe.each([[false], [true]])(
expect( expect(
Number(await browser.eval('window.__test_async_executions')) Number(await browser.eval('window.__test_async_executions'))
).toBe(1) ).toBe(1)
expect(
Number(await browser.eval('window.__test_defer_executions'))
).toBe(1)
await browser.elementByCss('#toggleScript').click() await browser.elementByCss('#toggleScript').click()
await waitFor(2000) await waitFor(2000)
...@@ -1690,6 +1693,9 @@ describe.each([[false], [true]])( ...@@ -1690,6 +1693,9 @@ describe.each([[false], [true]])(
expect( expect(
Number(await browser.eval('window.__test_async_executions')) Number(await browser.eval('window.__test_async_executions'))
).toBe(1) ).toBe(1)
expect(
Number(await browser.eval('window.__test_defer_executions'))
).toBe(1)
} finally { } finally {
if (browser) { if (browser) {
await browser.close() await browser.close()
......
...@@ -43,8 +43,8 @@ describe('Client Navigation rendering', () => { ...@@ -43,8 +43,8 @@ describe('Client Navigation rendering', () => {
describe('Rendering via HTTP', () => { describe('Rendering via HTTP', () => {
test('renders a stateless component', async () => { test('renders a stateless component', async () => {
const html = await render('/stateless') const html = await render('/stateless')
expect(html.includes('<meta charSet="utf-8"/>')).toBeTruthy() expect(html).toContain('<meta charSet="utf-8" data-next-head=""/>')
expect(html.includes('My component!')).toBeTruthy() expect(html).toContain('My component!')
}) })
it('should should not contain scripts that are not js', async () => { it('should should not contain scripts that are not js', async () => {
...@@ -349,55 +349,89 @@ describe.each([[false], [true]])( ...@@ -349,55 +349,89 @@ describe.each([[false], [true]])(
// default-head contains an empty <Head />. // default-head contains an empty <Head />.
test('header renders default charset', async () => { test('header renders default charset', async () => {
const html = await render('/default-head') const html = await render('/default-head')
expect(html.includes('<meta charSet="utf-8"/>')).toBeTruthy() expect(html).toContain(
expect(html.includes('next-head, but only once.')).toBeTruthy() strictNextHead
? '<meta charSet="utf-8" data-next-head=""/>'
: '<meta charSet="utf-8"/>'
)
expect(html).toContain('next-head, but only once.')
}) })
test('header renders default viewport', async () => { test('header renders default viewport', async () => {
const html = await render('/default-head') const html = await render('/default-head')
expect(html).toContain( expect(html).toContain(
'<meta name="viewport" content="width=device-width"/>' strictNextHead
? '<meta name="viewport" content="width=device-width" data-next-head=""/>'
: '<meta name="viewport" content="width=device-width"/>'
) )
}) })
test('header helper renders header information', async () => { test('header helper renders header information', async () => {
const html = await render('/head') const html = await render('/head')
expect(html.includes('<meta charSet="iso-8859-5"/>')).toBeTruthy()
expect(html.includes('<meta content="my meta"/>')).toBeTruthy()
expect(html).toContain( expect(html).toContain(
'<meta name="viewport" content="width=device-width,initial-scale=1"/>' strictNextHead
? '<meta charSet="iso-8859-5" data-next-head=""/>'
: '<meta charSet="iso-8859-5"/>'
)
expect(html).toContain(
strictNextHead
? '<meta content="my meta" data-next-head=""/>'
: '<meta content="my meta"/>'
)
expect(html).toContain(
strictNextHead
? '<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>'
: '<meta name="viewport" content="width=device-width,initial-scale=1"/>'
) )
expect(html.includes('I can have meta tags')).toBeTruthy() expect(html).toContain('I can have meta tags')
}) })
test('header helper dedupes tags', async () => { test('header helper dedupes tags', async () => {
const html = await render('/head') const html = await render('/head')
expect(html).toContain('<meta charSet="iso-8859-5"/>')
expect(html).not.toContain('<meta charSet="utf-8"/>')
expect(html).toContain( expect(html).toContain(
'<meta name="viewport" content="width=device-width,initial-scale=1"/>' strictNextHead
? '<meta charSet="iso-8859-5" data-next-head=""/>'
: '<meta charSet="iso-8859-5"/>'
)
expect(html).not.toContain(
strictNextHead
? '<meta charSet="utf-8" data-next-head=""/>'
: '<meta charSet="utf-8"/>'
)
expect(html).toContain(
strictNextHead
? '<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>'
: '<meta name="viewport" content="width=device-width,initial-scale=1"/>'
) )
// Should contain only one viewport // Should contain only one viewport
expect(html.match(/<meta name="viewport" /g).length).toBe(1) expect(html.match(/<meta name="viewport" /g).length).toBe(1)
expect(html).not.toContain( expect(html).not.toContain(
'<meta name="viewport" content="width=device-width"/>' '<meta name="viewport" content="width=device-width"'
) )
expect(html).toContain('<meta content="my meta"/>')
expect(html).toContain( expect(html).toContain(
strictNextHead strictNextHead
? '<link rel="stylesheet" href="/dup-style.css"/><meta name="next-head" content="1"/><link rel="stylesheet" href="/dup-style.css"/>' ? '<meta content="my meta" data-next-head=""/>'
: '<meta content="my meta"/>'
)
expect(html).toContain(
strictNextHead
? '<link rel="stylesheet" href="/dup-style.css" data-next-head=""/><link rel="stylesheet" href="/dup-style.css" data-next-head=""/>'
: '<link rel="stylesheet" href="/dup-style.css"/><link rel="stylesheet" href="/dup-style.css"/>' : '<link rel="stylesheet" href="/dup-style.css"/><link rel="stylesheet" href="/dup-style.css"/>'
) )
const dedupeLink = '<link rel="stylesheet" href="dedupe-style.css"/>' const dedupeLink = strictNextHead
? '<link rel="stylesheet" href="dedupe-style.css" data-next-head=""/>'
: '<link rel="stylesheet" href="dedupe-style.css"/>'
expect(html).toContain(dedupeLink) expect(html).toContain(dedupeLink)
expect( expect(
html.substring(html.indexOf(dedupeLink) + dedupeLink.length) html.substring(html.indexOf(dedupeLink) + dedupeLink.length)
).not.toContain('<link rel="stylesheet" href="dedupe-style.css"/>') ).not.toContain('<link rel="stylesheet" href="dedupe-style.css"')
expect(html).toContain( expect(html).toContain(
'<link rel="alternate" hrefLang="en" href="/last/en"/>' strictNextHead
? '<link rel="alternate" hrefLang="en" href="/last/en" data-next-head=""/>'
: '<link rel="alternate" hrefLang="en" href="/last/en"/>'
) )
expect(html).not.toContain( expect(html).not.toContain(
'<link rel="alternate" hrefLang="en" href="/first/en"/>' '<link rel="alternate" hrefLang="en" href="/first/en"'
) )
}) })
...@@ -407,86 +441,170 @@ describe.each([[false], [true]])( ...@@ -407,86 +441,170 @@ describe.each([[false], [true]])(
expect((html.match(/charSet=/g) || []).length).toBe(1) expect((html.match(/charSet=/g) || []).length).toBe(1)
// Expect exactly one `viewport` // Expect exactly one `viewport`
expect((html.match(/name="viewport"/g) || []).length).toBe(1) expect((html.match(/name="viewport"/g) || []).length).toBe(1)
expect(html).toContain('<meta charSet="iso-8859-1"/>') expect(html).toContain(
expect(html).toContain('<meta name="viewport" content="width=500"/>') strictNextHead
? '<meta charSet="iso-8859-1" data-next-head=""/>'
: '<meta charSet="iso-8859-1"/>'
)
expect(html).toContain(
strictNextHead
? '<meta name="viewport" content="width=500" data-next-head=""/>'
: '<meta name="viewport" content="width=500"/>'
)
}) })
test('header helper avoids dedupe of specific tags', async () => { test('header helper avoids dedupe of specific tags', async () => {
const html = await render('/head') const html = await render('/head')
expect(html).toContain('<meta property="article:tag" content="tag1"/>') console.log(html)
expect(html).toContain('<meta property="article:tag" content="tag2"/>')
expect(html).not.toContain('<meta property="dedupe:tag" content="tag3"/>')
expect(html).toContain('<meta property="dedupe:tag" content="tag4"/>')
expect(html).toContain( expect(html).toContain(
'<meta property="og:image" content="ogImageTag1"/>' strictNextHead
? '<meta property="article:tag" content="tag1" data-next-head=""/>'
: '<meta property="article:tag" content="tag1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image" content="ogImageTag2"/>' strictNextHead
? '<meta property="article:tag" content="tag2" data-next-head=""/>'
: '<meta property="article:tag" content="tag2"/>'
) )
expect(html).not.toContain('<meta property="dedupe:tag" content="tag3"')
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:alt" content="ogImageAltTag1"/>' strictNextHead
? '<meta property="dedupe:tag" content="tag4" data-next-head=""/>'
: '<meta property="dedupe:tag" content="tag4"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:alt" content="ogImageAltTag2"/>' strictNextHead
? '<meta property="og:image" content="ogImageTag1" data-next-head=""/>'
: '<meta property="og:image" content="ogImageTag1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:width" content="ogImageWidthTag1"/>' strictNextHead
? '<meta property="og:image" content="ogImageTag2" data-next-head=""/>'
: '<meta property="og:image" content="ogImageTag2"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:width" content="ogImageWidthTag2"/>' strictNextHead
? '<meta property="og:image:alt" content="ogImageAltTag1" data-next-head=""/>'
: '<meta property="og:image:alt" content="ogImageAltTag1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:height" content="ogImageHeightTag1"/>' strictNextHead
? '<meta property="og:image:alt" content="ogImageAltTag2" data-next-head=""/>'
: '<meta property="og:image:alt" content="ogImageAltTag2"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:height" content="ogImageHeightTag2"/>' strictNextHead
? '<meta property="og:image:width" content="ogImageWidthTag1" data-next-head=""/>'
: '<meta property="og:image:width" content="ogImageWidthTag1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:type" content="ogImageTypeTag1"/>' strictNextHead
? '<meta property="og:image:width" content="ogImageWidthTag2" data-next-head=""/>'
: '<meta property="og:image:width" content="ogImageWidthTag2"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:type" content="ogImageTypeTag2"/>' strictNextHead
? '<meta property="og:image:height" content="ogImageHeightTag1" data-next-head=""/>'
: '<meta property="og:image:height" content="ogImageHeightTag1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:secure_url" content="ogImageSecureUrlTag1"/>' strictNextHead
? '<meta property="og:image:height" content="ogImageHeightTag2" data-next-head=""/>'
: '<meta property="og:image:height" content="ogImageHeightTag2"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:type" content="ogImageTypeTag1" data-next-head=""/>'
: '<meta property="og:image:type" content="ogImageTypeTag1"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:type" content="ogImageTypeTag2" data-next-head=""/>'
: '<meta property="og:image:type" content="ogImageTypeTag2"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:secure_url" content="ogImageSecureUrlTag1" data-next-head=""/>'
: '<meta property="og:image:secure_url" content="ogImageSecureUrlTag1"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:secure_url" content="ogImageSecureUrlTag2" data-next-head=""/>'
: '<meta property="og:image:secure_url" content="ogImageSecureUrlTag2"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:url" content="ogImageUrlTag1" data-next-head=""/>'
: '<meta property="og:image:url" content="ogImageUrlTag1"/>'
)
expect(html).toContain(
strictNextHead
? '<meta property="og:image:url" content="ogImageUrlTag2" data-next-head=""/>'
: '<meta property="og:image:url" content="ogImageUrlTag2"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:secure_url" content="ogImageSecureUrlTag2"/>' strictNextHead
? '<meta property="fb:pages" content="fbpages1" data-next-head=""/>'
: '<meta property="fb:pages" content="fbpages1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta property="og:image:url" content="ogImageUrlTag1"/>' strictNextHead
? '<meta property="fb:pages" content="fbpages2" data-next-head=""/>'
: '<meta property="fb:pages" content="fbpages2"/>'
) )
expect(html).toContain('<meta property="fb:pages" content="fbpages1"/>')
expect(html).toContain('<meta property="fb:pages" content="fbpages2"/>')
}) })
test('header helper avoids dedupe of meta tags with the same name if they use unique keys', async () => { test('header helper avoids dedupe of meta tags with the same name if they use unique keys', async () => {
const html = await render('/head') const html = await render('/head')
expect(html).toContain( expect(html).toContain(
'<meta name="citation_author" content="authorName1"/>' strictNextHead
? '<meta name="citation_author" content="authorName1" data-next-head=""/>'
: '<meta name="citation_author" content="authorName1"/>'
) )
expect(html).toContain( expect(html).toContain(
'<meta name="citation_author" content="authorName2"/>' strictNextHead
? '<meta name="citation_author" content="authorName2" data-next-head=""/>'
: '<meta name="citation_author" content="authorName2"/>'
) )
}) })
test('header helper renders Fragment children', async () => { test('header helper renders Fragment children', async () => {
const html = await render('/head') const html = await render('/head')
expect(html).toContain('<title>Fragment title</title>') expect(html).toContain(
expect(html).toContain('<meta content="meta fragment"/>') strictNextHead
? '<title data-next-head="">Fragment title</title>'
: '<title>Fragment title</title>'
)
expect(html).toContain(
strictNextHead
? '<meta content="meta fragment" data-next-head=""/>'
: '<meta content="meta fragment"/>'
)
}) })
test('header helper renders boolean attributes correctly children', async () => { test('header helper renders boolean attributes correctly children', async () => {
const html = await render('/head') const html = await render('/head')
expect(html).toContain('<script src="/test-async-true.js" async="">') expect(html).toContain(
expect(html).toContain('<script src="/test-async-false.js">') strictNextHead
expect(html).toContain('<script src="/test-defer.js" defer="">') ? '<script src="/test-async-false.js" data-next-head="">'
: '<script src="/test-async-false.js">'
)
expect(html).toContain(
strictNextHead
? '<script src="/test-async-true.js" async="" data-next-head="">'
: ''
)
expect(html).toContain(
strictNextHead
? '<script src="/test-defer.js" defer="" data-next-head="">'
: ''
)
}) })
it('should place charset element at the top of <head>', async () => { it('should place charset element at the top of <head>', async () => {
const html = await render('/head-priority') const html = await render('/head-priority')
const nextHeadElement = strictNextHead const nextHeadElement = strictNextHead
? '<meta charSet="iso-8859-5"/><meta name="next-head" content="1"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="next-head" content="1"/><meta name="title" content="head title"/>' ? '<meta charSet="iso-8859-5" data-next-head=""/><meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/><meta name="title" content="head title" data-next-head=""/>'
: '<meta charSet="iso-8859-5"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="title" content="head title"/><meta name="next-head-count" content="3"/>' : '<meta charSet="iso-8859-5"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="title" content="head title"/><meta name="next-head-count" content="3"/>'
const documentHeadElement = const documentHeadElement =
'<meta name="keywords" content="document head test"/>' '<meta name="keywords" content="document head test"/>'
......
...@@ -32,7 +32,7 @@ describe('next/head', () => { ...@@ -32,7 +32,7 @@ describe('next/head', () => {
}) })
expect(html).toContain( expect(html).toContain(
`<meta charset="utf-8"><meta name="next-head" content="1"><meta name="viewport" content="width=device-width"><meta name="next-head" content="1"><meta name="test-head-1" content="hello">` `<meta charset="utf-8" data-next-head=""><meta name="viewport" content="width=device-width" data-next-head=""><meta name="test-head-1" content="hello" data-next-head="">`
) )
}) })
......
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