Backtestsvuerun-20261005-155915#14403
Preserve input values entered during hydration
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches use the same detection idea: in `created`, an element that already has a parent is being hydrated. In `mounted`, if the DOM value differs from the server-rendered default, the patch syncs the DOM value back to the model instead of overwriting it. Patch B only applies this when `el.type` is 'text' or 'textarea'. It does not cover: - other text-like input types handled by vModelText (email, password, search, number, tel, url); - checkboxes, radios and selects, which are common in the forms the issue describes. B also approximates the browser's value sanitization by hand with CR/LF regexes. Its only test is a single plain text-input case. Patch A covers every v-model variant: - **Text inputs:** handles all input types. It detects sanitization robustly by cloning the element and assigning `defaultValue`, so the browser's own sanitization is the reference (e.g. color lowercasing, range defaults). It respects the `.trim`, `.number` and `type=number` casts. - **Checkboxes:** handles both boolean and array/Set models. It tracks sibling checkboxes that share one model during the same flush, so they do not overwrite each other's assignments. - **Radios:** skips forcing `checked` in `created` when the user changed it, then syncs the checked radio in `mounted`. - **Selects:** detects a changed selection for single and multiple selects, including the browser's implicit first-enabled-option default. It refactors the change handlers into shared helpers without changing their behavior. Its tests are thorough and would fail before the fix: text, modifiers, textarea, sanitized types, dynamic type, checkbox bool/array, radio, select single/multi, and untouched fields staying reactive. The module-level `hydratedCheckboxModels` map adds some complexity, but it is cleared on `nextTick` and is limited to hydration. Overall, A resolves the issue far more completely and is better tested, while B is a narrow partial fix.
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
13m 46s
Wall-clock time in the container
Full test suite
No new failures
3,658 passed · 6 skipped · 3,664 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
376vs 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..91bb910a3 100644@@ -1718,6 +1718,163 @@ describe('SSR hydration', () => { expect((container.firstChild!.firstChild as any)._value).toBe(true) }) + describe('preserve form values entered before hydration', () => {+ async function hydrateAfterUserInput(+ template: string,+ initialState: Record<string, any>,+ userInput: (container: HTMLElement) => void,+ ) {+ const state = reactive({ ...initialState })+ const App = { setup: () => ({ state }), template }+ const container = document.createElement('div')+ const serverState = reactive({ ...initialState })+ container.innerHTML = await renderToString(+ h({ template, setup: () => ({ state: serverState }) }),+ )+ // user interacts with the server-rendered markup before hydration+ userInput(container)+ createSSRApp(App).mount(container)+ await nextTick()+ return { state, container }+ }++ test('text input', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input v-model="state.text">`,+ { text: 'foo' },+ c => (c.querySelector('input')!.value = 'typed'),+ )+ expect(container.querySelector('input')!.value).toBe('typed')+ expect(state.text).toBe('typed')+ })++ test('text input with .trim / .number modifiers', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input class="trim" v-model.trim="state.text">` ++ `<input class="num" v-model.number="state.num">` ++ `<input class="type-num" type="number" v-model="state.typeNum">`,+ { text: '', num: 0, typeNum: 1 },+ c => {+ ;(c.querySelector('.trim') as HTMLInputElement).value = ' hi '+ ;(c.querySelector('.num') as HTMLInputElement).value = '42'+ ;(c.querySelector('.type-num') as HTMLInputElement).value = '7'+ },+ )+ expect(state.text).toBe('hi')+ expect(state.num).toBe(42)+ expect(state.typeNum).toBe(7)+ expect((container.querySelector('.num') as HTMLInputElement).value).toBe(+ '42',+ )+ })++ test('textarea', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<textarea v-model="state.text"></textarea>`,+ { text: 'foo' },+ c => (c.querySelector('textarea')!.value = 'typed\nlines'),+ )+ expect(container.querySelector('textarea')!.value).toBe('typed\nlines')+ expect(state.text).toBe('typed\nlines')+ })++ test('value sanitized by the browser is not synced to the model', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input class="color" type="color" v-model="state.color">` ++ `<input class="range" type="range" v-model="state.range">`,+ { color: '#FF0000', range: null },+ () => {},+ )+ const color = container.querySelector('.color') as HTMLInputElement+ expect(color.value).toBe('#ff0000')+ expect(state.color).toBe('#FF0000')+ expect(state.range).toBe(null)+ })++ test('input with dynamic type', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input :type="state.type" v-model="state.text">`,+ { type: 'text', text: 'foo' },+ c => (c.querySelector('input')!.value = 'typed'),+ )+ expect(container.querySelector('input')!.value).toBe('typed')+ expect(state.text).toBe('typed')+ })++ test('checkbox (boolean and array)', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input class="bool" type="checkbox" v-model="state.bool">` ++ `<input class="a" type="checkbox" value="a" v-model="state.list">` ++ `<input class="b" type="checkbox" value="b" v-model="state.list">`,+ { bool: false, list: ['a'] },+ c => {+ ;(c.querySelector('.bool') as HTMLInputElement).checked = true+ ;(c.querySelector('.a') as HTMLInputElement).checked = false+ ;(c.querySelector('.b') as HTMLInputElement).checked = true+ },+ )+ expect(state.bool).toBe(true)+ expect(state.list).toEqual(['b'])+ const inputs = container.querySelectorAll('input')+ expect([...inputs].map(i => i.checked)).toEqual([true, false, true])+ })++ test('radio', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input class="a" type="radio" value="a" v-model="state.picked">` ++ `<input class="b" type="radio" value="b" v-model="state.picked">`,+ { picked: 'a' },+ c => ((c.querySelector('.b') as HTMLInputElement).checked = true),+ )+ expect(state.picked).toBe('b')+ expect((container.querySelector('.a') as HTMLInputElement).checked).toBe(+ false,+ )+ expect((container.querySelector('.b') as HTMLInputElement).checked).toBe(+ true,+ )+ })++ test('select (single and multiple)', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<select class="single" v-model="state.single">` ++ `<option value="a">a</option><option value="b">b</option></select>` ++ `<select class="multi" multiple v-model="state.multi">` ++ `<option value="a">a</option><option value="b">b</option></select>`,+ { single: 'a', multi: ['a'] },+ c => {+ ;(c.querySelector('.single') as HTMLSelectElement).value = 'b'+ const multi = c.querySelector('.multi') as HTMLSelectElement+ multi.options[0].selected = false+ multi.options[1].selected = true+ },+ )+ expect(state.single).toBe('b')+ expect(state.multi).toEqual(['b'])+ expect(container.querySelector('select')!.value).toBe('b')+ })++ test('untouched fields keep the model value', async () => {+ const { state, container } = await hydrateAfterUserInput(+ `<input v-model="state.text">` ++ `<input type="checkbox" v-model="state.bool">` ++ // no option matches: the browser auto-selects the first option+ `<select v-model="state.picked">` ++ `<option value="a">a</option><option value="b">b</option></select>`,+ { text: 'foo', bool: true, picked: 'none' },+ () => {},+ )+ expect(state).toEqual({ text: 'foo', bool: true, picked: 'none' })+ expect(container.querySelector('input')!.value).toBe('foo')+ expect(container.querySelector('select')!.selectedIndex).toBe(-1)++ // still reactive after hydration+ state.text = 'bar'+ await nextTick()+ expect(container.querySelector('input')!.value).toBe('bar')+ })+ })+ // #7203 test('force hydrate custom element with dynamic props', () => { class MyElement extends HTMLElement {packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..8e042acce 100644@@ -38,6 +38,39 @@ function onCompositionEnd(e: Event) { } const assignKey: unique symbol = Symbol('_assign')+const hydratingKey: unique symbol = Symbol('_hydrating')++/**+ * Called in the `created` hook. A freshly created element has not been+ * inserted yet at that point, so an element that already has a parent is one+ * being hydrated from server-rendered markup.+ */+function markHydrating(el: Element & { [hydratingKey]?: boolean }): boolean {+ return (el[hydratingKey] = !!el.parentNode)+}++/**+ * Called in the `mounted` hook. Returns true only for elements that were+ * hydrated (this flag is consumed and cleared here).+ */+function consumeHydrating(el: Element & { [hydratingKey]?: boolean }) {+ const hydrating = !!el[hydratingKey]+ el[hydratingKey] = false+ return hydrating+}++/**+ * Whether the user edited the value of a server-rendered input / textarea.+ * The browser sanitizes the `value` attribute for some input types (e.g.+ * range, color, email), so compare against the sanitized default value rather+ * than the raw attribute.+ */+function isValueChanged(el: HTMLInputElement | HTMLTextAreaElement): boolean {+ if (el.value === el.defaultValue) return false+ const clone = el.cloneNode() as HTMLInputElement | HTMLTextAreaElement+ clone.value = el.defaultValue+ return el.value !== clone.value+} type ModelDirective<T, Modifiers extends string = string> = ObjectDirective< T & { [assignKey]: AssignerFn; _assigning?: boolean },@@ -58,6 +91,7 @@ export const vModelText: ModelDirective< 'trim' | 'number' | 'lazy' > = { created(el, { modifiers: { lazy, trim, number } }, vnode) {+ markHydrating(el) el[assignKey] = getModelAssigner(vnode) const castToNumber = number || (vnode.props && vnode.props.type === 'number')@@ -81,7 +115,19 @@ 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) {+ // preserve a value the user entered before hydration finished and sync it+ // back to the model instead of resetting it to the server-rendered value+ if (consumeHydrating(el) && isValueChanged(el)) {+ el[assignKey](+ castValue(+ el.value,+ trim,+ number || (vnode.props && vnode.props.type === 'number'),+ ),+ )+ return+ } el.value = value == null ? '' : value }, beforeUpdate(@@ -125,43 +171,74 @@ export const vModelCheckbox: ModelDirective<HTMLInputElement> = { // #4096 array checkboxes need to be deep traversed deep: true, created(el, _, vnode) {+ markHydrating(el) el[assignKey] = getModelAssigner(vnode)- addEventListener(el, 'change', () => {- const modelValue = (el as any)._modelValue- const elementValue = getValue(el)- const checked = el.checked+ addEventListener(el, 'change', () => assignCheckboxValue(el))+ },+ // set initial checked on mount to wait for true-value/false-value+ mounted(el, binding, vnode) {+ // preserve checked state toggled by the user before hydration finished+ if (consumeHydrating(el) && el.checked !== el.defaultChecked) {+ // checkboxes sharing an array / Set model are synced in the same flush,+ // before a re-render can pass them the value assigned by a sibling, so+ // build on the latest value assigned to the same model.+ let model = binding.value+ while (hydratedCheckboxModels.has(model)) {+ model = hydratedCheckboxModels.get(model)+ }+ ;(el as any)._modelValue = model 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)+ assignCheckboxValue(el, newModel => {+ if (isArray(model) || isSet(model)) {+ if (!hydratedCheckboxModels.size) {+ nextTick(() => hydratedCheckboxModels.clear())+ }+ hydratedCheckboxModels.set(model, newModel) }- assign(cloned)- } else {- assign(getCheckboxValue(el, checked))- }- })+ assign(newModel)+ })+ return+ }+ setChecked(el, binding, vnode) },- // set initial checked on mount to wait for true-value/false-value- mounted: setChecked, beforeUpdate(el, binding, vnode) { el[assignKey] = getModelAssigner(vnode) setChecked(el, binding, vnode) }, } +const hydratedCheckboxModels = new Map<any, any>()++function assignCheckboxValue(+ el: HTMLInputElement & { [assignKey]: AssignerFn },+ assign: AssignerFn = el[assignKey],+) {+ const modelValue = (el as any)._modelValue+ const elementValue = getValue(el)+ const checked = el.checked+ 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))+ }+}+ function setChecked( el: HTMLInputElement, { value, oldValue }: DirectiveBinding,@@ -189,12 +266,23 @@ function setChecked( export const vModelRadio: ModelDirective<HTMLInputElement> = { created(el, { value }, vnode) {- el.checked = looseEqual(value, vnode.props!.value)+ // during hydration, leave a checked state changed by the user untouched;+ // it is synced to the model in mounted+ if (!(markHydrating(el) && el.checked !== el.defaultChecked)) {+ el.checked = looseEqual(value, vnode.props!.value)+ } el[assignKey] = getModelAssigner(vnode) addEventListener(el, 'change', () => { el[assignKey](getValue(el)) }) },+ mounted(el) {+ // the user checked this radio before hydration finished, sync it to the+ // model (a radio unchecked by the user is handled by the checked one)+ if (consumeHydrating(el) && el.checked && !el.defaultChecked) {+ el[assignKey](getValue(el))+ }+ }, beforeUpdate(el, { value, oldValue }, vnode) { el[assignKey] = getModelAssigner(vnode) if (value !== oldValue) {@@ -207,20 +295,10 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { // <select multiple> value need to be deep traversed deep: true, created(el, { value, modifiers: { number } }, vnode) {+ markHydrating(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],- )+ assignSelectedValue(el, number) el._assigning = true nextTick(() => { el._assigning = false@@ -230,7 +308,12 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { }, // set value in mounted & updated because <select> relies on its children // <option>s.- mounted(el, { value }) {+ mounted(el, { value, modifiers: { number } }) {+ // preserve a selection made by the user before hydration finished+ if (consumeHydrating(el) && isSelectionChanged(el)) {+ assignSelectedValue(el, number)+ return+ } setSelected(el, value) }, beforeUpdate(el, { value }, vnode) {@@ -244,6 +327,58 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { }, } +function assignSelectedValue(+ el: HTMLSelectElement & { [assignKey]: AssignerFn },+ 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],+ )+}++/**+ * Whether the current selection differs from the one the browser derives from+ * the server-rendered `selected` attributes.+ */+function isSelectionChanged(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+ }+ // for a single select, the last option with `selected` wins. Without one,+ // a select with a display size of 1 selects its first enabled option.+ let defaultIndex = -1+ for (let i = 0; i < options.length; i++) {+ if (options[i].defaultSelected) defaultIndex = i+ }+ if (defaultIndex === -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)+ ) {+ defaultIndex = i+ break+ }+ }+ }+ return el.selectedIndex !== defaultIndex+}+ 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,