diff options
Diffstat (limited to 'src/utils/web.ts')
-rw-r--r-- | src/utils/web.ts | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/utils/web.ts b/src/utils/web.ts index 9cfe718..5c46aec 100644 --- a/src/utils/web.ts +++ b/src/utils/web.ts @@ -16,6 +16,10 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ +/** + * Prompts the user to save a file to their system + * @param file The file to save + */ export function saveFile(file: File) { const a = document.createElement("a"); a.href = URL.createObjectURL(file); @@ -28,3 +32,24 @@ export function saveFile(file: File) { document.body.removeChild(a); }); } + +/** + * Prompts the user to choose a file from their system + * @param mimeTypes A comma separated list of mime types to accept, see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept#unique_file_type_specifiers + * @returns A promise that resolves to the chosen file or null if the user cancels + */ +export function chooseFile(mimeTypes: string) { + return new Promise<File | null>(resolve => { + const input = document.createElement("input"); + input.type = "file"; + input.style.display = "none"; + input.accept = mimeTypes; + input.onchange = async () => { + resolve(input.files?.[0] ?? null); + }; + + document.body.appendChild(input); + input.click(); + setImmediate(() => document.body.removeChild(input)); + }); +} |