um-react/src/features/settings/persistSettings.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-06-03 13:09:11 +00:00
import { debounce } from 'radash';
import { produce } from 'immer';
import type { AppStore } from '~/store';
import { settingsSlice, setProductionChanges, ProductionSettings } from './settingsSlice';
2023-06-03 13:09:11 +00:00
import { enumObject } from '~/util/objects';
import { getLogger } from '~/util/logUtils';
2023-06-17 13:29:50 +00:00
import { parseKwm2ProductionKey } from './keyFormats';
2023-06-03 13:09:11 +00:00
const DEFAULT_STORAGE_KEY = 'um-react-settings';
function mergeSettings(settings: ProductionSettings): ProductionSettings {
return produce(settingsSlice.getInitialState().production, (draft) => {
if (settings?.qmc2) {
const { allowFuzzyNameSearch, keys } = settings.qmc2;
for (const [k, v] of enumObject(keys)) {
if (typeof v === 'string') {
draft.qmc2.keys[k] = v;
}
}
if (typeof allowFuzzyNameSearch === 'boolean') {
draft.qmc2.allowFuzzyNameSearch = allowFuzzyNameSearch;
2023-06-03 13:09:11 +00:00
}
}
2023-06-17 13:29:50 +00:00
if (settings?.kwm2) {
const { keys } = settings.kwm2;
for (const [k, v] of enumObject(keys)) {
if (typeof v === 'string' && parseKwm2ProductionKey(k)) {
draft.kwm2.keys[k] = v;
}
}
}
2023-06-03 13:09:11 +00:00
});
}
export function persistSettings(store: AppStore, storageKey = DEFAULT_STORAGE_KEY) {
let lastSettings: unknown;
try {
const loadedSettings: ProductionSettings = JSON.parse(localStorage.getItem(storageKey) ?? '');
2023-06-03 13:09:11 +00:00
if (loadedSettings) {
const mergedSettings = mergeSettings(loadedSettings);
store.dispatch(setProductionChanges(mergedSettings));
2023-06-03 13:09:11 +00:00
getLogger().debug('settings loaded');
}
} catch {
// load failed, ignore.
}
return store.subscribe(
debounce({ delay: 150 }, () => {
const currentSettings = store.getState().settings.production;
2023-06-03 13:09:11 +00:00
if (lastSettings !== currentSettings) {
lastSettings = currentSettings;
localStorage.setItem(storageKey, JSON.stringify(currentSettings));
getLogger().debug('settings saved');
}
})
);
}