Skip to content

Commit

Permalink
feat(cache): loadData returns a promise
Browse files Browse the repository at this point in the history
instead of a passing callback to it
  • Loading branch information
EGRrqq committed Feb 1, 2024
1 parent f030b35 commit 4797372
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 28 deletions.
49 changes: 25 additions & 24 deletions src/canvasController/canvasData/manipulate/loadData.ts
Original file line number Diff line number Diff line change
@@ -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<IData> {
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<IData> {
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;
}
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,17 @@ if (boardController.ctx) {
);
});

openBtnController.onClick(() =>
loadData((data) => {
openBtnController.onClick(() => {
loadData("application/json").then((data) => {
cacheController.clearDataElements();

for (let element of data.elements) {
cacheController.storeDataElement(element);
}

canvasSetup();
}, "application/json")
);
});
});

clearBtnController.onClick(() => {
cacheController.clearDataElements();
Expand Down

0 comments on commit 4797372

Please sign in to comment.