@speckle/shared
Version:
Shared code between various Speckle JS packages
68 lines • 1.92 kB
JavaScript
function checkLocalStorageAvailability() {
try {
const testKey = '___localStorageAvailabilityTest';
const storage = globalThis.localStorage;
storage.setItem(testKey, testKey);
storage.getItem(testKey);
storage.removeItem(testKey);
return true;
}
catch {
return false;
}
}
/**
* In memory implementation of the Storage interface, for use when LocalStorage
* isn't available
*/
class FakeStorage {
#internalStorage = new Map();
clear() {
this.#internalStorage.clear();
}
getItem(key) {
return this.#internalStorage.get(key) || null;
}
key(index) {
return [...this.#internalStorage.keys()][index] || null;
}
removeItem(key) {
this.#internalStorage.delete(key);
}
setItem(key, value) {
this.#internalStorage.set(key, value);
}
get length() {
return this.#internalStorage.size;
}
}
/**
* Whether or not the local storage is available in this session
*/
const isLocalStorageAvailable = checkLocalStorageAvailability();
/**
* Localstorage (real or faked) to use in this session
*/
const internalStorage = isLocalStorageAvailable
? globalThis.localStorage
: new FakeStorage();
/**
* Utility for nicer reads/writes from/to LocalStorage without having to worry about the browser
* throwing a hissy fit because the page is opened in Incognito mode or node not having localStorage at all
*/
export const SafeLocalStorage = {
get(key) {
return internalStorage.getItem(key);
},
set(key, value) {
internalStorage.setItem(key, value);
},
remove(key) {
internalStorage.removeItem(key);
},
/**
* Flag for telling if we're using a real localStorage or faking it with a basic in-memory collection
*/
isRealLocalStorage: isLocalStorageAvailable
};
//# sourceMappingURL=localStorage.js.map