localStorage.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { ExcalidrawElement } from "../element/types";
  2. import { AppState } from "../types";
  3. import { clearAppStateForLocalStorage } from "../appState";
  4. import { restore } from "./restore";
  5. const LOCAL_STORAGE_KEY = "excalidraw";
  6. const LOCAL_STORAGE_KEY_STATE = "excalidraw-state";
  7. export function saveToLocalStorage(
  8. elements: readonly ExcalidrawElement[],
  9. appState: AppState,
  10. ) {
  11. localStorage.setItem(
  12. LOCAL_STORAGE_KEY,
  13. JSON.stringify(elements.filter((element) => !element.isDeleted)),
  14. );
  15. localStorage.setItem(
  16. LOCAL_STORAGE_KEY_STATE,
  17. JSON.stringify(clearAppStateForLocalStorage(appState)),
  18. );
  19. }
  20. export function restoreFromLocalStorage() {
  21. const savedElements = localStorage.getItem(LOCAL_STORAGE_KEY);
  22. const savedState = localStorage.getItem(LOCAL_STORAGE_KEY_STATE);
  23. let elements = [];
  24. if (savedElements) {
  25. try {
  26. elements = JSON.parse(savedElements);
  27. } catch {
  28. // Do nothing because elements array is already empty
  29. }
  30. }
  31. let appState = null;
  32. if (savedState) {
  33. try {
  34. appState = JSON.parse(savedState) as AppState;
  35. // If we're retrieving from local storage, we should not be collaborating
  36. appState.isCollaborating = false;
  37. appState.collaborators = new Map();
  38. } catch {
  39. // Do nothing because appState is already null
  40. }
  41. }
  42. return restore(elements, appState);
  43. }