Backtestsvuerun-20261005-124535#14403
Preserve input values entered during hydration
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches use the same core approach. During hydration, `created` runs on an element that already has a parent, so each patch compares the element's live state with its markup-derived default, keeps the user's value, and writes it back to the model in `mounted`. They differ mainly in coverage. **Patch A** - It only handles elements whose `type` is exactly 'text' or 'textarea'. - Every other `v-model` text-like input still gets reset during hydration: email, password, search, tel, url and number. - Checkboxes, radios and selects also still get reset. - These are exactly the form fields a user fills in on a slow page, so A only fixes part of the reported problem. - Its CR/LF normalization is careful, but it is guarding a narrow case. - It ignores the implicit `type="number"` cast that the existing `created` hook applies (`castToNumber`). - It adds one test, for a plain text input only. **Patch B** - It detects user modification for every `v-model` target: all input types, textarea, checkbox, radio, select and select multiple. - It handles browser value sanitization (range clamping, number parsing) by comparing against a fresh element with the same attributes. This avoids false positives on untouched fields. - It works out the default select index the same way the browser does, including disabled options and optgroups. - It handles the tricky case of several checkboxes sharing one array or Set model during hydration. It accumulates the pending assignments, because the binding value is stale until the next re-render. - It applies the same cast for implicit `type=number` as the existing `created` hook. - It refactors the existing change handlers into shared helpers (`assignCheckboxValue`, `assignSelectValue`) without changing their behavior. - Its tests cover every element kind, the `.trim`/`.number` modifiers and a dynamic `type`. They also include a negative test showing untouched fields (including range and select defaults) still follow the model. - Every one of these tests would fail before the change. **Trade-off** B is more complex: a module-level `WeakMap` and per-element pristine-clone creation, though the clone is only created when the value differs. That complexity is justified by the issue's general 'inputs/forms' scope and does not obscure the fix. B resolves the issue much more completely and has much stronger tests, so B is the better patch.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
17m 24s
Wall-clock time in the container
Full test suite
No new failures
3,659 passed · 6 skipped · 3,665 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
411vs 50 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.27
Link to minimal reproduction
https://github.com/nuxt/nuxt/issues/29206
Steps to reproduce
user loads a page with a slow internet connection
starts entering some values into the input with v-model
after all browser resources loaded - input v-model reset to default value
What is expected?
entered input value is preserved once hydration completes
What is actually happening?
input value is reset to its default value
System Info
Any additional comments?
This is affecting UX when interacting with inputs/forms in slowly loading apps, where values entered during hydration phase are erased and the progress is lost. I have been blocking all forms myself until mounted hook fires to workaround this issue - it would be great to not have to!
The two patches
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..f7bf3cb39 100644@@ -2179,6 +2179,180 @@ describe('SSR hydration', () => { expect(root.innerHTML).toBe('<div>bar</div>') }) + // #14402 preserve values entered by the user before hydration completes+ describe('form state modified before hydration', () => {+ async function hydrateAfterUserInput(+ App: any,+ interact: (container: Element) => void,+ ) {+ const container = document.createElement('div')+ container.innerHTML = await renderToString(h(App))+ document.body.appendChild(container)+ // simulate the user interacting with the server-rendered markup+ // while the client bundle is still loading+ interact(container)+ createSSRApp(App).mount(container)+ await nextTick()+ return container+ }++ test('text input', async () => {+ const App = {+ data: () => ({ text: 'default' }),+ template: `<div><input v-model="text"><span>{{ text }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector('input')!.value = 'typed'+ })+ expect(container.querySelector('input')!.value).toBe('typed')+ expect(container.querySelector('span')!.textContent).toBe('typed')+ })++ test('text input with .trim / .number modifiers', async () => {+ const App = {+ data: () => ({ text: 'default', num: 1 }),+ template:+ `<div><input class="t" v-model.trim="text">` ++ `<input class="n" v-model.number="num">` ++ `<span>{{ typeof num }}:{{ num }}:{{ text }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector<HTMLInputElement>('.t')!.value = ' typed '+ c.querySelector<HTMLInputElement>('.n')!.value = '42'+ })+ expect(container.querySelector<HTMLInputElement>('.n')!.value).toBe('42')+ expect(container.querySelector('span')!.textContent).toBe(+ 'number:42:typed',+ )+ })++ test('textarea', async () => {+ const App = {+ data: () => ({ text: 'default' }),+ template: `<div><textarea v-model="text"></textarea><span>{{ text }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector('textarea')!.value = 'typed'+ })+ expect(container.querySelector('textarea')!.value).toBe('typed')+ expect(container.querySelector('span')!.textContent).toBe('typed')+ })++ test('input with dynamic type', async () => {+ const App = {+ data: () => ({ text: 'default', type: 'text' }),+ template: `<div><input :type="type" v-model="text"><span>{{ text }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector('input')!.value = 'typed'+ })+ expect(container.querySelector('input')!.value).toBe('typed')+ expect(container.querySelector('span')!.textContent).toBe('typed')+ })++ test('checkbox', async () => {+ const App = {+ data: () => ({ checked: false }),+ template: `<div><input type="checkbox" v-model="checked"><span>{{ checked }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector('input')!.checked = true+ })+ expect(container.querySelector('input')!.checked).toBe(true)+ expect(container.querySelector('span')!.textContent).toBe('true')+ })++ test('checkbox group with array model', async () => {+ const App = {+ data: () => ({ list: ['a'] }),+ template:+ `<div><input type="checkbox" value="a" v-model="list">` ++ `<input type="checkbox" value="b" v-model="list">` ++ `<input type="checkbox" value="c" v-model="list">` ++ `<span>{{ list.join() }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ const inputs = c.querySelectorAll('input')+ inputs[0].checked = false+ inputs[1].checked = true+ inputs[2].checked = true+ })+ const inputs = container.querySelectorAll('input')+ expect([...inputs].map(i => i.checked)).toEqual([false, true, true])+ expect(container.querySelector('span')!.textContent).toBe('b,c')+ })++ test('radio', async () => {+ const App = {+ data: () => ({ picked: 'a' }),+ template:+ `<div><input type="radio" name="p" value="a" v-model="picked">` ++ `<input type="radio" name="p" value="b" v-model="picked">` ++ `<span>{{ picked }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelectorAll('input')[1].checked = true+ })+ const inputs = container.querySelectorAll('input')+ expect(inputs[0].checked).toBe(false)+ expect(inputs[1].checked).toBe(true)+ expect(container.querySelector('span')!.textContent).toBe('b')+ })++ test('select', async () => {+ const App = {+ data: () => ({ selected: 'a' }),+ template:+ `<div><select v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `</select><span>{{ selected }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ c.querySelector('select')!.value = 'b'+ })+ expect(container.querySelector('select')!.value).toBe('b')+ expect(container.querySelector('span')!.textContent).toBe('b')+ })++ test('select multiple', async () => {+ const App = {+ data: () => ({ selected: ['a'] }),+ template:+ `<div><select multiple v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `<option value="c">c</option>` ++ `</select><span>{{ selected.join() }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, c => {+ const options = c.querySelector('select')!.options+ options[0].selected = false+ options[2].selected = true+ })+ const options = container.querySelector('select')!.options+ expect([...options].map(o => o.selected)).toEqual([false, false, true])+ expect(container.querySelector('span')!.textContent).toBe('c')+ })++ test('unmodified fields keep using the model value', async () => {+ const App = {+ data: () => ({ text: 'default', range: null, selected: '' }),+ template:+ `<div><input class="t" v-model="text">` ++ `<input class="r" type="range" v-model="range">` ++ `<select v-model="selected"><option value="a">a</option></select>` ++ `<span>{{ text }}:{{ range }}:{{ selected }}</span></div>`,+ }+ const container = await hydrateAfterUserInput(App, () => {})+ expect(container.querySelector<HTMLInputElement>('.t')!.value).toBe(+ 'default',+ )+ // value differs from the (absent) value attribute only because of+ // range sanitization, and the first option is only selected by default+ expect(container.querySelector('span')!.textContent).toBe('default::')+ expect(container.querySelector('select')!.selectedIndex).toBe(-1)+ })+ })+ describe('mismatch handling', () => { test('text node', () => { const { container } = mountWithHydration(`foo`, () => 'bar')packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..f287ae1ee 100644@@ -38,13 +38,90 @@ function onCompositionEnd(e: Event) { } const assignKey: unique symbol = Symbol('_assign')+const userModifiedKey: unique symbol = Symbol('_userModified') type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<- T & { [assignKey]: AssignerFn; _assigning?: boolean },+ T & {+ [assignKey]: AssignerFn+ [userModifiedKey]?: boolean+ _assigning?: boolean+ }, any, Modifiers > +/**+ * Elements created by the client renderer are not inserted into the DOM+ * until after their `created` hooks run, so an element that already has a+ * parent at that point is a server-rendered element being hydrated.+ * The user may have interacted with it before hydration (e.g. on a slow+ * connection), in which case its live state no longer matches the state+ * described by its HTML attributes and must be preserved.+ */+function isUserModifiedBeforeHydration(+ el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,+): boolean {+ if (!el.parentNode) return false+ switch (el.tagName) {+ case 'TEXTAREA':+ return (+ (el as HTMLTextAreaElement).value !==+ (el as HTMLTextAreaElement).defaultValue+ )+ case 'SELECT':+ return isSelectModified(el as HTMLSelectElement)+ case 'INPUT':+ return isInputModified(el as HTMLInputElement)+ default:+ return false+ }+}++function isInputModified(el: HTMLInputElement): boolean {+ if (el.type === 'checkbox' || el.type === 'radio') {+ return el.checked !== el.defaultChecked+ }+ if (el.value === el.defaultValue) return false+ // the value may differ from the `value` attribute only because of value+ // sanitization (e.g. range clamping / defaulting, number parsing), so+ // compare against a pristine element carrying the same attributes.+ const pristine = el.ownerDocument.createElement('input')+ for (let i = 0; i < el.attributes.length; i++) {+ const { name, value } = el.attributes[i]+ pristine.setAttribute(name, value)+ }+ return el.value !== pristine.value+}++function isSelectModified(el: HTMLSelectElement): boolean {+ const options = el.options+ if (el.multiple) {+ for (let i = 0; i < options.length; i++) {+ if (options[i].selected !== options[i].defaultSelected) return true+ }+ return false+ }+ // compute the selection the browser derives from the markup alone+ let expected = -1+ for (let i = 0; i < options.length; i++) {+ if (options[i].defaultSelected) expected = i+ }+ if (expected === -1 && el.size <= 1) {+ for (let i = 0; i < options.length; i++) {+ const option = options[i]+ const parent = option.parentNode as HTMLOptGroupElement | null+ if (+ !option.disabled &&+ !(parent && parent.tagName === 'OPTGROUP' && parent.disabled)+ ) {+ expected = i+ break+ }+ }+ }+ return el.selectedIndex !== expected+}+ function castValue(value: string, trim?: boolean, number?: boolean | null) { if (trim) value = value.trim() if (number) value = looseToNumber(value)@@ -58,6 +135,7 @@ export const vModelText: ModelDirective< 'trim' | 'number' | 'lazy' > = { created(el, { modifiers: { lazy, trim, number } }, vnode) {+ el[userModifiedKey] = isUserModifiedBeforeHydration(el) el[assignKey] = getModelAssigner(vnode) const castToNumber = number || (vnode.props && vnode.props.type === 'number')@@ -81,7 +159,15 @@ export const vModelText: ModelDirective< } }, // set value on mounted so it's after min/max for type="range"- mounted(el, { value }) {+ mounted(el, { value, modifiers: { trim, number } }, vnode) {+ if (el[userModifiedKey]) {+ // preserve the value entered before hydration and sync it to the model+ el[userModifiedKey] = false+ const castToNumber =+ number || (vnode.props && vnode.props.type === 'number')+ el[assignKey](castValue(el.value, trim, castToNumber))+ return+ } el.value = value == null ? '' : value }, beforeUpdate(@@ -125,43 +211,74 @@ export const vModelCheckbox: ModelDirective<HTMLInputElement> = { // #4096 array checkboxes need to be deep traversed deep: true, created(el, _, vnode) {+ el[userModifiedKey] = isUserModifiedBeforeHydration(el) el[assignKey] = getModelAssigner(vnode) addEventListener(el, 'change', () => {- const modelValue = (el as any)._modelValue- const elementValue = getValue(el)- const checked = el.checked- const assign = el[assignKey]- if (isArray(modelValue)) {- const index = looseIndexOf(modelValue, elementValue)- const found = index !== -1- if (checked && !found) {- assign(modelValue.concat(elementValue))- } else if (!checked && found) {- const filtered = [...modelValue]- filtered.splice(index, 1)- assign(filtered)- }- } else if (isSet(modelValue)) {- const cloned = new Set(modelValue)- if (checked) {- cloned.add(elementValue)- } else {- cloned.delete(elementValue)- }- assign(cloned)- } else {- assign(getCheckboxValue(el, checked))- }+ assignCheckboxValue(el, (el as any)._modelValue) }) }, // set initial checked on mount to wait for true-value/false-value- mounted: setChecked,+ mounted(el, binding, vnode) {+ if (el[userModifiedKey]) {+ // preserve the checked state set before hydration and sync it to the+ // model. Multiple checkboxes may share the same array / Set model, so+ // build on the value assigned by previously hydrated siblings, since+ // the binding value is not updated until the next render.+ el[userModifiedKey] = false+ const { value } = binding+ const isCollection = isArray(value) || isSet(value)+ const modelValue =+ (isCollection && pendingCollectionModels.get(value)) || value+ ;(el as any)._modelValue = modelValue+ const assigned = assignCheckboxValue(el, modelValue)+ if (isCollection && assigned !== undefined) {+ pendingCollectionModels.set(value, assigned)+ nextTick(() => pendingCollectionModels.delete(value))+ }+ return+ }+ setChecked(el, binding, vnode)+ }, beforeUpdate(el, binding, vnode) { el[assignKey] = getModelAssigner(vnode) setChecked(el, binding, vnode) }, } +// array / Set checkbox models assigned during hydration but not yet+// re-rendered, keyed by the model value the checkboxes were rendered with+const pendingCollectionModels = new WeakMap<object, any>()++function assignCheckboxValue(el: HTMLInputElement, modelValue: any): any {+ const elementValue = getValue(el)+ const checked = el.checked+ const assign = (el as any)[assignKey] as AssignerFn+ let newValue: any+ if (isArray(modelValue)) {+ const index = looseIndexOf(modelValue, elementValue)+ const found = index !== -1+ if (checked && !found) {+ newValue = modelValue.concat(elementValue)+ } else if (!checked && found) {+ newValue = [...modelValue]+ newValue.splice(index, 1)+ } else {+ return+ }+ } else if (isSet(modelValue)) {+ newValue = new Set(modelValue)+ if (checked) {+ newValue.add(elementValue)+ } else {+ newValue.delete(elementValue)+ }+ } else {+ newValue = getCheckboxValue(el, checked)+ }+ assign(newValue)+ return newValue+}+ function setChecked( el: HTMLInputElement, { value, oldValue }: DirectiveBinding,@@ -189,12 +306,25 @@ function setChecked( export const vModelRadio: ModelDirective<HTMLInputElement> = { created(el, { value }, vnode) {- el.checked = looseEqual(value, vnode.props!.value)+ el[userModifiedKey] = isUserModifiedBeforeHydration(el)+ if (!el[userModifiedKey]) {+ el.checked = looseEqual(value, vnode.props!.value)+ } el[assignKey] = getModelAssigner(vnode) addEventListener(el, 'change', () => { el[assignKey](getValue(el)) }) },+ mounted(el) {+ if (el[userModifiedKey]) {+ // preserve the radio selected before hydration and sync it to the model.+ // assigned in mounted so that `:value` bindings have been patched.+ el[userModifiedKey] = false+ if (el.checked) {+ el[assignKey](getValue(el))+ }+ }+ }, beforeUpdate(el, { value, oldValue }, vnode) { el[assignKey] = getModelAssigner(vnode) if (value !== oldValue) {@@ -207,30 +337,23 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { // <select multiple> value need to be deep traversed deep: true, created(el, { value, modifiers: { number } }, vnode) {+ el[userModifiedKey] = isUserModifiedBeforeHydration(el) ;(el as any)._modelValue = value addEventListener(el, 'change', () => {- const selectedVal = Array.prototype.filter- .call(el.options, (o: HTMLOptionElement) => o.selected)- .map((o: HTMLOptionElement) =>- number ? looseToNumber(getValue(o)) : getValue(o),- )- el[assignKey](- el.multiple- ? isSet((el as any)._modelValue)- ? new Set(selectedVal)- : selectedVal- : selectedVal[0],- )- el._assigning = true- nextTick(() => {- el._assigning = false- })+ assignSelectValue(el, number) }) el[assignKey] = getModelAssigner(vnode) }, // set value in mounted & updated because <select> relies on its children // <option>s.- mounted(el, { value }) {+ mounted(el, { value, modifiers: { number } }) {+ if (el[userModifiedKey]) {+ // preserve the selection made before hydration and sync it to the model.+ // assigned in mounted so that `<option :value>` bindings are patched.+ el[userModifiedKey] = false+ assignSelectValue(el, number)+ return+ } setSelected(el, value) }, beforeUpdate(el, { value }, vnode) {@@ -244,6 +367,28 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { }, } +function assignSelectValue(+ el: HTMLSelectElement & { [assignKey]: AssignerFn; _assigning?: boolean },+ number: boolean | undefined,+) {+ const selectedVal = Array.prototype.filter+ .call(el.options, (o: HTMLOptionElement) => o.selected)+ .map((o: HTMLOptionElement) =>+ number ? looseToNumber(getValue(o)) : getValue(o),+ )+ el[assignKey](+ el.multiple+ ? isSet((el as any)._modelValue)+ ? new Set(selectedVal)+ : selectedVal+ : selectedVal[0],+ )+ el._assigning = true+ nextTick(() => {+ el._assigning = false+ })+}+ function setSelected(el: HTMLSelectElement, value: any) { const isMultiple = el.multiple const isArrayValue = isArray(value)
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..49c39bdd6 100644@@ -1692,6 +1692,24 @@ describe('SSR hydration', () => { expect((container.firstChild as any)._trueValue).toBe(true) }) + test('preserves text entered before v-model hydration', async () => {+ const state = reactive({ text: 'server value' })+ const App = {+ setup: () => state,+ template: `<input v-model="text">`,+ }+ const container = document.createElement('div')+ container.innerHTML = await renderToString(h(App))+ const input = container.firstChild as HTMLInputElement+ input.value = 'user value'++ createSSRApp(App).mount(container)+ await nextTick()++ expect(input.value).toBe('user value')+ expect(state.text).toBe('user value')+ })+ test('force hydrate checkbox with indeterminate', () => { const { container } = mountWithHydration( '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..eeb248f28 100644@@ -38,9 +38,14 @@ function onCompositionEnd(e: Event) { } const assignKey: unique symbol = Symbol('_assign')+const initialValueKey: unique symbol = Symbol('_initialValue') type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<- T & { [assignKey]: AssignerFn; _assigning?: boolean },+ T & {+ [assignKey]: AssignerFn+ [initialValueKey]?: string+ _assigning?: boolean+ }, any, Modifiers >@@ -58,6 +63,16 @@ export const vModelText: ModelDirective< 'trim' | 'number' | 'lazy' > = { created(el, { modifiers: { lazy, trim, number } }, vnode) {+ // During hydration, created runs on an element already in the DOM.+ if (el.parentNode) {+ if (el.type === 'text') {+ // Text inputs strip CR/LF from value, while defaultValue retains them.+ el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, '')+ } else if (el.type === 'textarea') {+ // Textareas normalize CRLF/CR to LF in value.+ el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, '\n')+ }+ } el[assignKey] = getModelAssigner(vnode) const castToNumber = number || (vnode.props && vnode.props.type === 'number')@@ -81,8 +96,19 @@ export const vModelText: ModelDirective< } }, // set value on mounted so it's after min/max for type="range"- mounted(el, { value }) {- el.value = value == null ? '' : value+ mounted(el, { value, modifiers: { trim, number } }) {+ const newValue = value == null ? '' : value+ const initialValue = el[initialValueKey]+ delete el[initialValueKey]+ if (+ initialValue !== undefined &&+ (el.type === 'text' || el.type === 'textarea') &&+ el.value !== initialValue+ ) {+ el[assignKey](castValue(el.value, trim, number))+ } else {+ el.value = newValue+ } }, beforeUpdate( el,