Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/htmx.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
25 changes: 17 additions & 8 deletions src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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));
Expand All @@ -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;
}
}
Expand Down
48 changes: 48 additions & 0 deletions test/tests/unit/morph.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', '<input id="name" name="name" value="ab"><input id="other" name="other" value="">');
const form = createProcessedHTML('<form hx-post="/validate" hx-trigger="submit" hx-swap="innerMorph"><input id="name" name="name" value=""><input id="other" name="other" value=""></form>');
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', '<textarea id="notes" name="notes">first</textarea>');
const div = createProcessedHTML('<div hx-get="/validate" hx-include="#notes" hx-target="this" hx-swap="innerMorph"><textarea id="notes" name="notes"></textarea></div>');
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', '<input id="name" name="name" value="Ab"><input id="email" name="email" value="b@example.com">');
const form = createProcessedHTML('<form hx-post="/validate" hx-trigger="submit" hx-swap="innerMorph"><input id="name" name="name" value=""><input id="email" value=""></form>');
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() {
Expand Down
4 changes: 4 additions & 0 deletions www/src/content/docs/morphing-swaps-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down