aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/utils/fileIO.ts
blob: abcc43eb6f21079763a6295786531f43e9e6839a (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * SPDX-FileCopyrightText: 2024 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

export async function saveBlob(
  blob: Blob,
  name: string,
  mimeType: string,
  id?: string,
): Promise<void> {
  if ('showSaveFilePicker' in window) {
    const options: FilePickerOptions = {
      suggestedName: name,
    };
    if (id !== undefined) {
      options.id = id;
    }
    const extensionIndex = name.lastIndexOf('.');
    if (extensionIndex >= 0) {
      options.types = [
        {
          description: `${name.substring(extensionIndex + 1)} files`,
          accept: {
            [mimeType]: [name.substring(extensionIndex)],
          },
        },
      ];
    }
    const handle = await window.showSaveFilePicker(options);
    const writable = await handle.createWritable();
    try {
      await writable.write(blob);
    } finally {
      await writable.close();
    }
    return;
  }
  const link = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  try {
    link.href = url;
    link.download = name;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
  } finally {
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  }
}

export async function copyBlob(blob: Blob): Promise<void> {
  const { clipboard } = navigator;
  if ('write' in clipboard) {
    await clipboard.write([
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);
  }
}