From 4e3fa649a3662ad58e4a8e2e645774a3ecd0266b Mon Sep 17 00:00:00 2001 From: SahinurDEV <68515168+SahinurDEV@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:28:52 +0600 Subject: [PATCH] Keep field values the user changed while a morph request was out Morph only kept the value of the focused field. A user who typed while the request was out and then moved focus lost that text to the response. Treat a field's value as the user's when it differs from the value the request sent for it. Fixes #4184 --- src/htmx.d.ts | 2 + src/htmx.js | 25 ++++++---- test/tests/unit/morph.js | 48 ++++++++++++++++++++ www/src/content/docs/morphing-swaps-guide.md | 4 ++ 4 files changed, 71 insertions(+), 8 deletions(-) diff --git a/src/htmx.d.ts b/src/htmx.d.ts index c9440f050..2eb729a1a 100644 --- a/src/htmx.d.ts +++ b/src/htmx.d.ts @@ -433,6 +433,8 @@ export interface HtmxRequestCtx { transition: boolean; /** Fetch request options: modify here in htmx:config:request */ request: HtmxRequestOptions; + /** Request body as sent, after htmx:config:request. Morph swaps keep field values the user changed since */ + sentValues?: FormData; /** Response object, available after fetch resolves */ response?: HtmxResponse; /** Response body text, available during htmx:after:request */ diff --git a/src/htmx.js b/src/htmx.js index 0a7f5fcb2..386c1980d 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -514,6 +514,8 @@ var htmx = (() => { if (!this.__trigger(elt, "htmx:config:request", {ctx: ctx})) return if (ctx.request.method === 'DIALOG') return + // Morph compares fields against these to keep values the user changed since + ctx.sentValues = ctx.request.body let javascriptContent = this.__extractJavascriptContent(ctx.request.action); if (javascriptContent != null) { @@ -1295,6 +1297,7 @@ var htmx = (() => { let swapPromises = []; let transitionTasks = []; for (let task of tasks) { + task.sentValues ??= ctx.sentValues; if (task.swapSpec?.transition ?? mainSwap?.transition ?? ctx.transition) { transitionTasks.push(task); } else { @@ -1436,10 +1439,10 @@ var htmx = (() => { target.replaceChildren(...fragment.firstElementChild.childNodes); newContent = [target]; } else if (swapStyle === 'innerMorph') { - this.__morph(target, fragment, true); + this.__morph(target, fragment, true, task.sentValues); newContent = [...target.childNodes]; } else if (swapStyle === 'outerMorph') { - this.__morph(target, fragment, false); + this.__morph(target, fragment, false, task.sentValues); newContent.push(target); } else if (swapStyle === 'beforebegin') { if (parentNode) { @@ -2016,12 +2019,12 @@ var htmx = (() => { htmxProp.listeners.push({fromElt: elt, eventName: "htmx:abort", handler}); } - __morph(oldNode, fragment, innerHTML) { + __morph(oldNode, fragment, innerHTML, sentValues) { let {persistentIds, idMap} = this.__createIdMaps(oldNode, fragment); let pantry = document.createElement("div"); pantry.hidden = true; document.body.after( pantry); - let ctx = {target: oldNode, idMap, persistentIds, pantry, futureMatches: new WeakSet()}; + let ctx = {target: oldNode, idMap, persistentIds, pantry, futureMatches: new WeakSet(), sentValues}; if (innerHTML) { this.__morphChildren(ctx, oldNode, fragment); @@ -2191,8 +2194,8 @@ var htmx = (() => { // Trigger extension hook - if returns false, skip morphing this node if (!this.__triggerExtensions(oldNode, "htmx:before:morph:node", {oldNode, newNode})) return; - this.__copyAttributes(oldNode, newNode); - if (oldNode instanceof HTMLTextAreaElement && document.activeElement !== oldNode && oldNode.defaultValue != newNode.defaultValue) { + this.__copyAttributes(oldNode, newNode, ctx.sentValues); + if (oldNode instanceof HTMLTextAreaElement && !this.__hasUserValue(oldNode, ctx.sentValues) && oldNode.defaultValue != newNode.defaultValue) { oldNode.value = newNode.value; } let skipChildren = this.config.morphSkipChildren && oldNode.matches?.(this.config.morphSkipChildren); @@ -2202,7 +2205,13 @@ var htmx = (() => { } } - __copyAttributes(destination, source) { + __hasUserValue(field, sentValues) { + if (document.activeElement === field) return true; + // The request carried another value, so the user changed the field since it was sent + return !!field.name && !!sentValues?.has?.(field.name) && !sentValues.getAll(field.name).includes(field.value); + } + + __copyAttributes(destination, source, sentValues) { let attributesToIgnore = this.config.morphIgnore || []; let needsReinit = false; let isHxAttr = name => this.__prefixes('hx-').some(p => name.startsWith(p)); @@ -2211,7 +2220,7 @@ var htmx = (() => { if (isHxAttr(attr.name)) needsReinit = true; if (!this.__triggerExtensions(destination, 'htmx:before:morph:attr', { attrName: attr.name, newValue: attr.value })) continue; destination.setAttribute(attr.name, attr.value); - if (attr.name === "value" && destination instanceof HTMLInputElement && destination.type !== "file" && document.activeElement !== destination) { + if (attr.name === "value" && destination instanceof HTMLInputElement && destination.type !== "file" && !this.__hasUserValue(destination, sentValues)) { destination.value = attr.value; } } diff --git a/test/tests/unit/morph.js b/test/tests/unit/morph.js index 7d0c418d7..95549c82e 100644 --- a/test/tests/unit/morph.js +++ b/test/tests/unit/morph.js @@ -428,6 +428,54 @@ describe('Morph Swap Styles Tests', function() { assert.equal(textarea.value, 'user typed this', 'focused textarea value should not be overwritten'); }); + it('keeps text typed while the request was out after the input loses focus', async function() { + mockResponse('POST', '/validate', ''); + const form = createProcessedHTML('
'); + const name = form.querySelector('#name'); + name.value = 'ab'; + form.addEventListener('htmx:before:swap', () => { + // the user types more and tabs away before the answer lands + name.value = 'abcd'; + form.querySelector('#other').focus(); + }, {once: true}); + + form.requestSubmit(); + await forRequest(); + + assert.equal(form.querySelector('#name'), name, 'input node should be preserved'); + assert.equal(name.getAttribute('value'), 'ab', 'value attribute should follow the response'); + assert.equal(name.value, 'abcd', 'text typed after the request should be kept'); + }); + + it('keeps a textarea edited while the request was out after it loses focus', async function() { + mockResponse('GET', '/validate', ''); + const div = createProcessedHTML('
'); + const notes = div.querySelector('#notes'); + notes.value = 'first'; + div.addEventListener('htmx:before:swap', () => { notes.value = 'first draft'; }, {once: true}); + + div.click(); + await forRequest(); + + assert.equal(div.querySelector('#notes'), notes, 'textarea node should be preserved'); + assert.equal(notes.value, 'first draft', 'text typed after the request should be kept'); + }); + + it('applies the response value to an input the user did not change since the request', async function() { + mockResponse('POST', '/validate', ''); + const form = createProcessedHTML('
'); + const name = form.querySelector('#name'); + const email = form.querySelector('#email'); + name.value = 'ab '; + email.value = 'a@example.com'; + + form.requestSubmit(); + await forRequest(); + + assert.equal(name.value, 'Ab', 'a value the server normalized should replace the sent one'); + assert.equal(email.value, 'b@example.com', 'an input that was not sent should take the response value'); + }); + }); describe('element reordering with ids', function() { diff --git a/www/src/content/docs/morphing-swaps-guide.md b/www/src/content/docs/morphing-swaps-guide.md index e49e0ad5c..226a8a362 100644 --- a/www/src/content/docs/morphing-swaps-guide.md +++ b/www/src/content/docs/morphing-swaps-guide.md @@ -96,6 +96,10 @@ Morph can be very useful for replacing or updating forms for dynamic validation. Morph swaps automatically preserve the value of the currently focused input or textarea, even when the server returns a different value. This prevents stale responses from overwriting what the user is typing. +The same goes for an input or textarea the user changed after the request was sent, even if it has lost focus since: +when the field's current value is not the one the request carried for its `name`, morph keeps the user's value and +only updates the `value` attribute. + For unfocused inputs, htmx preserves the user's value unless the `value` attribute changes between old and new content. This differs from idiomorph's default behavior, which resets the `.value` property to match the `value` attribute on every morph. To preserve all input values, have your server return inputs without changing the `value` attribute, or add `'value'` to `htmx.config.morphIgnore`.