LocalData.ts 7.2 KB

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