Files
faunosteo/apps/app/src/lib/download.ts
T

31 lines
935 B
TypeScript

import { todayIso } from '@/lib/dates'
const REVOKE_DELAY_MS = 30_000
/**
* Saves `blob` under `fileName`. The anchor is attached while clicked and the URL revoked
* later, since some engines (WebKit) cancel a download whose URL is revoked at once.
*/
export function downloadBlob(blob: Blob, fileName: string): void {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
}
/**
* Saves `raw` as `<stem>-<date>.json`. A lone surrogate in a JSON.stringify output is a
* `\uXXXX` escape, so the UTF-8 Blob is lossless. This copy may be the last one before a
* deletion.
*/
export function downloadJson(raw: string, stem: string): void {
downloadBlob(
new Blob([raw], { type: 'application/json' }),
`${stem}-${todayIso()}.json`,
)
}