mirror of
https://github.com/wukko/cobalt.git
synced 2024-11-15 12:50:01 +00:00
settings: only store settings if changed by user
This commit is contained in:
parent
a6ddceb643
commit
95bcf7bf66
1 changed files with 18 additions and 13 deletions
|
@ -4,9 +4,11 @@ import { merge } from 'ts-deepmerge';
|
||||||
import type { RecursivePartial } from './types/generic';
|
import type { RecursivePartial } from './types/generic';
|
||||||
import type { CobaltSettings } from './types/settings';
|
import type { CobaltSettings } from './types/settings';
|
||||||
|
|
||||||
import defaultSettings from "$lib/settings/defaults";
|
import defaultSettings from './settings/defaults';
|
||||||
|
|
||||||
const writeToStorage = (settings: CobaltSettings) => {
|
type PartialSettings = RecursivePartial<CobaltSettings>;
|
||||||
|
|
||||||
|
const writeToStorage = (settings: PartialSettings) => {
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
"settings",
|
"settings",
|
||||||
JSON.stringify(settings)
|
JSON.stringify(settings)
|
||||||
|
@ -18,28 +20,31 @@ const writeToStorage = (settings: CobaltSettings) => {
|
||||||
const loadFromStorage = () => {
|
const loadFromStorage = () => {
|
||||||
const settings = localStorage.getItem('settings');
|
const settings = localStorage.getItem('settings');
|
||||||
if (!settings) {
|
if (!settings) {
|
||||||
return defaultSettings;
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return JSON.parse(settings) as PartialSettings;
|
||||||
...defaultSettings,
|
|
||||||
...JSON.parse(settings) as CobaltSettings
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let update: (_: Updater<CobaltSettings>) => void;
|
let update: (_: Updater<CobaltSettings>) => void;
|
||||||
|
|
||||||
|
// deep merge partial type into full CobaltSettings type
|
||||||
|
const mergeWithDefaults = (partial: PartialSettings) => {
|
||||||
|
return merge(defaultSettings, partial) as CobaltSettings;
|
||||||
|
}
|
||||||
|
|
||||||
export default readable<CobaltSettings>(
|
export default readable<CobaltSettings>(
|
||||||
loadFromStorage(),
|
mergeWithDefaults(loadFromStorage()),
|
||||||
(_, _update) => { update = _update }
|
(_, _update) => { update = _update }
|
||||||
);
|
);
|
||||||
|
|
||||||
// update settings from outside
|
// update settings from outside
|
||||||
export function updateSetting(settings: RecursivePartial<CobaltSettings>) {
|
export function updateSetting(partial: PartialSettings) {
|
||||||
update((current) => {
|
update(() => {
|
||||||
// deep merge partial type into full CobaltSettings type
|
const updated = writeToStorage(
|
||||||
current = merge(current, settings) as CobaltSettings;
|
merge(loadFromStorage(), partial)
|
||||||
|
);
|
||||||
|
|
||||||
return writeToStorage(current);
|
return mergeWithDefaults(updated);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue