mapcomplete/UI/Input/Checkboxes.ts

91 lines
2.3 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";
2020-09-10 21:06:56 +02:00
import {UIElement} from "../UIElement";
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);
2020-09-10 21:06:56 +02:00
private readonly value: UIEventSource<number[]>;
2021-06-11 22:51:45 +02:00
private readonly _elements: BaseUIElement[]
private readonly _element : HTMLElement
2020-09-09 22:17:46 +02:00
2021-06-11 22:51:45 +02:00
constructor(elements: BaseUIElement[]) {
super();
2020-09-09 22:17:46 +02:00
this._elements = Utils.NoNull(elements);
2020-09-10 21:06:56 +02:00
this.value = new UIEventSource<number[]>([])
2021-06-11 22:51:45 +02:00
const el = document.createElement()
this._element = el;
}
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;
}
private IdFor(i) {
return 'checkmark-' + this.id + '-' + i;
}
InnerRender(): string {
let body = "";
for (let i = 0; i < this._elements.length; i++) {
let el = this._elements[i];
const htmlElement =
`<input type="checkbox" id="${this.IdFor(i)}"><label for="${this.IdFor(i)}">${el.Render()}</label><br/>`;
body += htmlElement;
}
2021-01-27 02:58:11 +01:00
2020-09-10 19:33:06 +02:00
return `<form id='${this.id}'>${body}</form>`;
2020-09-09 22:17:46 +02:00
}
protected InnerUpdate(htmlElement: HTMLElement) {
const self = this;
for (let i = 0; i < this._elements.length; i++) {
const el = document.getElementById(this.IdFor(i));
2020-09-10 21:06:56 +02:00
if(this.value.data.indexOf(i) >= 0){
2020-09-10 19:33:06 +02:00
// @ts-ignore
2020-09-10 21:06:56 +02:00
el.checked = true;
2020-09-09 22:17:46 +02:00
}
2020-09-10 21:06:56 +02:00
el.onchange = () => {
const index = self.value.data.indexOf(i);
2020-09-09 22:17:46 +02:00
// @ts-ignore
2020-09-10 21:06:56 +02:00
if(el.checked && index < 0){
self.value.data.push(i);
self.value.ping();
}else if(index >= 0){
self.value.data.splice(index,1);
self.value.ping();
2020-09-09 22:17:46 +02:00
}
}
}
}
}