Unverified Commit 3204d86c authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

Unify hydration error tree details (#99008)

## Summary

Unifies hydration error details in the development overlay:

- renders invalid HTML as a compact `Rendered tree` and mismatches as a
compact `client/server diff`
- keeps the nearest relevant user component and affected rows visible by
default, with a disclosure control to expand the complete React-rendered
tree
- keeps neutral markers for invalid HTML and the `+ Client` / `- Server`
legend only for actual mismatches
- uses the same frame, spacing, typography, and overflow behavior for
both variants

## Visual changes

### Invalid HTML

| Before | After |
| --- | --- |
| ![Invalid HTML shown with ambiguous diff
styling](https://github.com/user-attachments/assets/3ab72f7a-beac-4081-a91b-c0ebfa37027e)
| ![Invalid HTML shown as a compact, expandable rendered
tree](https://github.com/user-attachments/assets/1fcaa5ad-bdb6-4082-ba00-71bab8ab4466)
|

### Client/server mismatch

| Before | After |
| --- | --- |
| ![Client/server mismatch with an oversized collapsed
tree](https://github.com/user-attachments/assets/176b77a2-bad6-41d2-9f16-96d125f31048)
| ![Client/server mismatch shown as a compact, expandable diff with a
client and server
legend](https://github.com/user-attachments/assets/8d163768-4899-47bb-8155-67934a1c3e98)
|

## Verification

- App Router hydration acceptance tests with Turbopack and webpack
- Pages Router hydration acceptance tests with Turbopack and webpack
- focused hydration error count tests with and without Cache Components
- Next.js type checking, ESLint, and Prettier
- manual verification of invalid HTML and client/server mismatch
overlays

<!-- NEXT_JS_LLM -->
parent 9b96a51b
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { CollapseIcon } from '../../icons/collapse-icon' import { CollapseIcon } from '../../icons/collapse-icon'
// Keep the nearest relevant user component, the affected rows, and a closing
// delimiter. Unrelated ancestors and internal framework frames are omitted.
function getRenderedTreeExcerpt(lines: string[], signs: Set<string>) {
const isRelevantLine = (line: string) =>
!line.includes('<Next.js Internal Component>')
const isHighlightedLine = (line: string) =>
signs.has(line[0]) && isRelevantLine(line)
const contextLineLimit = signs.has('+') ? 3 : 1
const contextLines: string[] = []
const excerpt: string[] = []
let foundHighlightedLine = false
let lastHighlightedLine = -1
for (let index = 0; index < lines.length; index++) {
const line = lines[index]
if (isHighlightedLine(line)) {
if (!foundHighlightedLine) {
for (const contextLine of contextLines) {
excerpt.push(contextLine)
}
foundHighlightedLine = true
}
excerpt.push(line)
lastHighlightedLine = index
continue
}
if (foundHighlightedLine) {
continue
}
const trimmedLine = line.trim()
if (trimmedLine !== '' && trimmedLine !== '...' && isRelevantLine(line)) {
if (/^\s*<[A-Z]/.test(line)) {
contextLines.length = 0
}
contextLines.push(line)
if (contextLines.length > contextLineLimit) {
contextLines.shift()
}
}
}
if (!foundHighlightedLine) {
return lines
}
const possibleClosingLine = lines[lastHighlightedLine + 1]
if (/^\s*\/?>(?:\s*)$/.test(possibleClosingLine ?? '')) {
excerpt.push(possibleClosingLine)
}
let minimumIndent = Infinity
for (const line of excerpt) {
const content = signs.has(line[0]) ? line.slice(1) : line
const indent = content.length - content.trimStart().length
if (indent < minimumIndent) {
minimumIndent = indent
}
}
return excerpt.map((line) => {
if (signs.has(line[0])) {
return `${line[0]}${line.slice(1 + minimumIndent)}`
}
return line.slice(minimumIndent)
})
}
function renderDiffLines(lines: string[]) {
return lines.map((line, index) => {
const isDiffLine = line[0] === '+' || line[0] === '-'
const isHighlightedLine = line[0] === '>'
const hasSign = isDiffLine || isHighlightedLine
const sign = hasSign ? line[0] : ''
const signIndex = hasSign ? line.indexOf(sign) : -1
const [prefix, suffix] = hasSign
? [line.slice(0, signIndex), line.slice(signIndex + 1)]
: [line, '']
if (isDiffLine) {
return (
<span
key={'comp-diff' + index}
data-nextjs-container-errors-pseudo-html-line
data-nextjs-container-errors-pseudo-html--diff={
sign === '+' ? 'add' : 'remove'
}
>
<span>
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
</span>
)
}
return (
<span
data-nextjs-container-errors-pseudo-html-line
key={'comp-diff' + index}
{...(isHighlightedLine
? {
'data-nextjs-container-errors-pseudo-html--diff': 'error',
}
: undefined)}
>
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>{sign}</span>
{suffix}
{'\n'}
</span>
)
})
}
/** /**
* *
* Format component stack into pseudo HTML * Format component stack into pseudo HTML
...@@ -53,91 +179,62 @@ export function PseudoHtmlDiff({ ...@@ -53,91 +179,62 @@ export function PseudoHtmlDiff({
}: { }: {
reactOutputComponentDiff: string reactOutputComponentDiff: string
}) { }) {
const [isDiffCollapsed, toggleCollapseHtml] = useState(true) const [isExpanded, setIsExpanded] = useState(false)
const { hasClientServerDiff, excerptComponents, fullComponents } =
const htmlComponents = useMemo(() => { useMemo(() => {
const componentStacks: React.ReactNode[] = [] const reactComponentDiffLines = reactOutputComponentDiff.split('\n')
const reactComponentDiffLines = reactOutputComponentDiff.split('\n') let containsClientServerDiff = false
reactComponentDiffLines.forEach((line, index) => { for (const line of reactComponentDiffLines) {
const isDiffLine = line[0] === '+' || line[0] === '-' if (line[0] === '+' || line[0] === '-') {
const isHighlightedLine = line[0] === '>' containsClientServerDiff = true
const hasSign = isDiffLine || isHighlightedLine break
const sign = hasSign ? line[0] : '' }
const signIndex = hasSign ? line.indexOf(sign) : -1 }
const [prefix, suffix] = hasSign const displayedLines = getRenderedTreeExcerpt(
? [line.slice(0, signIndex), line.slice(signIndex + 1)] reactComponentDiffLines,
: [line, ''] new Set(containsClientServerDiff ? ['+', '-'] : ['>'])
)
if (isDiffLine) {
componentStacks.push( return {
<span hasClientServerDiff: containsClientServerDiff,
key={'comp-diff' + index} excerptComponents: renderDiffLines(displayedLines),
data-nextjs-container-errors-pseudo-html-line fullComponents: renderDiffLines(reactComponentDiffLines),
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--diff': 'error',
}
: undefined)}
>
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
)
} }
}) }, [reactOutputComponentDiff])
return componentStacks
}, [reactOutputComponentDiff]) const title = hasClientServerDiff ? 'client/server diff' : 'Rendered tree'
return ( return (
<div <div
data-nextjs-container-errors-pseudo-html data-nextjs-container-errors-pseudo-html
data-nextjs-container-errors-pseudo-html-collapse={isDiffCollapsed} data-nextjs-hydration-diff-type={
hasClientServerDiff ? 'client-server' : 'invalid-html'
}
> >
<div data-nextjs-hydration-diff-header> <div data-nextjs-hydration-diff-header>
<button <button
aria-expanded={!isDiffCollapsed} type="button"
aria-label="complete Component Stack" aria-expanded={isExpanded}
aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${title}`}
data-nextjs-container-errors-pseudo-html-collapse-button data-nextjs-container-errors-pseudo-html-collapse-button
onClick={() => toggleCollapseHtml(!isDiffCollapsed)} onClick={() => setIsExpanded((expanded) => !expanded)}
> >
<CollapseIcon collapsed={isDiffCollapsed} /> <CollapseIcon collapsed={!isExpanded} />
<span data-nextjs-hydration-diff-title>{title}</span>
</button> </button>
<div data-nextjs-hydration-diff-badge> {hasClientServerDiff && (
<span data-nextjs-hydration-diff-badge-item="client"> <div data-nextjs-hydration-diff-badge>
<span>+</span> Client <span data-nextjs-hydration-diff-badge-item="client">
</span> <span>+</span> Client
<span data-nextjs-hydration-diff-badge-item="server"> </span>
<span>-</span> Server <span data-nextjs-hydration-diff-badge-item="server">
</span> <span>-</span> Server
</div> </span>
</div>
)}
</div> </div>
<pre className="nextjs__container_errors__component-stack"> <pre className="nextjs__container_errors__component-stack">
<code>{htmlComponents}</code> <code>{isExpanded ? fullComponents : excerptComponents}</code>
</pre> </pre>
</div> </div>
) )
......
...@@ -29,3 +29,10 @@ export const ReactUnifiedMismatch: Story = { ...@@ -29,3 +29,10 @@ export const ReactUnifiedMismatch: Story = {
'<Page>\n <Layout>\n <div>asd\n- <p>Server content</p>\n+ <p>Client content</p>', '<Page>\n <Layout>\n <div>asd\n- <p>Server content</p>\n+ <p>Client content</p>',
}, },
} }
export const InvalidHtmlNesting: Story = {
args: {
reactOutputComponentDiff:
'...\n <ClientPageRoot Component={function Page} serverProvidedParams={{...}}>\n <Page params={Promise} searchParams={Promise}>\n> <p>\n> <p>\n ...',
},
}
...@@ -10,7 +10,7 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -10,7 +10,7 @@ export const PSEUDO_HTML_DIFF_STYLES = `
font-family: var(--font-stack-monospace); font-family: var(--font-stack-monospace);
font-size: var(--size-12); font-size: var(--size-12);
line-height: 1.33em; /* 16px in 12px font size */ line-height: 1.33em; /* 16px in 12px font size */
border-radius: var(--rounded-md-2); border-radius: var(--rounded-xl);
} }
[data-nextjs-container-errors-pseudo-html-line] { [data-nextjs-container-errors-pseudo-html-line] {
display: inline-block; display: inline-block;
...@@ -19,17 +19,10 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -19,17 +19,10 @@ export const PSEUDO_HTML_DIFF_STYLES = `
line-height: calc(5 / 3); line-height: calc(5 / 3);
} }
[data-nextjs-container-errors-pseudo-html--diff='error'] { [data-nextjs-container-errors-pseudo-html--diff='error'] {
background: var(--color-amber-100); background: var(--color-red-200);
box-shadow: 2px 0 0 0 var(--color-amber-900) inset; box-shadow: 2px 0 0 0 var(--color-red-900) inset;
font-weight: bold; font-weight: bold;
} }
[data-nextjs-container-errors-pseudo-html-collapse-button] {
all: unset;
margin-left: 12px;
&:focus {
outline: none;
}
}
[data-nextjs-container-errors-pseudo-html--diff='add'] { [data-nextjs-container-errors-pseudo-html--diff='add'] {
background: var(--color-green-300); background: var(--color-green-300);
} }
...@@ -52,7 +45,7 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -52,7 +45,7 @@ export const PSEUDO_HTML_DIFF_STYLES = `
} }
[data-nextjs-container-errors-pseudo-html--diff='error'] [data-nextjs-container-errors-pseudo-html--diff='error']
[data-nextjs-container-errors-pseudo-html-line-sign] { [data-nextjs-container-errors-pseudo-html-line-sign] {
color: var(--color-amber-900); color: var(--color-red-900);
} }
${/* hide but text are still accessible in DOM */ ''} ${/* hide but text are still accessible in DOM */ ''}
[data-nextjs-container-errors-pseudo-html--hint] { [data-nextjs-container-errors-pseudo-html--hint] {
...@@ -66,13 +59,6 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -66,13 +59,6 @@ export const PSEUDO_HTML_DIFF_STYLES = `
.nextjs__container_errors__component-stack { .nextjs__container_errors__component-stack {
margin: 0; margin: 0;
} }
[data-nextjs-container-errors-pseudo-html-collapse='true']
.nextjs__container_errors__component-stack
code {
max-height: 120px;
mask-image: linear-gradient(to bottom,rgba(0,0,0,0) 0%,black 10%);
padding-bottom: 40px;
}
.nextjs__container_errors__component-stack code { .nextjs__container_errors__component-stack code {
display: block; display: block;
width: 100%; width: 100%;
...@@ -80,6 +66,51 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -80,6 +66,51 @@ export const PSEUDO_HTML_DIFF_STYLES = `
scroll-snap-type: y mandatory; scroll-snap-type: y mandatory;
overflow-y: hidden; overflow-y: hidden;
} }
[data-nextjs-hydration-diff-type] {
color: var(--color-gray-1000);
font-size: var(--size-13);
overflow: hidden;
padding: 0;
}
[data-nextjs-hydration-diff-type]
[data-nextjs-container-errors-pseudo-html-line] {
box-sizing: border-box;
font-weight: normal;
line-height: var(--size-20);
}
[data-nextjs-hydration-diff-type='invalid-html']
[data-nextjs-container-errors-pseudo-html-line-sign] {
color: var(--color-gray-alpha-1000);
}
[data-nextjs-hydration-diff-type]
.nextjs__container_errors__component-stack,
[data-nextjs-hydration-diff-type]
.nextjs__container_errors__component-stack code {
overflow-x: hidden;
overflow-wrap: anywhere;
}
[data-nextjs-hydration-diff-type]
.nextjs__container_errors__component-stack {
background: var(--color-background-100);
padding: 8px 0 10px;
}
[data-nextjs-hydration-diff-title] {
color: var(--color-gray-900);
font-family: var(--font-stack-sans);
font-size: var(--size-12);
}
[data-nextjs-container-errors-pseudo-html-collapse-button] {
all: unset;
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
border-radius: var(--rounded-md);
}
[data-nextjs-container-errors-pseudo-html-collapse-button]:focus-visible {
outline: 2px solid var(--color-blue-600);
outline-offset: 2px;
}
[data-nextjs-container-errors-pseudo-html--diff] { [data-nextjs-container-errors-pseudo-html--diff] {
scroll-snap-align: center; scroll-snap-align: center;
} }
...@@ -93,7 +124,9 @@ export const PSEUDO_HTML_DIFF_STYLES = ` ...@@ -93,7 +124,9 @@ export const PSEUDO_HTML_DIFF_STYLES = `
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 0 12px 0 0; border-bottom: 1px solid var(--color-gray-200);
min-height: 36px;
padding: 0 12px;
} }
[data-nextjs-hydration-diff-badge] { [data-nextjs-hydration-diff-badge] {
display: flex; display: flex;
......
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