mapcomplete/UI/UIElement.ts

98 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-06-24 00:35:19 +02:00
import {UIEventSource} from "./UIEventSource";
2020-07-01 02:12:33 +02:00
import {Playground} from "../Layers/Playground";
2020-06-24 00:35:19 +02:00
export abstract class UIElement {
private static nextId: number = 0;
public readonly id: string;
public readonly _source: UIEventSource<any>;
private _hideIfEmpty = false;
2020-06-24 00:35:19 +02:00
protected constructor(source: UIEventSource<any>) {
this.id = "ui-element-" + UIElement.nextId;
this._source = source;
UIElement.nextId++;
this.ListenTo(source);
}
protected ListenTo(source: UIEventSource<any>) {
2020-07-01 02:12:33 +02:00
if (source === undefined) {
2020-06-24 00:35:19 +02:00
return;
}
const self = this;
source.addCallback(() => {
self.Update();
})
}
2020-07-01 02:12:33 +02:00
private _onClick: () => void;
public onClick(f: (() => void)) {
this._onClick = f;
this.Update();
return this;
2020-07-01 02:12:33 +02:00
}
2020-06-24 00:35:19 +02:00
Update(): void {
2020-07-01 02:12:33 +02:00
let element = document.getElementById(this.id);
2020-06-24 00:35:19 +02:00
if (element === null || element === undefined) {
// The element is not painted
return;
}
2020-07-01 02:12:33 +02:00
2020-06-24 00:35:19 +02:00
element.innerHTML = this.InnerRender();
2020-07-01 02:12:33 +02:00
if (this._hideIfEmpty) {
if (element.innerHTML === "") {
element.parentElement.style.display = "none";
2020-07-01 02:12:33 +02:00
} else {
element.parentElement.style.display = undefined;
}
}
2020-07-01 02:12:33 +02:00
if (this._onClick !== undefined) {
const self = this;
element.onclick = () => {
self._onClick();
}
2020-07-01 21:21:29 +02:00
element.style.pointerEvents = "all";
2020-07-01 02:12:33 +02:00
element.style.cursor = "pointer";
}
2020-06-24 00:35:19 +02:00
this.InnerUpdate(element);
}
HideOnEmpty(hide : boolean){
this._hideIfEmpty = hide;
this.Update();
return this;
}
2020-06-24 00:35:19 +02:00
// Called after the HTML has been replaced. Can be used for css tricks
InnerUpdate(htmlElement : HTMLElement){}
Render(): string {
return "<span class='uielement' id='" + this.id + "'>" + this.InnerRender() + "</span>"
}
AttachTo(divId: string) {
let element = document.getElementById(divId);
if(element === null){
console.log("SEVERE: could not attach UIElement to ", divId);
return;
}
2020-06-24 00:35:19 +02:00
element.innerHTML = this.Render();
this.Update();
return this;
2020-06-24 00:35:19 +02:00
}
protected abstract InnerRender(): string;
public Activate(): void {};
public IsEmpty(): boolean {
return this.InnerRender() === "";
}
}