Allow to pin nodes to top of the list (#48)

* Refactored persistent state a bit
* Allow nodes to be pinned to top
This commit is contained in:
Maciej Hirsz
2018-09-24 17:30:39 +02:00
committed by GitHub
parent 44d91a54d5
commit 1559b82eb0
24 changed files with 194 additions and 86 deletions
@@ -0,0 +1,38 @@
import { Maybe, Stringified, stringify, parse } from '@dotstats/common';
export class Persistent<Data> {
private readonly onChange: (value: Data) => void;
private readonly key: string;
private value: Data;
constructor(key: string, initial: Data, onChange: (value: Readonly<Data>) => void) {
this.key = key;
this.onChange = onChange;
const stored = window.localStorage.getItem(key) as Maybe<Stringified<Data>>;
if (stored) {
this.value = parse(stored);
} else {
this.value = initial;
}
window.addEventListener('storage', (event) => {
if (event.key === this.key) {
this.value = parse(event.newValue as any as Stringified<Data>);
this.onChange(this.value);
}
});
}
public get(): Readonly<Data> {
return this.value;
}
public set(value: Data) {
this.value = value;
window.localStorage.setItem(this.key, stringify(this.value) as any as string);
this.onChange(this.value);
}
}