Skip to content

Commit 4670d7e

Browse files
feat: Allow chunk to swap previous chunk (#182)
Co-authored-by: Douglas Duteil <douglasduteil@gmail.com>
1 parent 9238dde commit 4670d7e

1 file changed

Lines changed: 33 additions & 3 deletions

File tree

index.ts

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,35 @@ declare const htmx: typeof htmxType;
2222

2323
if (name === "htmx:beforeRequest") {
2424
const xhr = evt.detail.xhr as XMLHttpRequest;
25+
(xhr as any)._chunkedMode = elt.getAttribute("hx-chunked-mode") || "append";
26+
(xhr as any)._chunkedLastLen = 0;
27+
2528
xhr.onprogress = function () {
2629
const is_chunked =
2730
xhr.getResponseHeader("Transfer-Encoding") === "chunked";
2831

2932
if (!is_chunked) return;
3033

31-
let response = xhr.response as string;
34+
const mode = (xhr as any)._chunkedMode || "append";
35+
const full = (xhr.response as string) ?? "";
36+
let response: string;
37+
38+
if (mode === "swap") {
39+
const lastLen = (xhr as any)._chunkedLastLen || 0;
40+
if (full.length <= lastLen) return;
41+
response = full.slice(lastLen);
42+
(xhr as any)._chunkedLastLen = full.length;
43+
} else {
44+
response = full;
45+
}
3246

3347
api.withExtensions(elt, function (extension) {
3448
if (!extension.transformResponse) return;
3549
response = extension.transformResponse(response, xhr, elt);
3650
});
3751

38-
var swapSpec = api.getSwapSpecification(elt);
39-
var settleInfo = api.makeSettleInfo(elt);
52+
const swapSpec = api.getSwapSpecification(elt);
53+
const settleInfo = api.makeSettleInfo(elt);
4054
if (api.swap) {
4155
api.swap(target, response, swapSpec);
4256
} else {
@@ -51,6 +65,22 @@ declare const htmx: typeof htmxType;
5165
api.settleImmediately(settleInfo.tasks);
5266
};
5367
}
68+
69+
// Keep: cancel final full swap in swap mode
70+
if (name === "htmx:beforeSwap") {
71+
const detail = evt.detail as any;
72+
const xhr = detail && (detail.xhr as XMLHttpRequest | undefined);
73+
if (!xhr) return;
74+
75+
const mode = (xhr as any)._chunkedMode;
76+
if (mode !== "swap") return;
77+
78+
const is_chunked =
79+
xhr.getResponseHeader("Transfer-Encoding") === "chunked";
80+
if (!is_chunked) return;
81+
82+
detail.shouldSwap = false;
83+
}
5484
},
5585
} as HtmxExtension & { init: (apiRef: any) => void });
5686
})();

0 commit comments

Comments
 (0)