mapcomplete/UI/Base/UIRadioButton.ts

107 lines
3.1 KiB
TypeScript
Raw Normal View History

2020-06-29 03:12:44 +02:00
import {UIElement} from "../UIElement";
import {UIEventSource} from "../UIEventSource";
2020-07-05 18:59:47 +02:00
import {UIInputElement} from "./UIInputElement";
2020-07-05 18:59:47 +02:00
export class UIRadioButton<T> extends UIInputElement<T> {
2020-07-05 18:59:47 +02:00
public readonly SelectedElementIndex: UIEventSource<number>
= new UIEventSource<number>(null);
2020-07-05 18:59:47 +02:00
private readonly _elements: UIEventSource<UIElement[]>
private _selectFirstAsDefault: boolean;
private _valueMapping: (i: number) => T;
2020-07-05 18:59:47 +02:00
constructor(elements: UIEventSource<UIElement[]>,
valueMapping: ((i: number) => T),
selectFirstAsDefault = true) {
super(elements);
this._elements = elements;
2020-07-05 18:59:47 +02:00
this._selectFirstAsDefault = selectFirstAsDefault;
const self = this;
this._valueMapping = valueMapping;
this.SelectedElementIndex.addCallback(() => {
self.InnerUpdate(undefined);
})
}
2020-07-05 18:59:47 +02:00
GetValue(): UIEventSource<T> {
return this.SelectedElementIndex.map(this._valueMapping);
}
2020-07-05 18:59:47 +02:00
private IdFor(i) {
return 'radio-' + this.id + '-' + i;
}
protected InnerRender(): string {
let body = "";
let i = 0;
for (const el of this._elements.data) {
const htmlElement =
2020-07-05 18:59:47 +02:00
'<input type="radio" id="' + this.IdFor(i) + '" name="radiogroup-' + this.id + '">' +
'<label for="' + this.IdFor(i) + '">' + el.Render() + '</label>' +
'<br>';
body += htmlElement;
i++;
}
return "<form id='" + this.id + "-form'>" + body + "</form>";
}
InnerUpdate(htmlElement: HTMLElement) {
const self = this;
function checkButtons() {
for (let i = 0; i < self._elements.data.length; i++) {
const el = document.getElementById(self.IdFor(i));
// @ts-ignore
if (el.checked) {
2020-07-05 18:59:47 +02:00
self.SelectedElementIndex.setData(i);
}
}
}
const el = document.getElementById(this.id);
el.addEventListener("change",
function () {
checkButtons();
}
);
if (this.SelectedElementIndex.data == null) {
2020-07-05 18:59:47 +02:00
if (this._selectFirstAsDefault) {
const el = document.getElementById(this.IdFor(0));
// @ts-ignore
el.checked = true;
checkButtons();
}
} else {
// We check that what is selected matches the previous rendering
var checked = -1;
2020-07-05 18:59:47 +02:00
var expected = this.SelectedElementIndex.data;
if (expected) {
for (let i = 0; i < self._elements.data.length; i++) {
const el = document.getElementById(self.IdFor(i));
// @ts-ignore
if (el.checked) {
checked = i;
}
}
2020-07-05 18:59:47 +02:00
if (expected != checked) {
const el = document.getElementById(this.IdFor(expected));
// @ts-ignore
el.checked = true;
}
}
}
}
}