LocalData.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /**
  2. * This file deals with saving data state (appState, elements, images, ...)
  3. * locally to the browser.
  4. *
  5. * Notes:
  6. *
  7. * - DataState refers to full state of the app: appState, elements, images,
  8. * though some state is saved separately (collab username, library) for one
  9. * reason or another. We also save different data to different storage
  10. * (localStorage, indexedDB).
  11. */
  12. import { createStore, entries, del, getMany, set, setMany } from "idb-keyval";
  13. import { clearAppStateForLocalStorage } from "../../src/appState";
  14. import { clearElementsForLocalStorage } from "../../src/element";
  15. import { ExcalidrawElement, FileId } from "../../src/element/types";
  16. import { AppState, BinaryFileData, BinaryFiles } from "../../src/types";
  17. import { debounce } from "../../src/utils";
  18. import { SAVE_TO_LOCAL_STORAGE_TIMEOUT, STORAGE_KEYS } from "../app_constants";
  19. import { FileManager } from "./FileManager";
  20. import { Locker } from "./Locker";
  21. import { updateBrowserStateVersion } from "./tabSync";
  22. const filesStore = createStore("files-db", "files-store");
  23. class LocalFileManager extends FileManager {
  24. clearObsoleteFiles = async (opts: { currentFileIds: FileId[] }) => {
  25. await entries(filesStore).then((entries) => {
  26. for (const [id, imageData] of entries as [FileId, BinaryFileData][]) {
  27. // if image is unused (not on canvas) & is older than 1 day, delete it
  28. // from storage. We check `lastRetrieved` we care about the last time
  29. // the image was used (loaded on canvas), not when it was initially
  30. // created.
  31. if (
  32. (!imageData.lastRetrieved ||
  33. Date.now() - imageData.lastRetrieved > 24 * 3600 * 1000) &&
  34. !opts.currentFileIds.includes(id as FileId)
  35. ) {
  36. del(id, filesStore);
  37. }
  38. }
  39. });
  40. };
  41. }
  42. const saveDataStateToLocalStorage = (
  43. elements: readonly ExcalidrawElement[],
  44. appState: AppState,
  45. ) => {
  46. try {
  47. localStorage.setItem(
  48. STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS,
  49. JSON.stringify(clearElementsForLocalStorage(elements)),
  50. );
  51. localStorage.setItem(
  52. STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
  53. JSON.stringify(clearAppStateForLocalStorage(appState)),
  54. );
  55. updateBrowserStateVersion(STORAGE_KEYS.VERSION_DATA_STATE);
  56. } catch (error: any) {
  57. // Unable to access window.localStorage
  58. console.error(error);
  59. }
  60. };
  61. type SavingLockTypes = "collaboration";
  62. export class LocalData {
  63. private static _save = debounce(
  64. async (
  65. elements: readonly ExcalidrawElement[],
  66. appState: AppState,
  67. files: BinaryFiles,
  68. onFilesSaved: () => void,
  69. ) => {
  70. saveDataStateToLocalStorage(elements, appState);
  71. await this.fileStorage.saveFiles({
  72. elements,
  73. files,
  74. });
  75. onFilesSaved();
  76. },
  77. SAVE_TO_LOCAL_STORAGE_TIMEOUT,
  78. );
  79. /** Saves DataState, including files. Bails if saving is paused */
  80. static save = (
  81. elements: readonly ExcalidrawElement[],
  82. appState: AppState,
  83. files: BinaryFiles,
  84. onFilesSaved: () => void,
  85. ) => {
  86. // we need to make the `isSavePaused` check synchronously (undebounced)
  87. if (!this.isSavePaused()) {
  88. this._save(elements, appState, files, onFilesSaved);
  89. }
  90. };
  91. static flushSave = () => {
  92. this._save.flush();
  93. };
  94. private static locker = new Locker<SavingLockTypes>();
  95. static pauseSave = (lockType: SavingLockTypes) => {
  96. this.locker.lock(lockType);
  97. };
  98. static resumeSave = (lockType: SavingLockTypes) => {
  99. this.locker.unlock(lockType);
  100. };
  101. static isSavePaused = () => {
  102. return document.hidden || this.locker.isLocked();
  103. };
  104. // ---------------------------------------------------------------------------
  105. static fileStorage = new LocalFileManager({
  106. getFiles(ids) {
  107. return getMany(ids, filesStore).then(
  108. async (filesData: (BinaryFileData | undefined)[]) => {
  109. const loadedFiles: BinaryFileData[] = [];
  110. const erroredFiles = new Map<FileId, true>();
  111. const filesToSave: [FileId, BinaryFileData][] = [];
  112. filesData.forEach((data, index) => {
  113. const id = ids[index];
  114. if (data) {
  115. const _data: BinaryFileData = {
  116. ...data,
  117. lastRetrieved: Date.now(),
  118. };
  119. filesToSave.push([id, _data]);
  120. loadedFiles.push(_data);
  121. } else {
  122. erroredFiles.set(id, true);
  123. }
  124. });
  125. try {
  126. // save loaded files back to storage with updated `lastRetrieved`
  127. setMany(filesToSave, filesStore);
  128. } catch (error) {
  129. console.warn(error);
  130. }
  131. return { loadedFiles, erroredFiles };
  132. },
  133. );
  134. },
  135. async saveFiles({ addedFiles }) {
  136. const savedFiles = new Map<FileId, true>();
  137. const erroredFiles = new Map<FileId, true>();
  138. // before we use `storage` event synchronization, let's update the flag
  139. // optimistically. Hopefully nothing fails, and an IDB read executed
  140. // before an IDB write finishes will read the latest value.
  141. updateBrowserStateVersion(STORAGE_KEYS.VERSION_FILES);
  142. await Promise.all(
  143. [...addedFiles].map(async ([id, fileData]) => {
  144. try {
  145. await set(id, fileData, filesStore);
  146. savedFiles.set(id, true);
  147. } catch (error: any) {
  148. console.error(error);
  149. erroredFiles.set(id, true);
  150. }
  151. }),
  152. );
  153. return { savedFiles, erroredFiles };
  154. },
  155. });
  156. }