From 182c3ba3932a46aa99ba2d7413edc90e27e88239 Mon Sep 17 00:00:00 2001 From: Azalea <22280294+hykilpikonna@users.noreply.github.com> Date: Thu, 20 Mar 2025 06:05:03 -0400 Subject: [PATCH] [+] selectJsonFile --- AquaNet/src/libs/ui.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/AquaNet/src/libs/ui.ts b/AquaNet/src/libs/ui.ts index 23bca645..8eabcc82 100644 --- a/AquaNet/src/libs/ui.ts +++ b/AquaNet/src/libs/ui.ts @@ -221,3 +221,44 @@ export function download(data: string, filename: string) { link.download = filename; link.click(); } + +export async function selectJsonFile(): Promise { + return new Promise((resolve, reject) => { + // Create a hidden file input element + const input = document.createElement('input'); + input.type = 'file'; + input.accept = '.json,application/json'; + input.style.display = 'none'; + + // Listen for when the user selects a file + input.addEventListener('change', (event: Event) => { + const target = event.target as HTMLInputElement; + if (!target.files || target.files.length === 0) { + return reject(new Error("No file selected")); + } + const file = target.files[0]; + const reader = new FileReader(); + + reader.onload = () => { + try { + const jsonData = JSON.parse(reader.result as string); + resolve(jsonData); + } catch (error) { + reject(new Error("Error parsing JSON: " + error)); + } + }; + + reader.onerror = () => { + reject(new Error("Error reading file")); + }; + + reader.readAsText(file); + }); + + // Append the input to the DOM, trigger click, and then remove it + document.body.appendChild(input); + input.click(); + document.body.removeChild(input); + }); +} +