Skip to content

Commit

Permalink
fix(hydration): fix mismatch of leading newline in <textarea> and <pre>
Browse files Browse the repository at this point in the history
close #11873
close #11874
  • Loading branch information
yyx990803 committed Sep 13, 2024
1 parent 3c4bf76 commit a5f3c2e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
15 changes: 15 additions & 0 deletions packages/runtime-core/__tests__/hydration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1908,6 +1908,21 @@ describe('SSR hydration', () => {
expect(`Hydration attribute mismatch`).toHaveBeenWarned()
})

// #11873
test('<textarea> with newlines at the beginning', async () => {
const render = () => h('textarea', null, '\nhello')
const html = await renderToString(createSSRApp({ render }))
mountWithHydration(html, render)
expect(`Hydration text content mismatch`).not.toHaveBeenWarned()
})

test('<pre> with newlines at the beginning', async () => {
const render = () => h('pre', null, '\n')
const html = await renderToString(createSSRApp({ render }))
mountWithHydration(html, render)
expect(`Hydration text content mismatch`).not.toHaveBeenWarned()
})

test('boolean attr handling', () => {
mountWithHydration(`<input />`, () => h('input', { readonly: false }))
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
Expand Down
14 changes: 12 additions & 2 deletions packages/runtime-core/src/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,17 @@ export function createHydrationFunctions(
remove(cur)
}
} else if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
if (el.textContent !== vnode.children) {
// #11873 the HTML parser will "eat" the first newline when parsing
// <pre> and <textarea>, so if the client value starts with a newline,
// we need to remove it before comparing
let clientText = vnode.children as string
if (
clientText[0] === '\n' &&
(el.tagName === 'PRE' || el.tagName === 'TEXTAREA')
) {
clientText = clientText.slice(1)
}
if (el.textContent !== clientText) {
if (!isMismatchAllowed(el, MismatchTypes.TEXT)) {
;(__DEV__ || __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__) &&
warn(
Expand Down Expand Up @@ -753,7 +763,7 @@ export function createHydrationFunctions(
const isTemplateNode = (node: Node): node is HTMLTemplateElement => {
return (
node.nodeType === DOMNodeTypes.ELEMENT &&
(node as Element).tagName.toLowerCase() === 'template'
(node as Element).tagName === 'TEMPLATE'
)
}

Expand Down

0 comments on commit a5f3c2e

Please sign in to comment.