aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/lib/ts/download.ts
blob: a6167d757bb08be90327e289889b2595beefbf57 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Yoinked from https://web.dev/patterns/files/save-a-file/ for the polyfill

export default async function saveFile(blob: ArrayBuffer, suggestedName: string | undefined) {
	const supportsFSAccess = 'showSaveFilePicker' in window &&
		(() => {
			try {
				return window.self === window.top;
			} catch {
				return false;
			}
		})();

	if (supportsFSAccess) {
		try {
			const handle = await window.showSaveFilePicker({
				suggestedName: suggestedName,
			})
			const writable = await handle.createWritable();
			await writable.write(blob);
			await writable.close();
		} catch (err: unknown) {
			// TypeScript
			if ((err as Error)?.name !== 'AbortError') {
				console.error(err);
			}
		}
	} else {
		const anchor = document.createElement('a');
		anchor.download = suggestedName ?? 'truncated';
		anchor.href = URL.createObjectURL(new Blob([blob]));
		anchor.click();
	}
}