diff options
author | 2024-02-23 19:49:30 +0100 | |
---|---|---|
committer | 2024-02-23 19:49:30 +0100 | |
commit | 4944ca0f5ab9adfc17a45fadc778c7b78568a038 (patch) | |
tree | acabe2d42592a422b6032078e3114c0da6b7a2fa /subprojects/frontend/src/utils/fileIO.ts | |
parent | fix(frontend): top button styling (diff) | |
download | refinery-4944ca0f5ab9adfc17a45fadc778c7b78568a038.tar.gz refinery-4944ca0f5ab9adfc17a45fadc778c7b78568a038.tar.zst refinery-4944ca0f5ab9adfc17a45fadc778c7b78568a038.zip |
refactor(web): use filesystem access API when available
Diffstat (limited to 'subprojects/frontend/src/utils/fileIO.ts')
-rw-r--r-- | subprojects/frontend/src/utils/fileIO.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/subprojects/frontend/src/utils/fileIO.ts b/subprojects/frontend/src/utils/fileIO.ts new file mode 100644 index 00000000..abcc43eb --- /dev/null +++ b/subprojects/frontend/src/utils/fileIO.ts | |||
@@ -0,0 +1,63 @@ | |||
1 | /* | ||
2 | * SPDX-FileCopyrightText: 2024 The Refinery Authors <https://refinery.tools/> | ||
3 | * | ||
4 | * SPDX-License-Identifier: EPL-2.0 | ||
5 | */ | ||
6 | |||
7 | export async function saveBlob( | ||
8 | blob: Blob, | ||
9 | name: string, | ||
10 | mimeType: string, | ||
11 | id?: string, | ||
12 | ): Promise<void> { | ||
13 | if ('showSaveFilePicker' in window) { | ||
14 | const options: FilePickerOptions = { | ||
15 | suggestedName: name, | ||
16 | }; | ||
17 | if (id !== undefined) { | ||
18 | options.id = id; | ||
19 | } | ||
20 | const extensionIndex = name.lastIndexOf('.'); | ||
21 | if (extensionIndex >= 0) { | ||
22 | options.types = [ | ||
23 | { | ||
24 | description: `${name.substring(extensionIndex + 1)} files`, | ||
25 | accept: { | ||
26 | [mimeType]: [name.substring(extensionIndex)], | ||
27 | }, | ||
28 | }, | ||
29 | ]; | ||
30 | } | ||
31 | const handle = await window.showSaveFilePicker(options); | ||
32 | const writable = await handle.createWritable(); | ||
33 | try { | ||
34 | await writable.write(blob); | ||
35 | } finally { | ||
36 | await writable.close(); | ||
37 | } | ||
38 | return; | ||
39 | } | ||
40 | const link = document.createElement('a'); | ||
41 | const url = window.URL.createObjectURL(blob); | ||
42 | try { | ||
43 | link.href = url; | ||
44 | link.download = name; | ||
45 | link.style.display = 'none'; | ||
46 | document.body.appendChild(link); | ||
47 | link.click(); | ||
48 | } finally { | ||
49 | window.URL.revokeObjectURL(url); | ||
50 | document.body.removeChild(link); | ||
51 | } | ||
52 | } | ||
53 | |||
54 | export async function copyBlob(blob: Blob): Promise<void> { | ||
55 | const { clipboard } = navigator; | ||
56 | if ('write' in clipboard) { | ||
57 | await clipboard.write([ | ||
58 | new ClipboardItem({ | ||
59 | [blob.type]: blob, | ||
60 | }), | ||
61 | ]); | ||
62 | } | ||
63 | } | ||