blob.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { getDefaultAppState, cleanAppStateForExport } from "../appState";
  2. import { restore } from "./restore";
  3. import { t } from "../i18n";
  4. import { AppState } from "../types";
  5. export const loadFromBlob = async (blob: any) => {
  6. const updateAppState = (contents: string) => {
  7. const defaultAppState = getDefaultAppState();
  8. let elements = [];
  9. let appState = defaultAppState;
  10. try {
  11. const data = JSON.parse(contents);
  12. if (data.type !== "excalidraw") {
  13. throw new Error(t("alerts.couldNotLoadInvalidFile"));
  14. }
  15. elements = data.elements || [];
  16. appState = {
  17. ...defaultAppState,
  18. ...cleanAppStateForExport(data.appState as Partial<AppState>),
  19. };
  20. } catch {
  21. throw new Error(t("alerts.couldNotLoadInvalidFile"));
  22. }
  23. return { elements, appState };
  24. };
  25. if (blob.handle) {
  26. (window as any).handle = blob.handle;
  27. }
  28. let contents;
  29. if ("text" in Blob) {
  30. contents = await blob.text();
  31. } else {
  32. contents = await new Promise((resolve) => {
  33. const reader = new FileReader();
  34. reader.readAsText(blob, "utf8");
  35. reader.onloadend = () => {
  36. if (reader.readyState === FileReader.DONE) {
  37. resolve(reader.result as string);
  38. }
  39. };
  40. });
  41. }
  42. const { elements, appState } = updateAppState(contents);
  43. return restore(elements, appState, { scrollToContent: true });
  44. };