| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
(() => { |
| 18 |
htmx.registerExtension('download', { |
| 19 |
htmx_before_request: (elt, {ctx}) => { |
| 20 |
if (ctx.swap !== 'download') return; |
| 21 |
let originalFetch = ctx.fetch; |
| 22 |
ctx.fetch = async (url, options) => { |
| 23 |
let response = await originalFetch(url, options); |
| 24 |
let total = +response.headers.get('Content-Length') || null; |
| 25 |
htmx.trigger(ctx.sourceElement, 'htmx:download:start', {total}); |
| 26 |
|
| 27 |
let reader = response.body.getReader(); |
| 28 |
let chunks = [], loaded = 0; |
| 29 |
while (true) { |
| 30 |
let {done, value} = await reader.read(); |
| 31 |
if (done) break; |
| 32 |
chunks.push(value); |
| 33 |
loaded += value.length; |
| 34 |
htmx.trigger(ctx.sourceElement, 'htmx:download:progress', { |
| 35 |
loaded, total, |
| 36 |
percent: total ? Math.round(loaded / total * 100) : null |
| 37 |
}); |
| 38 |
} |
| 39 |
|
| 40 |
ctx.download = { |
| 41 |
blob: new Blob(chunks, { |
| 42 |
type: response.headers.get('Content-Type') || 'application/octet-stream' |
| 43 |
}), |
| 44 |
filename: parseFilename(response.headers, url) |
| 45 |
}; |
| 46 |
return new Response('', {status: response.status, headers: response.headers}); |
| 47 |
}; |
| 48 |
}, |
| 49 |
|
| 50 |
htmx_before_swap: (elt, {ctx}) => { |
| 51 |
if (!ctx.download) return; |
| 52 |
let {blob, filename} = ctx.download; |
| 53 |
let url = URL.createObjectURL(blob); |
| 54 |
let a = document.createElement('a'); |
| 55 |
a.href = url; |
| 56 |
a.download = filename; |
| 57 |
a.click(); |
| 58 |
URL.revokeObjectURL(url); |
| 59 |
htmx.trigger(ctx.sourceElement, 'htmx:download:complete', {filename, size: blob.size}); |
| 60 |
return false; |
| 61 |
} |
| 62 |
}); |
| 63 |
|
| 64 |
function parseFilename(headers, url) { |
| 65 |
let cd = headers.get('Content-Disposition'); |
| 66 |
if (cd) { |
| 67 |
let match = cd.match(/filename\*?=['"]?(?:UTF-8'')?([^'";]+)/i); |
| 68 |
if (match) return decodeURIComponent(match[1]); |
| 69 |
} |
| 70 |
return url.split('/').pop().split('?')[0] || 'download'; |
| 71 |
} |
| 72 |
})(); |