2021-08-26 18:52:04 +02:00
|
|
|
import { writable, get, derived } from "svelte/store"
|
2021-09-27 13:59:49 +02:00
|
|
|
import { localStorageStore } from "builder/src/builderStore/store/localStorage"
|
2021-08-26 18:52:04 +02:00
|
|
|
import { appStore } from "./app"
|
2021-08-26 12:28:44 +02:00
|
|
|
|
|
|
|
const createStateStore = () => {
|
2021-08-26 18:52:04 +02:00
|
|
|
const localStorageKey = `${get(appStore).appId}.state`
|
|
|
|
const persistentStore = localStorageStore(localStorageKey, {})
|
2021-08-26 12:28:44 +02:00
|
|
|
|
2021-08-26 18:52:04 +02:00
|
|
|
// Initialise the temp store to mirror the persistent store
|
|
|
|
const tempStore = writable(get(persistentStore))
|
|
|
|
|
|
|
|
// Sets a value to state, optionally persistent
|
|
|
|
const setValue = (key, value, persist = false) => {
|
|
|
|
const storeToSave = persist ? persistentStore : tempStore
|
|
|
|
const storeToClear = persist ? tempStore : persistentStore
|
|
|
|
storeToSave.update(state => {
|
2021-08-26 12:28:44 +02:00
|
|
|
state[key] = value
|
|
|
|
return state
|
|
|
|
})
|
2021-08-26 18:52:04 +02:00
|
|
|
storeToClear.update(state => {
|
2021-08-26 12:28:44 +02:00
|
|
|
delete state[key]
|
|
|
|
return state
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-26 18:52:04 +02:00
|
|
|
// Delete a certain key from both stores
|
|
|
|
const deleteValue = key => {
|
|
|
|
const stores = [tempStore, persistentStore]
|
|
|
|
stores.forEach(store => {
|
|
|
|
store.update(state => {
|
|
|
|
delete state[key]
|
|
|
|
return state
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-12-15 09:55:22 +01:00
|
|
|
// Initialises the temporary state store with a certain value
|
|
|
|
const initialise = tempStore.set
|
|
|
|
|
2021-08-26 18:52:04 +02:00
|
|
|
// Derive the combination of both persisted and non persisted stores
|
|
|
|
const store = derived(
|
|
|
|
[tempStore, persistentStore],
|
|
|
|
([$tempStore, $persistentStore]) => {
|
|
|
|
return {
|
|
|
|
...$tempStore,
|
|
|
|
...$persistentStore,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-08-26 12:28:44 +02:00
|
|
|
return {
|
|
|
|
subscribe: store.subscribe,
|
2021-12-15 09:55:22 +01:00
|
|
|
actions: { setValue, deleteValue, initialise },
|
2021-08-26 12:28:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const stateStore = createStateStore()
|