From 47973721667ded7d14833e9115e756f55f029f92 Mon Sep 17 00:00:00 2001 From: EGRrqq Date: Wed, 31 Jan 2024 23:18:10 -0500 Subject: [PATCH] feat(cache): loadData returns a promise instead of a passing callback to it --- .../canvasData/manipulate/loadData.ts | 49 ++++++++++--------- src/index.ts | 8 +-- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/src/canvasController/canvasData/manipulate/loadData.ts b/src/canvasController/canvasData/manipulate/loadData.ts index 91a2ab5..63abae8 100644 --- a/src/canvasController/canvasData/manipulate/loadData.ts +++ b/src/canvasController/canvasData/manipulate/loadData.ts @@ -1,36 +1,37 @@ import { IData } from "../Data"; import { TContentType } from "./TContentType"; -type TLoadData = (callback: TCallback, contentType: TContentType) => void; -type TCallback = (data: IData) => void; +export function loadData(type: TContentType): Promise { + return new Promise((res, rej) => { + const input = createInput(type); -export const loadData: TLoadData = (callback, contentType) => { - const input = document.createElement("input"); + input.onchange = () => { + const file = input.files?.[0]; - input.type = "file"; - input.accept = contentType; - input.addEventListener("change", (e) => inputOnChange(e, callback), { - once: true, - }); - input.click(); + if (file) readData(file).then(res).catch(rej); + }; - input.remove(); -}; + input.click(); + }); +} -function inputOnChange(e: Event, callback: TCallback) { - const inputFile = (e.target as HTMLInputElement).files?.[0]; - if (inputFile) { - const fileReader = new FileReader(); +function readData(file: File): Promise { + return new Promise((res, rej) => { + const reader = new FileReader(); - fileReader.addEventListener("load", (e) => readerOnLoad(e, callback), { - once: true, - }); - fileReader.readAsText(inputFile); - } + reader.onerror = rej; + reader.onload = () => { + const data = JSON.parse(reader.result as string); + res(data); + }; + reader.readAsText(file); + }); } -function readerOnLoad(e: Event, callback: TCallback) { - const data: IData = JSON.parse((e.target as FileReader).result as string); +function createInput(type: TContentType): HTMLInputElement { + const input = document.createElement("input"); + input.type = "file"; + input.accept = type; - callback(data); + return input; } diff --git a/src/index.ts b/src/index.ts index 1b5a87f..e9482d8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -81,8 +81,8 @@ if (boardController.ctx) { ); }); - openBtnController.onClick(() => - loadData((data) => { + openBtnController.onClick(() => { + loadData("application/json").then((data) => { cacheController.clearDataElements(); for (let element of data.elements) { @@ -90,8 +90,8 @@ if (boardController.ctx) { } canvasSetup(); - }, "application/json") - ); + }); + }); clearBtnController.onClick(() => { cacheController.clearDataElements();