mapcomplete/UI/Base/TextField.ts

85 lines
2.6 KiB
TypeScript
Raw Normal View History

2020-07-01 00:12:33 +00:00
import {UIElement} from "../UIElement";
import {UIEventSource} from "../UIEventSource";
2020-07-05 16:59:47 +00:00
import {UIInputElement} from "./UIInputElement";
2020-07-01 00:12:33 +00:00
2020-07-05 16:59:47 +00:00
export class TextField<T> extends UIInputElement<T> {
2020-07-01 00:12:33 +00:00
2020-07-20 11:28:45 +00:00
private value: UIEventSource<string>;
private mappedValue: UIEventSource<T>;
2020-07-01 00:12:33 +00:00
/**
* Pings and has the value data
*/
public enterPressed = new UIEventSource<string>(undefined);
private _placeholder: UIEventSource<string>;
2020-07-20 11:28:45 +00:00
private _pretext: string;
private _fromString: (string: string) => T;
2020-07-01 00:12:33 +00:00
2020-07-20 11:28:45 +00:00
constructor(options: {
placeholder?: UIEventSource<string>,
toString: (t: T) => string,
fromString: (string: string) => T,
pretext?: string,
value?: UIEventSource<T>
}) {
super(options?.placeholder);
this.value = new UIEventSource<string>("");
this.mappedValue = options?.value ?? new UIEventSource<T>(undefined);
this.value.addCallback((str) => this.mappedValue.setData(options.fromString(str)));
this.mappedValue.addCallback((t) => this.value.setData(options.toString(t)));
this._placeholder = options?.placeholder ?? new UIEventSource<string>("");
this._pretext = options?.pretext ?? "";
const self = this;
this.mappedValue.addCallback((t) => {
if (t === undefined && t === null) {
return;
}
const field = document.getElementById('text-' + this.id);
if (field === undefined && field === null) {
return;
}
field.value = options.toString(t);
})
2020-07-05 16:59:47 +00:00
}
GetValue(): UIEventSource<T> {
2020-07-20 11:28:45 +00:00
return this.mappedValue;
2020-07-01 00:12:33 +00:00
}
protected InnerRender(): string {
2020-07-20 11:28:45 +00:00
return this._pretext + "<form onSubmit='return false' class='form-text-field'>" +
2020-07-05 16:59:47 +00:00
"<input type='text' placeholder='" + (this._placeholder.data ?? "") + "' id='text-" + this.id + "'>" +
2020-07-01 00:12:33 +00:00
"</form>";
}
InnerUpdate(htmlElement: HTMLElement) {
const field = document.getElementById('text-' + this.id);
const self = this;
field.oninput = () => {
2020-07-05 16:59:47 +00:00
// @ts-ignore
2020-07-01 00:12:33 +00:00
self.value.setData(field.value);
};
field.addEventListener("keyup", function (event) {
if (event.key === "Enter") {
2020-07-05 16:59:47 +00:00
// @ts-ignore
2020-07-01 00:12:33 +00:00
self.enterPressed.setData(field.value);
}
});
2020-07-05 16:59:47 +00:00
2020-07-01 00:12:33 +00:00
}
Clear() {
const field = document.getElementById('text-' + this.id);
if (field !== undefined) {
2020-07-05 16:59:47 +00:00
// @ts-ignore
2020-07-01 00:12:33 +00:00
field.value = "";
}
}
}