| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 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 |
})(); |