2020-09-22 21:51:49 +02:00
|
|
|
import { 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-09-22 21:51:49 +02:00
|
|
|
import { LibraryData, ImportedDataState } from "./types";
|
2020-07-27 17:18:49 +05:30
|
|
|
import { calculateScrollCenter } from "../scene";
|
2020-03-07 10:20:38 -05:00
|
|
|
|
2020-07-27 15:29:19 +03:00
|
|
|
const loadFileContents = async (blob: any) => {
|
|
|
|
let contents: string;
|
2020-03-07 10:20:38 -05:00
|
|
|
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-07-27 15:29:19 +03:00
|
|
|
return contents;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param blob
|
|
|
|
* @param appState if provided, used for centering scroll to restored scene
|
|
|
|
*/
|
|
|
|
export const loadFromBlob = async (blob: any, appState?: AppState) => {
|
|
|
|
if (blob.handle) {
|
2020-09-22 15:21:22 +02:00
|
|
|
// TODO: Make this part of `AppState`.
|
2020-07-27 15:29:19 +03:00
|
|
|
(window as any).handle = blob.handle;
|
|
|
|
}
|
2020-04-10 10:58:09 +01:00
|
|
|
|
2020-07-27 15:29:19 +03:00
|
|
|
const contents = await loadFileContents(blob);
|
2020-07-27 17:18:49 +05:30
|
|
|
try {
|
2020-09-22 21:51:49 +02:00
|
|
|
const data: ImportedDataState = JSON.parse(contents);
|
2020-07-27 17:18:49 +05:30
|
|
|
if (data.type !== "excalidraw") {
|
|
|
|
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
|
|
|
}
|
2020-09-22 21:51:49 +02:00
|
|
|
return restore({
|
|
|
|
elements: data.elements,
|
|
|
|
appState: {
|
|
|
|
appearance: appState?.appearance,
|
|
|
|
...cleanAppStateForExport(data.appState || {}),
|
|
|
|
...(appState
|
|
|
|
? calculateScrollCenter(data.elements || [], appState, null)
|
|
|
|
: {}),
|
|
|
|
},
|
|
|
|
});
|
2020-07-27 17:18:49 +05:30
|
|
|
} catch {
|
|
|
|
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
|
|
|
}
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2020-07-27 15:29:19 +03:00
|
|
|
|
|
|
|
export const loadLibraryFromBlob = async (blob: any) => {
|
|
|
|
const contents = await loadFileContents(blob);
|
|
|
|
const data: LibraryData = JSON.parse(contents);
|
|
|
|
if (data.type !== "excalidrawlib") {
|
|
|
|
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
|
|
|
}
|
|
|
|
return data;
|
|
|
|
};
|