mapcomplete/UI/Input/DropDown.ts

96 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-06-29 01:12:44 +00:00
import {UIEventSource} from "../UIEventSource";
import {UIElement} from "../UIElement";
2020-07-20 19:39:07 +00:00
import {InputElement} from "./InputElement";
import instantiate = WebAssembly.instantiate;
import {FixedUiElement} from "../Base/FixedUiElement";
2020-07-20 19:39:07 +00:00
export class DropDown<T> extends InputElement<T> {
2020-07-20 19:39:07 +00:00
private readonly _label: string;
private readonly _values: { value: T; shown: UIElement }[];
2020-07-20 19:39:07 +00:00
private readonly _value;
constructor(label: string,
values: { value: T, shown: string | UIElement }[],
value: UIEventSource<T> = undefined) {
super(undefined);
2020-07-20 19:39:07 +00:00
this._value = value ?? new UIEventSource<T>(undefined);
this._label = label;
2020-07-20 19:39:07 +00:00
this._values = values.map(v => {
return {
value: v.value,
shown: v.shown instanceof UIElement ? v.shown : new FixedUiElement(v.shown)
}
}
);
this.ListenTo(this._value)
}
2020-07-20 19:39:07 +00:00
GetValue(): UIEventSource<T> {
return this._value;
}
2020-07-20 19:39:07 +00:00
ShowValue(t: T): boolean {
if (!this.IsValid(t)) {
return false;
}
this._value.setData(t);
}
2020-07-20 19:39:07 +00:00
IsValid(t: T): boolean {
for (const value of this._values) {
2020-07-20 19:39:07 +00:00
if (value.value === t) {
return true;
}
}
2020-07-20 19:39:07 +00:00
return false
}
InnerRender(): string {
2020-07-20 22:07:04 +00:00
if(this._values.length <=1){
return "";
}
2020-07-20 19:39:07 +00:00
let options = "";
for (let i = 0; i < this._values.length; i++) {
options += "<option value='" + i + "'>" + this._values[i].shown.InnerRender() + "</option>"
}
return "<form>" +
"<label for='dropdown-" + this.id + "'>" + this._label + "</label>" +
"<select name='dropdown-" + this.id + "' id='dropdown-" + this.id + "'>" +
options +
"</select>" +
"</form>";
}
2020-07-20 19:39:07 +00:00
protected InnerUpdate(element) {
2020-07-20 22:07:04 +00:00
2020-07-20 19:39:07 +00:00
var e = document.getElementById("dropdown-" + this.id);
2020-07-20 22:07:04 +00:00
if(e === null){
return;
}
const self = this;
2020-07-20 19:39:07 +00:00
e.onchange = (() => {
// @ts-ignore
2020-07-20 19:39:07 +00:00
var index = parseInt(e.selectedIndex);
self._value.setData(self._values[index].value);
});
var t = this._value.data;
for (let i = 0; i < this._values.length ; i++) {
const value = this._values[i];
if (value.value == t) {
// @ts-ignore
e.selectedIndex = i;
}
}
2020-07-20 19:39:07 +00:00
}
}