Add settings helpers
This commit is contained in:
parent
2f1a0d0b0d
commit
bdc407b7df
2 changed files with 151 additions and 0 deletions
45
src/utils/persist.ts
Normal file
45
src/utils/persist.ts
Normal 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;
|
||||
},
|
||||
});
|
||||
};
|
||||
Loading…
Reference in a new issue