localStorage.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. const LOCAL_STORAGE_KEY_COLLAB = "excalidraw-collab";
  8. export const saveUsernameToLocalStorage = (username: string) => {
  9. try {
  10. localStorage.setItem(
  11. LOCAL_STORAGE_KEY_COLLAB,
  12. JSON.stringify({ username }),
  13. );
  14. } catch (error) {
  15. // Unable to access window.localStorage
  16. console.error(error);
  17. }
  18. };
  19. export const restoreUsernameFromLocalStorage = (): string | null => {
  20. try {
  21. const data = localStorage.getItem(LOCAL_STORAGE_KEY_COLLAB);
  22. if (data) {
  23. return JSON.parse(data).username;
  24. }
  25. } catch (error) {
  26. // Unable to access localStorage
  27. console.error(error);
  28. }
  29. return null;
  30. };
  31. export const saveToLocalStorage = (
  32. elements: readonly ExcalidrawElement[],
  33. appState: AppState,
  34. ) => {
  35. try {
  36. localStorage.setItem(
  37. LOCAL_STORAGE_KEY,
  38. JSON.stringify(elements.filter((element) => !element.isDeleted)),
  39. );
  40. localStorage.setItem(
  41. LOCAL_STORAGE_KEY_STATE,
  42. JSON.stringify(clearAppStateForLocalStorage(appState)),
  43. );
  44. } catch (error) {
  45. // Unable to access window.localStorage
  46. console.error(error);
  47. }
  48. };
  49. export const restoreFromLocalStorage = () => {
  50. let savedElements = null;
  51. let savedState = null;
  52. try {
  53. savedElements = localStorage.getItem(LOCAL_STORAGE_KEY);
  54. savedState = localStorage.getItem(LOCAL_STORAGE_KEY_STATE);
  55. } catch (error) {
  56. // Unable to access localStorage
  57. console.error(error);
  58. }
  59. let elements = [];
  60. if (savedElements) {
  61. try {
  62. elements = JSON.parse(savedElements);
  63. } catch {
  64. // Do nothing because elements array is already empty
  65. }
  66. }
  67. let appState = null;
  68. if (savedState) {
  69. try {
  70. appState = JSON.parse(savedState) as AppState;
  71. // If we're retrieving from local storage, we should not be collaborating
  72. appState.isCollaborating = false;
  73. appState.collaborators = new Map();
  74. } catch {
  75. // Do nothing because appState is already null
  76. }
  77. }
  78. return restore(elements, appState);
  79. };