excalidraw/src/data/localStorage.ts

90 lines
2.3 KiB
TypeScript
Raw Normal View History

import { ExcalidrawElement } from "../element/types";
2020-10-30 21:01:41 +01:00
import { AppState } from "../types";
import { clearAppStateForLocalStorage, getDefaultAppState } from "../appState";
2020-10-30 21:01:41 +01:00
import { STORAGE_KEYS } from "../constants";
import { clearElementsForLocalStorage } from "../element";
export const saveUsernameToLocalStorage = (username: string) => {
try {
localStorage.setItem(
2020-10-30 21:01:41 +01:00
STORAGE_KEYS.LOCAL_STORAGE_COLLAB,
JSON.stringify({ username }),
);
} catch (error) {
// Unable to access window.localStorage
console.error(error);
}
};
export const importUsernameFromLocalStorage = (): string | null => {
try {
2020-10-30 21:01:41 +01:00
const data = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_COLLAB);
if (data) {
return JSON.parse(data).username;
}
} catch (error) {
// Unable to access localStorage
console.error(error);
}
return null;
};
export const saveToLocalStorage = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
try {
localStorage.setItem(
2020-10-30 21:01:41 +01:00
STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS,
JSON.stringify(clearElementsForLocalStorage(elements)),
);
localStorage.setItem(
2020-10-30 21:01:41 +01:00
STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
JSON.stringify(clearAppStateForLocalStorage(appState)),
);
} catch (error) {
// Unable to access window.localStorage
console.error(error);
}
};
export const importFromLocalStorage = () => {
let savedElements = null;
let savedState = null;
try {
2020-10-30 21:01:41 +01:00
savedElements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS);
savedState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE);
} catch (error) {
// Unable to access localStorage
console.error(error);
}
let elements: ExcalidrawElement[] = [];
if (savedElements) {
try {
elements = clearElementsForLocalStorage(JSON.parse(savedElements));
} catch (error) {
console.error(error);
// Do nothing because elements array is already empty
}
}
let appState = null;
if (savedState) {
try {
appState = {
...getDefaultAppState(),
...clearAppStateForLocalStorage(
JSON.parse(savedState) as Partial<AppState>,
),
};
} catch (error) {
console.error(error);
// Do nothing because appState is already null
}
}
return { elements, appState };
};