LocalData.ts 5.5 KB

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