Unverified Commit f5f71516 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Improve hydration diff view (#75799)

parent 22e61a3c
import {
isHydrationError,
getDefaultHydrationErrorMessage,
testReactHydrationWarning,
} from '../is-hydration-error'
import {
hydrationErrorState,
......@@ -8,39 +8,50 @@ import {
} from './hydration-error-info'
export function attachHydrationErrorState(error: Error) {
if (
isHydrationError(error) &&
!error.message.includes(
'https://nextjs.org/docs/messages/react-hydration-error'
)
) {
const reactHydrationDiffSegments = getReactHydrationDiffSegments(
error.message
)
let parsedHydrationErrorState: typeof hydrationErrorState = {}
if (reactHydrationDiffSegments) {
const reactHydrationDiffSegments = getReactHydrationDiffSegments(
error.message
)
let parsedHydrationErrorState: typeof hydrationErrorState = {}
const isHydrationWarning = testReactHydrationWarning(error.message)
// If the reactHydrationDiffSegments exists
// and the diff (reactHydrationDiffSegments[1]) exists
// e.g. the hydration diff log error.
if (reactHydrationDiffSegments && reactHydrationDiffSegments[1]) {
parsedHydrationErrorState = {
...(error as any).details,
...hydrationErrorState,
warning: hydrationErrorState.warning || [
getDefaultHydrationErrorMessage(),
],
notes: isHydrationWarning ? '' : reactHydrationDiffSegments[0],
reactOutputComponentDiff: reactHydrationDiffSegments[1],
}
// Cache the `reactOutputComponentDiff` into hydrationErrorState.
// This is only required for now when we still squashed the hydration diff log into hydration error.
// Once the all error is logged to dev overlay in order, this will go away.
hydrationErrorState.reactOutputComponentDiff =
parsedHydrationErrorState.reactOutputComponentDiff
} else {
// Normal runtime error, where it doesn't contain the hydration diff.
// If there's any extra information in the error message to display,
// append it to the error message details property
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
parsedHydrationErrorState = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
warning: hydrationErrorState.warning || [
getDefaultHydrationErrorMessage(),
],
notes: reactHydrationDiffSegments[0],
reactOutputComponentDiff: reactHydrationDiffSegments[1],
}
} else {
// If there's any extra information in the error message to display,
// append it to the error message details property
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
parsedHydrationErrorState = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
}
}
}
;(error as any).details = parsedHydrationErrorState
// Consume the cached hydration diff.
// This is only required for now when we still squashed the hydration diff log into hydration error.
// Once the all error is logged to dev overlay in order, this will go away.
if (hydrationErrorState.reactOutputComponentDiff) {
parsedHydrationErrorState.reactOutputComponentDiff =
hydrationErrorState.reactOutputComponentDiff
}
}
;(error as any).details = parsedHydrationErrorState
}
import { getHydrationErrorStackInfo } from '../is-hydration-error'
import {
getHydrationErrorStackInfo,
testReactHydrationWarning,
} from '../is-hydration-error'
export type HydrationErrorState = {
// Hydration warning template format: <message> <serverContent> <clientContent>
......@@ -28,8 +31,6 @@ const textAndTagsMismatchWarnings = new Set([
'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',
])
const textMismatchWarning =
'Warning: Text content did not match. Server: "%s" Client: "%s"%s'
export const getHydrationWarningType = (
message: NullableText
......@@ -52,28 +53,9 @@ export const getHydrationWarningType = (
const isHtmlTagsWarning = (message: string) => htmlTagsWarnings.has(message)
const isTextMismatchWarning = (message: string) =>
textMismatchWarning === message
const isTextInTagsMismatchWarning = (msg: string) =>
textAndTagsMismatchWarnings.has(msg)
const isKnownHydrationWarning = (message: NullableText) => {
if (typeof message !== 'string') {
return false
}
// React 18 has the `Warning: ` prefix.
// React 19 does not.
const normalizedMessage = message.startsWith('Warning: ')
? message
: `Warning: ${message}`
return (
isHtmlTagsWarning(normalizedMessage) ||
isTextInTagsMismatchWarning(normalizedMessage) ||
isTextMismatchWarning(normalizedMessage)
)
}
export const getReactHydrationDiffSegments = (msg: NullableText) => {
if (msg) {
const { message, diff } = getHydrationErrorStackInfo(msg)
......@@ -90,16 +72,115 @@ export const getReactHydrationDiffSegments = (msg: NullableText) => {
*/
export function storeHydrationErrorStateFromConsoleArgs(...args: any[]) {
const [msg, serverContent, clientContent, componentStack] = args
if (isKnownHydrationWarning(msg)) {
hydrationErrorState.warning = [
let [msg, firstContent, secondContent, ...rest] = args
if (testReactHydrationWarning(msg)) {
// Some hydration warnings has 4 arguments, some has 3, fallback to the last argument
// when the 3rd argument is not the component stack but an empty string
const isReact18 = msg.startsWith('Warning: ')
// For some warnings, there's only 1 argument for template.
// The second argument is the diff or component stack.
if (args.length === 3) {
secondContent = ''
}
const warning: [string, string, string] = [
// remove the last %s from the message
msg,
serverContent,
clientContent,
firstContent,
secondContent,
]
hydrationErrorState.componentStack = componentStack
hydrationErrorState.serverContent = serverContent
hydrationErrorState.clientContent = clientContent
const lastArg = (rest[rest.length - 1] || '').trim()
if (!isReact18) {
hydrationErrorState.reactOutputComponentDiff = lastArg
} else {
hydrationErrorState.reactOutputComponentDiff =
generateHydrationDiffReact18(msg, firstContent, secondContent, lastArg)
}
hydrationErrorState.warning = warning
hydrationErrorState.serverContent = firstContent
hydrationErrorState.clientContent = secondContent
}
}
/*
* Some hydration errors in React 18 does not have the diff in the error message.
* Instead it has the error stack trace which is component stack that we can leverage.
* Will parse the diff from the error stack trace
* e.g.
* Warning: Expected server HTML to contain a matching <div> in <p>.
* at div
* at p
* at div
* at div
* at Page
* output:
* <Page>
* <div>
* <p>
* > <div>
*
*/
function generateHydrationDiffReact18(
message: string,
firstContent: string,
secondContent: string,
lastArg: string
) {
const componentStack = lastArg
let firstIndex = -1
let secondIndex = -1
const hydrationWarningType = getHydrationWarningType(message)
// at div\n at Foo\n at Bar (....)\n -> [div, Foo]
const components = componentStack
.split('\n')
// .reverse()
.map((line: string, index: number) => {
// `<space>at <component> (<location>)` -> `at <component> (<location>)`
line = line.trim()
// extract `<space>at <component>` to `<<component>>`
// e.g. ` at Foo` -> `<Foo>`
const [, component, location] = /at (\w+)( \((.*)\))?/.exec(line) || []
// If there's no location then it's user-land stack frame
if (!location) {
if (component === firstContent && firstIndex === -1) {
firstIndex = index
} else if (component === secondContent && secondIndex === -1) {
secondIndex = index
}
}
return location ? '' : component
})
.filter(Boolean)
.reverse()
let diff = ''
for (let i = 0; i < components.length; i++) {
const component = components[i]
const matchFirstContent =
hydrationWarningType === 'tag' && i === components.length - firstIndex - 1
const matchSecondContent =
hydrationWarningType === 'tag' &&
i === components.length - secondIndex - 1
if (matchFirstContent || matchSecondContent) {
const spaces = ' '.repeat(Math.max(i * 2 - 2, 0) + 2)
diff += `> ${spaces}<${component}>\n`
} else {
const spaces = ' '.repeat(i * 2 + 2)
diff += `${spaces}<${component}>\n`
}
}
if (hydrationWarningType === 'text') {
const spaces = ' '.repeat(components.length * 2)
diff += `+ ${spaces}"${firstContent}"\n`
diff += `- ${spaces}"${secondContent}"\n`
} else if (hydrationWarningType === 'text-in-tag') {
const spaces = ' '.repeat(components.length * 2)
diff += `> ${spaces}<${secondContent}>\n`
diff += `> ${spaces}"${firstContent}"\n`
}
return diff
}
......@@ -24,6 +24,28 @@ export function isReactHydrationErrorMessage(msg: string): boolean {
return reactHydrationStartMessages.some((prefix) => msg.startsWith(prefix))
}
const hydrationWarningRegexes = [
/^In HTML, (.+?) cannot be a child of <(.+?)>\.(.*)\nThis will cause a hydration error\.(.*)/,
/^In HTML, (.+?) cannot be a descendant of <(.+?)>\.\nThis will cause a hydration error\.(.*)/,
/^In HTML, text nodes cannot be a child of <(.+?)>\.\nThis will cause a hydration error\./,
/^In HTML, whitespace text nodes cannot be a child of <(.+?)>\. Make sure you don't have any extra whitespace between tags on each line of your source code\.\nThis will cause a hydration error\./,
/^Expected server HTML to contain a matching <(.+?)> in <(.+?)>\.(.*)/,
/^Did not expect server HTML to contain a <(.+?)> in <(.+?)>\.(.*)/,
/^Expected server HTML to contain a matching text node for "(.+?)" in <(.+?)>\.(.*)/,
/^Did not expect server HTML to contain the text node "(.+?)" in <(.+?)>\.(.*)/,
/^Text content did not match\. Server: "(.+?)" Client: "(.+?)"(.*)/,
]
export function testReactHydrationWarning(msg: string): boolean {
if (typeof msg !== 'string' || !msg) return false
// React 18 has the `Warning: ` prefix.
// React 19 does not.
if (msg.startsWith('Warning: ')) {
msg = msg.slice('Warning: '.length)
}
return hydrationWarningRegexes.some((regex) => regex.test(msg))
}
export function getHydrationErrorStackInfo(rawMessage: string): {
message: string | null
link?: string
......@@ -31,9 +53,28 @@ export function getHydrationErrorStackInfo(rawMessage: string): {
diff?: string
} {
rawMessage = rawMessage.replace(/^Error: /, '')
if (!isReactHydrationErrorMessage(rawMessage)) {
return { message: null }
rawMessage = rawMessage.replace('Warning: ', '')
const isReactHydrationWarning = testReactHydrationWarning(rawMessage)
if (!isReactHydrationErrorMessage(rawMessage) && !isReactHydrationWarning) {
return {
message: null,
link: '',
stack: rawMessage,
diff: '',
}
}
if (isReactHydrationWarning) {
const [message, diffLog] = rawMessage.split('\n\n')
return {
message: message.trim(),
link: reactHydrationErrorDocLink,
stack: '',
diff: (diffLog || '').trim(),
}
}
const firstLineBreak = rawMessage.indexOf('\n')
rawMessage = rawMessage.slice(firstLineBreak + 1).trim()
......
......@@ -186,10 +186,9 @@ export function Errors({
<PseudoHtmlDiff
className="nextjs__container_errors__component-stack"
hydrationMismatchType={hydrationErrorType}
componentStackFrames={activeError.componentStackFrames || []}
firstContent={serverContent}
secondContent={clientContent}
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff}
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff || ''}
/>
) : null}
<Suspense fallback={<div data-nextjs-error-suspended />}>
......
......@@ -13,28 +13,8 @@ const meta: Meta<typeof PseudoHtmlDiff> = {
export default meta
type Story = StoryObj<typeof PseudoHtmlDiff>
const sampleComponentStack = [
{
component: 'div',
canOpenInEditor: false,
},
{
component: 'article',
canOpenInEditor: false,
},
{
component: 'main',
canOpenInEditor: false,
},
{
component: 'Home',
canOpenInEditor: false,
},
]
export const TextMismatch: Story = {
args: {
componentStackFrames: sampleComponentStack,
firstContent: 'Server rendered content',
secondContent: 'Client rendered content',
hydrationMismatchType: 'text',
......@@ -44,7 +24,6 @@ export const TextMismatch: Story = {
export const TextInTagMismatch: Story = {
args: {
componentStackFrames: sampleComponentStack,
firstContent: 'Mismatched content',
secondContent: 'p',
hydrationMismatchType: 'text-in-tag',
......@@ -54,7 +33,6 @@ export const TextInTagMismatch: Story = {
export const ReactUnifiedMismatch: Story = {
args: {
componentStackFrames: sampleComponentStack,
hydrationMismatchType: 'tag',
reactOutputComponentDiff: `<Page>
<Layout>
......
import { useMemo, useState } from 'react'
import { CollapseIcon } from '../internal/icons/CollapseIcon'
/**
*
* Format component stack into pseudo HTML
* component stack is an array of strings, e.g.: ['p', 'p', 'Page', ...]
*
* For html tags mismatch, it will render it for the code block
*
* ```
* <pre>
* <code>{`
* <Page>
* <p red>
* <p red>
* `}</code>
* </pre>
* ```
*
* For text mismatch, it will render it for the code block
*
* ```
* <pre>
* <code>{`
* <Page>
* <p>
* "Server Text" (green)
* "Client Text" (red)
* </p>
* </Page>
* `}</code>
* ```
*
* For bad text under a tag it will render it for the code block,
* e.g. "Mismatched Text" under <p>
*
* ```
* <pre>
* <code>{`
* <Page>
* <div>
* <p>
* "Mismatched Text" (red)
* </p>
* </div>
* </Page>
* `}</code>
* ```
*
*/
export function PseudoHtmlDiff({
firstContent,
secondContent,
hydrationMismatchType,
reactOutputComponentDiff,
...props
}: {
firstContent: string
secondContent: string
reactOutputComponentDiff: string
hydrationMismatchType: 'tag' | 'text' | 'text-in-tag'
} & React.HTMLAttributes<HTMLPreElement>) {
const [isDiffCollapsed, toggleCollapseHtml] = useState(true)
const htmlComponents = useMemo(() => {
const componentStacks: React.ReactNode[] = []
const reactComponentDiffLines = reactOutputComponentDiff!.split('\n')
reactComponentDiffLines.forEach((line, index) => {
let trimmedLine = line.trim()
const isDiffLine = trimmedLine[0] === '+' || trimmedLine[0] === '-'
const isHighlightedLine = trimmedLine[0] === '>'
const hasSign = isDiffLine || isHighlightedLine
const sign = hasSign ? trimmedLine[0] : ''
const signIndex = hasSign ? line.indexOf(sign) : -1
const [prefix, suffix] = hasSign
? [line.slice(0, signIndex), line.slice(signIndex + 1)]
: [line, '']
if (isDiffLine) {
componentStacks.push(
<span
key={'comp-diff' + index}
data-nextjs-container-errors-pseudo-html-line
data-nextjs-container-errors-pseudo-html--diff={
sign === '+' ? 'add' : 'remove'
}
>
<span>
{/* Slice 2 spaces for the icon */}
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
</span>
)
} else {
// In general, if it's not collapsed, show the whole diff
componentStacks.push(
<span
data-nextjs-container-errors-pseudo-html-line
key={'comp-diff' + index}
{...(isHighlightedLine
? {
'data-nextjs-container-errors-pseudo-html-line--error': true,
}
: undefined)}
>
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
)
}
})
return componentStacks
}, [reactOutputComponentDiff])
return (
<div
data-nextjs-container-errors-pseudo-html
data-nextjs-container-errors-pseudo-html-collapse={isDiffCollapsed}
>
<button
tabIndex={10} // match CallStackFrame
data-nextjs-container-errors-pseudo-html-collapse-button
onClick={() => toggleCollapseHtml(!isDiffCollapsed)}
>
<CollapseIcon collapsed={isDiffCollapsed} />
</button>
<pre {...props}>
<code>{htmlComponents}</code>
</pre>
</div>
)
}
......@@ -381,10 +381,11 @@ export function Errors({
<PseudoHtmlDiff
className="nextjs__container_errors__component-stack"
hydrationMismatchType={hydrationErrorType}
componentStackFrames={activeError.componentStackFrames || []}
firstContent={serverContent}
secondContent={clientContent}
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff}
reactOutputComponentDiff={
errorDetails.reactOutputComponentDiff || ''
}
/>
) : null}
{isServerError ? (
......
......@@ -201,35 +201,4 @@ export const styles = css`
[data-nextjs-collapsed-call-stack-details] [data-nextjs-call-stack-frame] {
margin-bottom: var(--size-gap-double);
}
[data-nextjs-container-errors-pseudo-html] {
position: relative;
}
[data-nextjs-container-errors-pseudo-html-collapse] {
position: absolute;
left: 10px;
top: 10px;
color: inherit;
background: none;
border: none;
padding: 0;
}
[data-nextjs-container-errors-pseudo-html--diff='add'] {
color: var(--color-ansi-green);
}
[data-nextjs-container-errors-pseudo-html--diff='remove'] {
color: var(--color-ansi-red);
}
[data-nextjs-container-errors-pseudo-html--tag-error] {
color: var(--color-ansi-red);
font-weight: bold;
}
/* hide but text are still accessible in DOM */
[data-nextjs-container-errors-pseudo-html--hint] {
display: inline-block;
font-size: 0;
}
[data-nextjs-container-errors-pseudo-html--tag-adjacent='false'] {
color: var(--color-accents-1);
}
`
......@@ -8,6 +8,7 @@ import { styles as versionStaleness } from '../components/VersionStalenessInfo'
import { styles as buildErrorStyles } from '../container/BuildError'
import { styles as containerErrorStyles } from '../container/Errors'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { styles as pseudoHtmlStyles } from '../container/RuntimeError/component-stack-pseudo-html'
import { noop as css } from '../helpers/noop-template'
export function ComponentStyles() {
......@@ -24,6 +25,7 @@ export function ComponentStyles() {
${containerErrorStyles}
${containerRuntimeErrorStyles}
${versionStaleness}
${pseudoHtmlStyles}
`}
</style>
)
......
'use client'
export default function Page() {
return (
<p>
......
......@@ -10,7 +10,6 @@ import {
waitFor,
openRedbox,
getRedboxDescriptionWarning,
toggleCollapseComponentStack,
getRedboxErrorLink,
} from './next-test-utils'
import webdriver, { WebdriverOptions } from './next-webdriver'
......@@ -151,12 +150,9 @@ export async function createSandbox(
/**
* @returns `null` if there are no frames
*/
async getRedboxComponentStack() {
getRedboxComponentStack() {
return getRedboxComponentStack(browser)
},
async toggleCollapseComponentStack() {
return toggleCollapseComponentStack(browser)
},
async getVersionCheckerText() {
return getVersionCheckerText(browser)
},
......
......@@ -1308,8 +1308,7 @@ export function getSnapshotTestDescribe(variant: TestVariants) {
export async function getRedboxComponentStack(
browser: BrowserInterface
): Promise<string | null> {
// TODO: the type for elementsByCss is incorrect
const componentStackFrameElements: any = await browser.elementsByCss(
const componentStackFrameElements = await browser.elementsByCss(
'[data-nextjs-container-errors-pseudo-html] code'
)
if (componentStackFrameElements.length === 0) {
......@@ -1323,14 +1322,6 @@ export async function getRedboxComponentStack(
return componentStackFrameTexts.join('\n').trim()
}
export async function toggleCollapseComponentStack(
browser: BrowserInterface
): Promise<void> {
await browser
.elementByCss('[data-nextjs-container-errors-pseudo-html-collapse]')
.click()
}
export async function hasRedboxCallStack(browser: BrowserInterface) {
await ensureNoSuspendedComponentsInRedBox(browser)
return browser.eval(() => {
......
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