All files / webapp/util JsonFileUpload.ts

88.88% Statements 16/18
50% Branches 3/6
75% Functions 3/4
88.88% Lines 16/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            8x   8x 8x 8x   8x 8x   8x 8x     8x       8x   8x   8x     8x       8x     8x 8x    
/**
 * Plain DOM utility (no UI5 dependency) for the "hidden `<input type=file>`"
 * upload dialog pattern, previously duplicated with identical boilerplate
 * across the App, Main and MyProducts controllers.
 *
 * Opens the browser's file picker restricted to `.json` files and reads the
 * selected file as text.
 * @param onContent Called with the selected file's text content once read
 * @param onError Called if reading the selected file fails
 */
export function pickJsonFile(
    onContent: (fileContent: string) => void,
    onError: () => void
): void {
    const fileInput = document.createElement("input");
 
    fileInput.type = "file";
    fileInput.accept = ".json,application/json";
    fileInput.style.display = "none";
 
    fileInput.addEventListener("change", () => {
        const selectedFile = fileInput.files?.[0];
 
        Eif (document.body.contains(fileInput)) {
            document.body.removeChild(fileInput);
        }
 
        Iif (!selectedFile) {
            return;
        }
 
        const fileReader = new FileReader();
 
        fileReader.onload = () => {
            // readAsText() always yields a string (or null) result, never an ArrayBuffer
            onContent(typeof fileReader.result === "string" ? fileReader.result : "");
        };
 
        fileReader.onerror = () => {
            onError();
        };
 
        fileReader.readAsText(selectedFile);
    });
 
    document.body.appendChild(fileInput);
    fileInput.click();
}