Unverified Commit 6556a342 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

fix: hydration error display for text under tag case (#63288)

There's a type of hydration warning is mismatch `"text content"` under a
`<tag>`, such as `Did not expect server HTML to contain the text node
"bad text" in <div>.`, we need to treate them separately from the text
diff or bad neseting tags.

### After

![image](https://github.com/vercel/next.js/assets/4800338/4dabfeae-b42a-4232-ab55-1704db36f5ce)


### Before


![image](https://github.com/vercel/next.js/assets/4800338/1da14435-cb3a-4883-84c8-7f0ce4c83b21)


Closes NEXT-2819
parent 847b3401
...@@ -25,8 +25,8 @@ import { getErrorSource } from '../../../../../shared/lib/error-source' ...@@ -25,8 +25,8 @@ import { getErrorSource } from '../../../../../shared/lib/error-source'
import { HotlinkedText } from '../components/hot-linked-text' import { HotlinkedText } from '../components/hot-linked-text'
import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html' import { PseudoHtmlDiff } from './RuntimeError/component-stack-pseudo-html'
import { import {
isHtmlTagsWarning,
type HydrationErrorState, type HydrationErrorState,
getHydrationWarningType,
} from '../helpers/hydration-error-info' } from '../helpers/hydration-error-info'
export type SupportedErrorEvent = { export type SupportedErrorEvent = {
...@@ -226,7 +226,7 @@ export function Errors({ ...@@ -226,7 +226,7 @@ export function Errors({
const [warningTemplate, serverContent, clientContent] = const [warningTemplate, serverContent, clientContent] =
errorDetails.warning || [null, '', ''] errorDetails.warning || [null, '', '']
const isHtmlTagsWarningTemplate = isHtmlTagsWarning(warningTemplate) const hydrationErrorType = getHydrationWarningType(warningTemplate)
const hydrationWarning = warningTemplate const hydrationWarning = warningTemplate
? warningTemplate ? warningTemplate
.replace('%s', serverContent) .replace('%s', serverContent)
...@@ -274,12 +274,10 @@ export function Errors({ ...@@ -274,12 +274,10 @@ export function Errors({
<p id="nextjs__container_errors__extra">{hydrationWarning}</p> <p id="nextjs__container_errors__extra">{hydrationWarning}</p>
<PseudoHtmlDiff <PseudoHtmlDiff
className="nextjs__container_errors__extra_code" className="nextjs__container_errors__extra_code"
hydrationMismatchType={ hydrationMismatchType={hydrationErrorType}
isHtmlTagsWarningTemplate ? 'tag' : 'text'
}
componentStackFrames={activeError.componentStackFrames} componentStackFrames={activeError.componentStackFrames}
serverContent={serverContent} firstContent={serverContent}
clientContent={clientContent} secondContent={clientContent}
/> />
</> </>
)} )}
......
...@@ -37,15 +37,15 @@ import { CollapseIcon } from '../../icons/CollapseIcon' ...@@ -37,15 +37,15 @@ import { CollapseIcon } from '../../icons/CollapseIcon'
*/ */
export function PseudoHtmlDiff({ export function PseudoHtmlDiff({
componentStackFrames, componentStackFrames,
serverContent, firstContent,
clientContent, secondContent,
hydrationMismatchType, hydrationMismatchType,
...props ...props
}: { }: {
componentStackFrames: ComponentStackFrame[] componentStackFrames: ComponentStackFrame[]
serverContent: string firstContent: string
clientContent: string secondContent: string
hydrationMismatchType: 'tag' | 'text' hydrationMismatchType: 'tag' | 'text' | 'text-in-tag'
} & React.HTMLAttributes<HTMLPreElement>) { } & React.HTMLAttributes<HTMLPreElement>) {
const isHtmlTagsWarning = hydrationMismatchType === 'tag' const isHtmlTagsWarning = hydrationMismatchType === 'tag'
// For text mismatch, mismatched text will take 2 rows, so we display 4 rows of component stack // For text mismatch, mismatched text will take 2 rows, so we display 4 rows of component stack
...@@ -54,7 +54,7 @@ export function PseudoHtmlDiff({ ...@@ -54,7 +54,7 @@ export function PseudoHtmlDiff({
const [isHtmlCollapsed, toggleCollapseHtml] = useState(shouldCollapse) const [isHtmlCollapsed, toggleCollapseHtml] = useState(shouldCollapse)
const htmlComponents = useMemo(() => { const htmlComponents = useMemo(() => {
const tagNames = isHtmlTagsWarning ? [serverContent, clientContent] : [] const tagNames = isHtmlTagsWarning ? [firstContent, secondContent] : []
const nestedHtmlStack: React.ReactNode[] = [] const nestedHtmlStack: React.ReactNode[] = []
let lastText = '' let lastText = ''
...@@ -131,18 +131,33 @@ export function PseudoHtmlDiff({ ...@@ -131,18 +131,33 @@ export function PseudoHtmlDiff({
} }
}) })
if (hydrationMismatchType === 'text') { // Hydration mismatch: text or text-tag
if (!isHtmlTagsWarning) {
const spaces = ' '.repeat(nestedHtmlStack.length * 2) const spaces = ' '.repeat(nestedHtmlStack.length * 2)
const wrappedCodeLine = ( let wrappedCodeLine
<Fragment key={nestedHtmlStack.length}> if (hydrationMismatchType === 'text') {
<span data-nextjs-container-errors-pseudo-html--diff-remove> // hydration type is "text", represent [server content, client content]
{spaces + `"${serverContent}"\n`} wrappedCodeLine = (
</span> <Fragment key={nestedHtmlStack.length}>
<span data-nextjs-container-errors-pseudo-html--diff-add> <span data-nextjs-container-errors-pseudo-html--diff-remove>
{spaces + `"${clientContent}"\n`} {spaces + `"${firstContent}"\n`}
</span> </span>
</Fragment> <span data-nextjs-container-errors-pseudo-html--diff-add>
) {spaces + `"${secondContent}"\n`}
</span>
</Fragment>
)
} else {
// hydration type is "text-in-tag", represent [parent tag, mismatch content]
wrappedCodeLine = (
<Fragment key={nestedHtmlStack.length}>
<span>{spaces + `<${secondContent}>\n`}</span>
<span data-nextjs-container-errors-pseudo-html--diff-remove>
{spaces + ` "${firstContent}"\n`}
</span>
</Fragment>
)
}
nestedHtmlStack.push(wrappedCodeLine) nestedHtmlStack.push(wrappedCodeLine)
} }
...@@ -150,8 +165,8 @@ export function PseudoHtmlDiff({ ...@@ -150,8 +165,8 @@ export function PseudoHtmlDiff({
}, [ }, [
componentStackFrames, componentStackFrames,
isHtmlCollapsed, isHtmlCollapsed,
clientContent, firstContent,
serverContent, secondContent,
isHtmlTagsWarning, isHtmlTagsWarning,
hydrationMismatchType, hydrationMismatchType,
MAX_NON_COLLAPSED_FRAMES, MAX_NON_COLLAPSED_FRAMES,
......
...@@ -8,14 +8,26 @@ export type HydrationErrorState = { ...@@ -8,14 +8,26 @@ export type HydrationErrorState = {
type NullableText = string | null | undefined type NullableText = string | null | undefined
export const isHtmlTagsWarning = (msg: NullableText) => export const getHydrationWarningType = (
msg: NullableText
): 'tag' | 'text' | 'text-in-tag' => {
if (isHtmlTagsWarning(msg)) return 'tag'
if (isTextInTagsMismatchWarning(msg)) return 'text-in-tag'
return 'text'
}
const isHtmlTagsWarning = (msg: NullableText) =>
Boolean(msg && htmlTagsWarnings.has(msg)) Boolean(msg && htmlTagsWarnings.has(msg))
export const isTextMismatchWarning = (msg: NullableText) => const isTextMismatchWarning = (msg: NullableText) =>
Boolean(msg && textMismatchWarnings.has(msg)) Boolean(msg && textMismatchWarnings.has(msg))
const isTextInTagsMismatchWarning = (msg: NullableText) =>
Boolean(msg && textInTagsMismatchWarnings.has(msg))
const isKnownHydrationWarning = (msg: NullableText) => const isKnownHydrationWarning = (msg: NullableText) =>
isHtmlTagsWarning(msg) || isTextMismatchWarning(msg) isHtmlTagsWarning(msg) ||
isTextInTagsMismatchWarning(msg) ||
isTextMismatchWarning(msg)
export const hydrationErrorState: HydrationErrorState = {} export const hydrationErrorState: HydrationErrorState = {}
...@@ -25,11 +37,13 @@ const htmlTagsWarnings = new Set([ ...@@ -25,11 +37,13 @@ const htmlTagsWarnings = new Set([
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s', 'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s', 'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s',
]) ])
const textMismatchWarnings = new Set([ const textInTagsMismatchWarnings = new Set([
'Warning: Text content did not match. Server: "%s" Client: "%s"%s',
'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s', 'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s',
'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s', 'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s',
]) ])
const textMismatchWarnings = new Set([
'Warning: Text content did not match. Server: "%s" Client: "%s"%s',
])
/** /**
* Patch console.error to capture hydration errors. * Patch console.error to capture hydration errors.
......
...@@ -246,6 +246,29 @@ describe('Error overlay for hydration errors', () => { ...@@ -246,6 +246,29 @@ describe('Error overlay for hydration errors', () => {
`"Did not expect server HTML to contain the text node "only" in <div>."` `"Did not expect server HTML to contain the text node "only" in <div>."`
) )
const pseudoHtml = await session.getRedboxComponentStack()
if (isTurbopack) {
expect(pseudoHtml).toMatchInlineSnapshot(`
"...
<NotFoundErrorBoundary>
<RedirectBoundary>
<RedirectErrorBoundary>
<InnerLayoutRouter>
<Mismatch>
<div>
<div>
"only""
`)
} else {
expect(pseudoHtml).toMatchInlineSnapshot(`
"<Mismatch>
<div>
<div>
"only""
`)
}
await cleanup() await cleanup()
}) })
......
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