LocalData.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 {
  13. createStore,
  14. entries,
  15. del,
  16. getMany,
  17. set,
  18. setMany,
  19. get,
  20. } from "idb-keyval";
  21. import { clearAppStateForLocalStorage } from "../../packages/excalidraw/appState";
  22. import type { LibraryPersistedData } from "../../packages/excalidraw/data/library";
  23. import type { ImportedDataState } from "../../packages/excalidraw/data/types";
  24. import { clearElementsForLocalStorage } from "../../packages/excalidraw/element";
  25. import type {
  26. ExcalidrawElement,
  27. FileId,
  28. } from "../../packages/excalidraw/element/types";
  29. import type {
  30. AppState,
  31. BinaryFileData,
  32. BinaryFiles,
  33. } from "../../packages/excalidraw/types";
  34. import type { MaybePromise } from "../../packages/excalidraw/utility-types";
  35. import { debounce } from "../../packages/excalidraw/utils";
  36. import { SAVE_TO_LOCAL_STORAGE_TIMEOUT, STORAGE_KEYS } from "../app_constants";
  37. import { FileManager } from "./FileManager";
  38. import { Locker } from "./Locker";
  39. import { updateBrowserStateVersion } from "./tabSync";
  40. const filesStore = createStore("files-db", "files-store");
  41. class LocalFileManager extends FileManager {
  42. clearObsoleteFiles = async (opts: { currentFileIds: FileId[] }) => {
  43. await entries(filesStore).then((entries) => {
  44. for (const [id, imageData] of entries as [FileId, BinaryFileData][]) {
  45. // if image is unused (not on canvas) & is older than 1 day, delete it
  46. // from storage. We check `lastRetrieved` we care about the last time
  47. // the image was used (loaded on canvas), not when it was initially
  48. // created.
  49. if (
  50. (!imageData.lastRetrieved ||
  51. Date.now() - imageData.lastRetrieved > 24 * 3600 * 1000) &&
  52. !opts.currentFileIds.includes(id as FileId)
  53. ) {
  54. del(id, filesStore);
  55. }
  56. }
  57. });
  58. };
  59. }
  60. const saveDataStateToLocalStorage = (
  61. elements: readonly ExcalidrawElement[],
  62. appState: AppState,
  63. ) => {
  64. try {
  65. localStorage.setItem(
  66. STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS,
  67. JSON.stringify(clearElementsForLocalStorage(elements)),
  68. );
  69. localStorage.setItem(
  70. STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
  71. JSON.stringify(clearAppStateForLocalStorage(appState)),
  72. );
  73. updateBrowserStateVersion(STORAGE_KEYS.VERSION_DATA_STATE);
  74. } catch (error: any) {
  75. // Unable to access window.localStorage
  76. console.error(error);
  77. }
  78. };
  79. type SavingLockTypes = "collaboration";
  80. export class LocalData {
  81. private static _save = debounce(
  82. async (
  83. elements: readonly ExcalidrawElement[],
  84. appState: AppState,
  85. files: BinaryFiles,
  86. onFilesSaved: () => void,
  87. ) => {
  88. saveDataStateToLocalStorage(elements, appState);
  89. await this.fileStorage.saveFiles({
  90. elements,
  91. files,
  92. });
  93. onFilesSaved();
  94. },
  95. SAVE_TO_LOCAL_STORAGE_TIMEOUT,
  96. );
  97. /** Saves DataState, including files. Bails if saving is paused */
  98. static save = (
  99. elements: readonly ExcalidrawElement[],
  100. appState: AppState,
  101. files: BinaryFiles,
  102. onFilesSaved: () => void,
  103. ) => {
  104. // we need to make the `isSavePaused` check synchronously (undebounced)
  105. if (!this.isSavePaused()) {
  106. this._save(elements, appState, files, onFilesSaved);
  107. }
  108. };
  109. static flushSave = () => {
  110. this._save.flush();
  111. };
  112. private static locker = new Locker<SavingLockTypes>();
  113. static pauseSave = (lockType: SavingLockTypes) => {
  114. this.locker.lock(lockType);
  115. };
  116. static resumeSave = (lockType: SavingLockTypes) => {
  117. this.locker.unlock(lockType);
  118. };
  119. static isSavePaused = () => {
  120. return document.hidden || this.locker.isLocked();
  121. };
  122. // ---------------------------------------------------------------------------
  123. static fileStorage = new LocalFileManager({
  124. getFiles(ids) {
  125. return getMany(ids, filesStore).then(
  126. async (filesData: (BinaryFileData | undefined)[]) => {
  127. const loadedFiles: BinaryFileData[] = [];
  128. const erroredFiles = new Map<FileId, true>();
  129. const filesToSave: [FileId, BinaryFileData][] = [];
  130. filesData.forEach((data, index) => {
  131. const id = ids[index];
  132. if (data) {
  133. const _data: BinaryFileData = {
  134. ...data,
  135. lastRetrieved: Date.now(),
  136. };
  137. filesToSave.push([id, _data]);
  138. loadedFiles.push(_data);
  139. } else {
  140. erroredFiles.set(id, true);
  141. }
  142. });
  143. try {
  144. // save loaded files back to storage with updated `lastRetrieved`
  145. setMany(filesToSave, filesStore);
  146. } catch (error) {
  147. console.warn(error);
  148. }
  149. return { loadedFiles, erroredFiles };
  150. },
  151. );
  152. },
  153. async saveFiles({ addedFiles }) {
  154. const savedFiles = new Map<FileId, true>();
  155. const erroredFiles = new Map<FileId, true>();
  156. // before we use `storage` event synchronization, let's update the flag
  157. // optimistically. Hopefully nothing fails, and an IDB read executed
  158. // before an IDB write finishes will read the latest value.
  159. updateBrowserStateVersion(STORAGE_KEYS.VERSION_FILES);
  160. await Promise.all(
  161. [...addedFiles].map(async ([id, fileData]) => {
  162. try {
  163. await set(id, fileData, filesStore);
  164. savedFiles.set(id, true);
  165. } catch (error: any) {
  166. console.error(error);
  167. erroredFiles.set(id, true);
  168. }
  169. }),
  170. );
  171. return { savedFiles, erroredFiles };
  172. },
  173. });
  174. }
  175. export class LibraryIndexedDBAdapter {
  176. /** IndexedDB database and store name */
  177. private static idb_name = STORAGE_KEYS.IDB_LIBRARY;
  178. /** library data store key */
  179. private static key = "libraryData";
  180. private static store = createStore(
  181. `${LibraryIndexedDBAdapter.idb_name}-db`,
  182. `${LibraryIndexedDBAdapter.idb_name}-store`,
  183. );
  184. static async load() {
  185. const IDBData = await get<LibraryPersistedData>(
  186. LibraryIndexedDBAdapter.key,
  187. LibraryIndexedDBAdapter.store,
  188. );
  189. return IDBData || null;
  190. }
  191. static save(data: LibraryPersistedData): MaybePromise<void> {
  192. return set(
  193. LibraryIndexedDBAdapter.key,
  194. data,
  195. LibraryIndexedDBAdapter.store,
  196. );
  197. }
  198. }
  199. /** LS Adapter used only for migrating LS library data
  200. * to indexedDB */
  201. export class LibraryLocalStorageMigrationAdapter {
  202. static load() {
  203. const LSData = localStorage.getItem(
  204. STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY,
  205. );
  206. if (LSData != null) {
  207. const libraryItems: ImportedDataState["libraryItems"] =
  208. JSON.parse(LSData);
  209. if (libraryItems) {
  210. return { libraryItems };
  211. }
  212. }
  213. return null;
  214. }
  215. static clear() {
  216. localStorage.removeItem(STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY);
  217. }
  218. }