mirror of
https://github.com/excalidraw/excalidraw.git
synced 2025-05-03 10:00:07 -04:00
Fix library dnd (#2314)
This commit is contained in:
parent
8a50916ef2
commit
ba3f548b91
16 changed files with 261 additions and 168 deletions
|
@ -1,8 +1,16 @@
|
|||
import { loadLibraryFromBlob } from "./blob";
|
||||
import { LibraryItems, LibraryItem } from "../types";
|
||||
import { loadLibrary, saveLibrary } from "./localStorage";
|
||||
import { restoreElements } from "./restore";
|
||||
import { STORAGE_KEYS } from "../constants";
|
||||
|
||||
export class Library {
|
||||
private static libraryCache: LibraryItems | null = null;
|
||||
|
||||
static resetLibrary = () => {
|
||||
Library.libraryCache = null;
|
||||
localStorage.removeItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY);
|
||||
};
|
||||
|
||||
/** imports library (currently merges, removing duplicates) */
|
||||
static async importLibrary(blob: Blob) {
|
||||
const libraryFile = await loadLibraryFromBlob(blob);
|
||||
|
@ -34,10 +42,51 @@ export class Library {
|
|||
});
|
||||
};
|
||||
|
||||
const existingLibraryItems = await loadLibrary();
|
||||
const existingLibraryItems = await Library.loadLibrary();
|
||||
const filtered = libraryFile.library!.filter((libraryItem) =>
|
||||
isUniqueitem(existingLibraryItems, libraryItem),
|
||||
);
|
||||
saveLibrary([...existingLibraryItems, ...filtered]);
|
||||
Library.saveLibrary([...existingLibraryItems, ...filtered]);
|
||||
}
|
||||
|
||||
static loadLibrary = (): Promise<LibraryItems> => {
|
||||
return new Promise(async (resolve) => {
|
||||
if (Library.libraryCache) {
|
||||
return resolve(JSON.parse(JSON.stringify(Library.libraryCache)));
|
||||
}
|
||||
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY);
|
||||
if (!data) {
|
||||
return resolve([]);
|
||||
}
|
||||
|
||||
const items = (JSON.parse(data) as LibraryItems).map((elements) =>
|
||||
restoreElements(elements),
|
||||
) as Mutable<LibraryItems>;
|
||||
|
||||
// clone to ensure we don't mutate the cached library elements in the app
|
||||
Library.libraryCache = JSON.parse(JSON.stringify(items));
|
||||
|
||||
resolve(items);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
static saveLibrary = (items: LibraryItems) => {
|
||||
const prevLibraryItems = Library.libraryCache;
|
||||
try {
|
||||
const serializedItems = JSON.stringify(items);
|
||||
// cache optimistically so that consumers have access to the latest
|
||||
// immediately
|
||||
Library.libraryCache = JSON.parse(serializedItems);
|
||||
localStorage.setItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY, serializedItems);
|
||||
} catch (e) {
|
||||
Library.libraryCache = prevLibraryItems;
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue