MapComplete/src/Logic/Web/LocalStorageSource.ts

62 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-09-08 21:40:48 +02:00
import { UIEventSource } from "../UIEventSource"
2024-10-17 04:13:27 +02:00
import { Utils } from "../../Utils"
2021-03-29 14:10:20 +02:00
/**
* UIEventsource-wrapper around localStorage
*/
export class LocalStorageSource {
private static readonly _cache: Record<string, UIEventSource<string>> = {}
static getParsed<T>(key: string, defaultValue: T): UIEventSource<T> {
return LocalStorageSource.get(key).sync(
2022-09-08 21:40:48 +02:00
(str) => {
if (str === undefined) {
return defaultValue
}
try {
return JSON.parse(str)
} catch {
return defaultValue
}
2022-09-08 21:40:48 +02:00
},
[],
2024-10-19 14:44:55 +02:00
(value) => JSON.stringify(value)
)
}
static get(key: string, defaultValue: string = undefined): UIEventSource<string> {
const cached = LocalStorageSource._cache[key]
if (cached) {
return cached
}
let saved = defaultValue
if (!Utils.runningFromConsole) {
try {
saved = localStorage.getItem(key)
if (saved === "undefined") {
saved = undefined
}
} catch (e) {
console.error("Could not get value", key, "from local storage")
2023-12-26 22:30:27 +01:00
}
2020-07-31 17:11:44 +02:00
}
const source = new UIEventSource<string>(saved ?? defaultValue, "localstorage:" + key)
source.addCallback((data) => {
if (data === undefined || data === "" || data === null) {
localStorage.removeItem(key)
return
}
try {
localStorage.setItem(key, data)
} catch (e) {
// Probably exceeded the quota with this item!
// Let's nuke everything
localStorage.clear()
}
})
LocalStorageSource._cache[key] = source
return source
}
2020-07-31 17:11:44 +02:00
}