2020-03-07 10:20:38 -05:00
|
|
|
import { getDefaultAppState } from "../appState";
|
|
|
|
import { DataState } from "./types";
|
|
|
|
import { restore } from "./restore";
|
2020-04-03 12:50:51 +01:00
|
|
|
import { t } from "../i18n";
|
2020-03-07 10:20:38 -05:00
|
|
|
|
|
|
|
export async function loadFromBlob(blob: any) {
|
|
|
|
const updateAppState = (contents: string) => {
|
|
|
|
const defaultAppState = getDefaultAppState();
|
|
|
|
let elements = [];
|
|
|
|
let appState = defaultAppState;
|
|
|
|
try {
|
|
|
|
const data = JSON.parse(contents);
|
|
|
|
if (data.type !== "excalidraw") {
|
2020-04-03 12:50:51 +01:00
|
|
|
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
2020-03-07 10:20:38 -05:00
|
|
|
}
|
|
|
|
elements = data.elements || [];
|
|
|
|
appState = { ...defaultAppState, ...data.appState };
|
|
|
|
} catch {
|
|
|
|
// Do nothing because elements array is already empty
|
|
|
|
}
|
|
|
|
return { elements, appState };
|
|
|
|
};
|
|
|
|
|
|
|
|
if (blob.handle) {
|
|
|
|
(window as any).handle = blob.handle;
|
|
|
|
}
|
|
|
|
let contents;
|
|
|
|
if ("text" in Blob) {
|
|
|
|
contents = await blob.text();
|
|
|
|
} else {
|
2020-03-23 13:05:07 +02:00
|
|
|
contents = await new Promise((resolve) => {
|
2020-03-07 10:20:38 -05:00
|
|
|
const reader = new FileReader();
|
|
|
|
reader.readAsText(blob, "utf8");
|
|
|
|
reader.onloadend = () => {
|
|
|
|
if (reader.readyState === FileReader.DONE) {
|
|
|
|
resolve(reader.result as string);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
const { elements, appState } = updateAppState(contents);
|
|
|
|
if (!elements.length) {
|
2020-04-03 12:50:51 +01:00
|
|
|
return Promise.reject(t("alerts.couldNotLoadInvalidFile"));
|
2020-03-07 10:20:38 -05:00
|
|
|
}
|
2020-03-23 13:05:07 +02:00
|
|
|
return new Promise<DataState>((resolve) => {
|
2020-03-07 10:20:38 -05:00
|
|
|
resolve(restore(elements, appState, { scrollToContent: true }));
|
|
|
|
});
|
|
|
|
}
|