MapComplete/UI/Input/Checkboxes.ts

83 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-09-09 22:17:46 +02:00
import {InputElement} from "./InputElement";
import {UIEventSource} from "../../Logic/UIEventSource";
import {Utils} from "../../Utils";
2021-06-11 22:51:45 +02:00
import BaseUIElement from "../BaseUIElement";
2020-09-09 22:17:46 +02:00
/**
* Supports multi-input
*/
export default class CheckBoxes extends InputElement<number[]> {
2020-09-09 22:17:46 +02:00
IsSelected: UIEventSource<boolean> = new UIEventSource<boolean>(false);
2021-06-11 22:51:45 +02:00
private readonly _element : HTMLElement
2021-06-12 02:58:32 +02:00
private static _nextId = 0;
private readonly value: UIEventSource<number[]>
constructor(elements: BaseUIElement[], value =new UIEventSource<number[]>([])) {
2021-06-11 22:51:45 +02:00
super();
2021-06-12 02:58:32 +02:00
this.value = value;
elements = Utils.NoNull(elements);
2021-06-11 22:51:45 +02:00
2021-06-12 02:58:32 +02:00
const el = document.createElement("form")
for (let i = 0; i < elements.length; i++) {
let inputI = elements[i];
const input = document.createElement("input")
const id = CheckBoxes._nextId
CheckBoxes._nextId ++;
input.id = "checkbox"+id
input.type = "checkbox"
const label = document.createElement("label")
label.htmlFor = input.id
label.appendChild(inputI.ConstructElement())
value.addCallbackAndRun(selectedValues =>{
if(selectedValues === undefined){
return;
}
if(selectedValues.indexOf(i) >= 0){
input.checked = true;
}
})
input.onchange = () => {
const index = value.data.indexOf(i);
if(input.checked && index < 0){
value.data.push(i);
value.ping();
}else if(index >= 0){
value.data.splice(index,1);
value.ping();
}
}
el.appendChild(input)
el.appendChild(document.createElement("br"))
}
2021-06-11 22:51:45 +02:00
}
protected InnerConstructElement(): HTMLElement {
return this._element
2020-09-09 22:17:46 +02:00
}
2020-09-10 21:06:56 +02:00
IsValid(ts: number[]): boolean {
2021-01-27 02:58:11 +01:00
return ts !== undefined;
2020-09-09 22:17:46 +02:00
}
2020-09-10 21:06:56 +02:00
GetValue(): UIEventSource<number[]> {
2020-09-09 22:17:46 +02:00
return this.value;
}
}