Skip to content

Commit

Permalink
Fix htmx.ajax "mirror" errorSwap override value + test
Browse files Browse the repository at this point in the history
  • Loading branch information
Telroshan committed Jul 23, 2023
1 parent 8251869 commit aff2739
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -3349,14 +3349,20 @@ return (function () {
var shouldSwap = xhr.status >= 200 && xhr.status < 400 && xhr.status !== 204;

var isError = xhr.status >= 400;
var swapOverride = isError ? etc.errorSwapOverride : etc.swapOverride;
// User could force shouldSwap to true from a htmx:beforeSwap listener, in which case we don't want to
// interfere with hx-error-target & hx-error-swap logic by relying solely on isError
var isStandardErrorSwap = false
if (isError && (htmx.config.httpErrorCodesToSwap.length === 0 || htmx.config.httpErrorCodesToSwap.indexOf(xhr.status) >= 0)) {
if (etc.errorTargetOverride) {
responseInfo.target = etc.errorTargetOverride
}
var errorSwapSpec = getErrorTargetSpec(elt, responseInfo.target, etc.errorSwapOverride);
// Error swap override set to "mirror" should replicate standard swap override if defined
// Otherwise, fallback to attributes then default strategy
if (swapOverride === "mirror" && etc.swapOverride) {
swapOverride = etc.swapOverride
}
var errorSwapSpec = getErrorTargetSpec(elt, responseInfo.target, swapOverride);
if (errorSwapSpec.shouldSwap) {
shouldSwap = true;
isStandardErrorSwap = true
Expand Down Expand Up @@ -3401,7 +3407,6 @@ return (function () {
saveCurrentPageToHistory();
}

var swapOverride = isError ? etc.errorSwapOverride : etc.swapOverride;
if (hasHeader(xhr,/HX-Reswap:/i)) {
swapOverride = xhr.getResponseHeader("HX-Reswap");
}
Expand Down
10 changes: 10 additions & 0 deletions test/core/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -408,4 +408,14 @@ describe("Core htmx API test", function(){
}
});

it('ajax api works with errorSwap mirror', function () {
this.server.respondWith("GET", "/test", function (xhr) {
xhr.respond(400, {}, "<p class='test'>foo!</p>")
});
var div = make("<div id='target'><div id='child'></div></div>");
htmx.ajax("GET", "/test", {target: "#child", swap: "outerHTML", errorSwap: "mirror"});
this.server.respond();
div.innerHTML.should.equal('<p class="test">foo!</p>');
});

})

0 comments on commit aff2739

Please sign in to comment.