aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/lib/ts/download.ts
blob: 48debec3a9221c97c4aa9f2fd6a7de958a403d12 (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
34
35
36
37
// 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()
      return
    } catch (err: unknown) {
      // TypeScript
      if ((err as Error)?.name !== 'AbortError') {
        return Promise.reject(err)
      }
    }
  } else {
    const anchor = document.createElement('a')
    anchor.download = suggestedName ?? 'truncated'
    anchor.href = URL.createObjectURL(new Blob([blob]))
    anchor.click()
    URL.revokeObjectURL(anchor.href)
    document.body.removeChild(anchor)
  }
}