2023-06-19 18:24:40 +02:00
|
|
|
import { writable, get, derived } from "svelte/store"
|
2023-06-19 10:54:24 +02:00
|
|
|
|
|
|
|
// A simple svelte store which deeply compares all changes and ensures that
|
|
|
|
// subscribed children will only fire when a new value is actually set
|
|
|
|
export const memo = initialValue => {
|
|
|
|
const store = writable(initialValue)
|
2024-08-20 16:29:39 +02:00
|
|
|
let currentJSON = JSON.stringify(initialValue)
|
2023-06-19 10:54:24 +02:00
|
|
|
|
2024-08-12 10:55:12 +02:00
|
|
|
const tryUpdateValue = newValue => {
|
|
|
|
const newJSON = JSON.stringify(newValue)
|
|
|
|
if (newJSON !== currentJSON) {
|
2023-06-19 10:54:24 +02:00
|
|
|
store.set(newValue)
|
2024-08-12 10:55:12 +02:00
|
|
|
currentJSON = newJSON
|
2023-06-19 10:54:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
subscribe: store.subscribe,
|
2024-08-12 10:55:12 +02:00
|
|
|
set: tryUpdateValue,
|
2023-06-19 10:54:24 +02:00
|
|
|
update: updateFn => {
|
2024-08-12 10:55:12 +02:00
|
|
|
let mutableCurrentValue = JSON.parse(currentJSON)
|
2023-06-19 10:54:24 +02:00
|
|
|
const newValue = updateFn(mutableCurrentValue)
|
2024-08-12 10:55:12 +02:00
|
|
|
tryUpdateValue(newValue)
|
2023-06-19 10:54:24 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2023-06-19 18:24:40 +02:00
|
|
|
|
|
|
|
// Enriched version of svelte's derived store which returns a memo
|
|
|
|
export const derivedMemo = (store, derivation) => {
|
|
|
|
const derivedStore = derived(store, derivation)
|
|
|
|
const memoStore = memo(get(derivedStore))
|
|
|
|
derivedStore.subscribe(memoStore.set)
|
|
|
|
return memoStore
|
|
|
|
}
|