Debian Codegraph @

dist/ext/hx-download.js

raw symbols SCIP
1 //==========================================================
2 // hx-download.js
3 //
4 // An extension that triggers a file download instead of a
5 // DOM swap, with streaming progress events for progress bars.
6 //
7 // Activates when:
8 // - hx-swap="download" is set on the element
9 // - server responds with Content-Disposition: attachment
10 // - server responds with HX-Download: <url> (fetches that
11 // url as the download, useful when the backend cannot
12 // stream the file directly as the htmx response)
13 //
14 // Usage:
15 // <button hx-get="/file.pdf" hx-swap="download"
16 // hx-ext="download">Download</button>
17 //
18 // Events:
19 // htmx:download:start {total}
20 // htmx:download:progress {loaded, total, percent}
21 // htmx:download:complete {filename, size}
22 //==========================================================
23 (() => {
24 let api;
25
26 htmx.registerExtension('download', {
27 init: (internalAPI) => {
28 api = internalAPI;
29 },
30 htmx_before_response: (elt, {ctx}) => {
31 let downloadUrl = ctx.response.headers.get('HX-Download');
32 if (downloadUrl) {
33 (async () => streamDownload(ctx.sourceElement, await fetch(downloadUrl), downloadUrl))();
34 return;
35 }
36 let cd = ctx.response.headers.get('Content-Disposition');
37 if (ctx.swap !== 'download' && !cd?.includes('attachment')) return;
38 streamDownload(ctx.sourceElement, ctx.response.raw, ctx.request.action);
39 return false;
40 }
41 });
42
43 function streamDownload(sourceElement, response, url) {
44 (async () => {
45 let total = +response.headers.get('Content-Length') || null;
46 api.triggerHtmxEvent(sourceElement, 'htmx:download:start', {total});
47 let reader = response.body.getReader();
48 let chunks = [], loaded = 0;
49 while (true) {
50 let {done, value} = await reader.read();
51 if (done) break;
52 chunks.push(value);
53 loaded += value.length;
54 api.triggerHtmxEvent(sourceElement, 'htmx:download:progress', {
55 loaded, total,
56 percent: total ? Math.round(loaded / total * 100) : null
57 });
58 }
59 let blob = new Blob(chunks, {
60 type: response.headers.get('Content-Type') || 'application/octet-stream'
61 });
62 let filename = parseFilename(response.headers, url);
63 let blobUrl = URL.createObjectURL(blob);
64 Object.assign(document.createElement('a'), {href: blobUrl, download: filename}).click();
65 URL.revokeObjectURL(blobUrl);
66 api.triggerHtmxEvent(sourceElement, 'htmx:download:complete', {filename, size: blob.size});
67 })();
68 }
69
70 function parseFilename(headers, url) {
71 let cd = headers.get('Content-Disposition');
72 if (cd) {
73 let match = cd.match(/filename\*?=['"]?(?:UTF-8'')?([^'";]+)/i);
74 if (match) return decodeURIComponent(match[1]);
75 }
76 return url.split('/').pop().split('?')[0] || 'download';
77 }
78 })();