Add settings helpers

This commit is contained in:
Andras Schmelczer 2023-05-27 10:38:35 +01:00
commit bdc407b7df
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
2 changed files with 151 additions and 0 deletions

45
src/utils/persist.ts Normal file
View file

@ -0,0 +1,45 @@
export const persist = <T extends Record<string, number>>(wrapee: T): T => {
const initialState = { ...wrapee };
const keys = Object.keys(wrapee);
const keysToShortKeys = Object.fromEntries(
keys.map((key, i) => [key, String.fromCharCode(65 + i)])
);
const params = new URLSearchParams(window.location.search);
const newParams = new URLSearchParams();
keys.forEach((key) => {
if (params.has(keysToShortKeys[key])) {
(wrapee as any)[key] = Number(params.get(keysToShortKeys[key]));
newParams.set(keysToShortKeys[key], params.get(keysToShortKeys[key])!);
}
});
window.history.replaceState(
{},
'',
`${window.location.pathname}?${newParams.toString()}`
);
return new Proxy(wrapee, {
set: (target, key: string, value: number) => {
const params = new URLSearchParams(window.location.search);
if (initialState[key] === value) {
params.delete(keysToShortKeys[key]);
} else {
params.set(keysToShortKeys[key], value.toString());
}
(target as any)[key] = value;
window.history.replaceState(
{},
'',
`${window.location.pathname}?${params.toString()}`
);
return true;
},
});
};