2020-11-24 17:48:14 +01:00
|
|
|
const havePrefs = typeof window.localStorage !== 'undefined';
|
2019-03-31 20:52:45 -07:00
|
|
|
|
2020-11-24 17:48:14 +01:00
|
|
|
export default class Prefs {
|
2022-05-10 06:52:06 -07:00
|
|
|
url: URL;
|
|
|
|
title: string;
|
2021-12-25 07:24:59 -08:00
|
|
|
|
|
|
|
constructor() {
|
2022-05-10 06:52:06 -07:00
|
|
|
this.url = new URL(window.location.href);
|
|
|
|
this.title = window.document.title;
|
2021-12-25 07:24:59 -08:00
|
|
|
}
|
2020-11-24 17:48:14 +01:00
|
|
|
|
|
|
|
havePrefs() {
|
|
|
|
return havePrefs;
|
|
|
|
}
|
2021-02-21 18:38:21 -08:00
|
|
|
|
2022-05-10 06:52:06 -07:00
|
|
|
readPref(name: string): string | null;
|
|
|
|
readPref(name: string, defaultValue: string): string;
|
2021-02-21 18:38:21 -08:00
|
|
|
readPref(name: string, defaultValue: string | null = null) {
|
2022-05-10 06:52:06 -07:00
|
|
|
if (this.url.searchParams.has(name)) {
|
|
|
|
return this.url.searchParams.get(name);
|
2021-12-25 07:24:59 -08:00
|
|
|
}
|
|
|
|
|
2021-02-21 18:38:21 -08:00
|
|
|
if (havePrefs) {
|
|
|
|
return window.localStorage.getItem(name) ?? defaultValue;
|
|
|
|
}
|
|
|
|
return defaultValue;
|
2020-11-24 17:48:14 +01:00
|
|
|
}
|
2021-02-21 18:38:21 -08:00
|
|
|
|
2020-11-24 17:48:14 +01:00
|
|
|
writePref(name: string, value: string) {
|
2022-05-10 06:52:06 -07:00
|
|
|
if (this.url.searchParams.has(name)) {
|
|
|
|
this.url.searchParams.set(name, value);
|
|
|
|
history.replaceState(
|
|
|
|
null,
|
|
|
|
this.title,
|
|
|
|
this.url.toString()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-02-21 18:38:21 -08:00
|
|
|
if (havePrefs) {
|
2020-11-24 17:48:14 +01:00
|
|
|
window.localStorage.setItem(name, value);
|
2021-02-21 18:38:21 -08:00
|
|
|
}
|
2020-11-24 17:48:14 +01:00
|
|
|
}
|
2013-10-10 11:03:07 -07:00
|
|
|
}
|