mapcomplete/Logic/UIEventSource.ts

109 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-06-23 22:35:19 +00:00
export class UIEventSource<T>{
public data: T;
2020-06-23 22:35:19 +00:00
private _callbacks = [];
constructor(data: T) {
this.data = data;
}
public addCallback(callback: ((latestData : T) => void)) : UIEventSource<T>{
2020-06-23 22:35:19 +00:00
this._callbacks.push(callback);
return this;
}
public setData(t: T): UIEventSource<T> {
2020-06-23 22:35:19 +00:00
if (this.data === t) {
return;
}
this.data = t;
this.ping();
return this;
2020-06-23 22:35:19 +00:00
}
public ping(): void {
for (const callback of this._callbacks) {
callback(this.data);
2020-06-23 22:35:19 +00:00
}
}
2020-07-20 11:28:45 +00:00
public static flatten<X>(source: UIEventSource<UIEventSource<X>>, possibleSources: UIEventSource<any>[]): UIEventSource<X> {
const sink = new UIEventSource<X>(source.data?.data);
source.addCallback((latestData) => {
sink.setData(latestData?.data);
});
for (const possibleSource of possibleSources) {
2020-09-02 09:37:34 +00:00
possibleSource?.addCallback(() => {
2020-07-20 11:28:45 +00:00
sink.setData(source.data?.data);
})
}
return sink;
}
2020-07-08 09:23:36 +00:00
public map<J>(f: ((T) => J),
extraSources: UIEventSource<any>[] = [],
g: ((J) => T) = undefined ): UIEventSource<J> {
2020-06-23 22:35:19 +00:00
const self = this;
const newSource = new UIEventSource<J>(
f(this.data)
);
2020-07-08 09:23:36 +00:00
const update = function () {
2020-06-23 22:35:19 +00:00
newSource.setData(f(self.data));
2020-07-08 09:23:36 +00:00
}
2020-07-20 11:28:45 +00:00
2020-07-08 09:23:36 +00:00
this.addCallback(update);
for (const extraSource of extraSources) {
2020-08-31 11:25:13 +00:00
extraSource?.addCallback(update);
2020-07-08 09:23:36 +00:00
}
if(g !== undefined) {
newSource.addCallback((latest) => {
self.setData((g(latest)));
})
}
2020-07-08 09:23:36 +00:00
2020-06-23 22:35:19 +00:00
return newSource;
}
2020-07-20 22:07:04 +00:00
public syncWith(otherSource: UIEventSource<T>) : UIEventSource<T>{
2020-07-20 22:07:04 +00:00
this.addCallback((latest) => otherSource.setData(latest));
const self = this;
otherSource.addCallback((latest) => self.setData(latest));
if(this.data === undefined){
this.setData(otherSource.data);
}else{
otherSource.setData(this.data);
}
return this;
2020-07-20 22:07:04 +00:00
}
2020-09-02 09:37:34 +00:00
public stabilized(millisToStabilize) : UIEventSource<T>{
const newSource = new UIEventSource<T>(this.data);
let currentCallback = 0;
this.addCallback(latestData => {
currentCallback++;
const thisCallback = currentCallback;
window.setTimeout(() => {
if(thisCallback === currentCallback){
newSource.setData(latestData);
}
}, millisToStabilize)
});
return newSource;
}
2020-06-23 22:35:19 +00:00
}