aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/utils/fileIO.ts
blob: fe0b1fbb6f23ece718aa4630dcb26bbef6e5dd81 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * SPDX-FileCopyrightText: 2024 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

export interface OpenResult {
  name: string;
  handle: FileSystemFileHandle | undefined;
}

export interface OpenTextFileResult extends OpenResult {
  text: string;
}

export async function openTextFile(
  options: FilePickerOptions,
): Promise<OpenTextFileResult> {
  let file: File;
  let handle: FileSystemFileHandle | undefined;
  if ('showOpenFilePicker' in window) {
    [handle] = await window.showOpenFilePicker(options);
    if (handle === undefined) {
      throw new Error('No file was selected');
    }
    file = await handle.getFile();
  } else {
    const input = document.createElement('input');
    input.type = 'file';
    file = await new Promise((resolve, reject) => {
      input.addEventListener('change', () => {
        const { files } = input;
        const result = files?.item(0);
        if (result) {
          resolve(result);
        } else {
          reject(new Error('No file was selected'));
        }
      });
      input.click();
    });
  }
  const text = await file.text();
  return {
    name: file.name,
    text,
    handle,
  };
}

export async function saveTextFile(
  handle: FileSystemFileHandle,
  text: string,
): Promise<void> {
  const writable = await handle.createWritable();
  try {
    await writable.write(text);
  } finally {
    await writable.close();
  }
}

export async function saveBlob(
  blob: Blob,
  name: string,
  options: FilePickerOptions,
): Promise<OpenResult | undefined> {
  if ('showSaveFilePicker' in window) {
    const handle = await window.showSaveFilePicker({
      ...options,
      suggestedName: name,
    });
    const writable = await handle.createWritable();
    try {
      await writable.write(blob);
    } finally {
      await writable.close();
    }
    return {
      name: handle.name,
      handle,
    };
  }
  const link = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  try {
    link.href = url;
    link.download = name;
    link.click();
  } finally {
    window.URL.revokeObjectURL(url);
  }
  return undefined;
}

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