2020-07-11 13:09:40 +02:00
|
|
|
import { getDefaultAppState, cleanAppStateForExport } from "../appState";
|
2020-03-07 10:20:38 -05:00
|
|
|
import { restore } from "./restore";
|
2020-04-03 12:50:51 +01:00
|
|
|
import { t } from "../i18n";
|
2020-07-11 13:09:40 +02:00
|
|
|
import { AppState } from "../types";
|
2020-03-07 10:20:38 -05:00
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const loadFromBlob = async (blob: any) => {
|
2020-03-07 10:20:38 -05:00
|
|
|
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 || [];
|
2020-07-11 13:09:40 +02:00
|
|
|
appState = {
|
|
|
|
...defaultAppState,
|
|
|
|
...cleanAppStateForExport(data.appState as Partial<AppState>),
|
|
|
|
};
|
2020-03-07 10:20:38 -05:00
|
|
|
} catch {
|
2020-04-10 10:58:09 +01:00
|
|
|
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
2020-03-07 10:20:38 -05:00
|
|
|
}
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|
2020-04-10 10:58:09 +01:00
|
|
|
|
2020-03-07 10:20:38 -05:00
|
|
|
const { elements, appState } = updateAppState(contents);
|
2020-04-10 10:58:09 +01:00
|
|
|
return restore(elements, appState, { scrollToContent: true });
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|