mapcomplete/UI/Input/FileSelectorButton.ts

66 lines
2 KiB
TypeScript
Raw Normal View History

2021-06-11 22:51:45 +02:00
import BaseUIElement from "../BaseUIElement";
2021-06-14 19:21:33 +02:00
import {InputElement} from "./InputElement";
2021-06-11 22:51:45 +02:00
import {UIEventSource} from "../../Logic/UIEventSource";
export default class FileSelectorButton extends InputElement<FileList> {
2021-06-14 19:21:33 +02:00
private static _nextid;
2021-06-11 22:51:45 +02:00
IsSelected: UIEventSource<boolean>;
private readonly _value = new UIEventSource(undefined);
private readonly _label: BaseUIElement;
private readonly _acceptType: string;
constructor(label: BaseUIElement, acceptType: string = "image/*") {
super();
this._label = label;
this._acceptType = acceptType;
2021-06-14 19:21:33 +02:00
this.SetClass("block cursor-pointer")
label.SetClass("cursor-pointer")
2021-06-11 22:51:45 +02:00
}
GetValue(): UIEventSource<FileList> {
return this._value;
}
IsValid(t: FileList): boolean {
return true;
}
protected InnerConstructElement(): HTMLElement {
const self = this;
const el = document.createElement("form")
2021-06-14 19:21:33 +02:00
const label = document.createElement("label")
label.appendChild(this._label.ConstructElement())
el.appendChild(label)
2021-06-11 22:51:45 +02:00
2021-06-14 19:21:33 +02:00
const actualInputElement = document.createElement("input");
actualInputElement.style.cssText = "display:none";
actualInputElement.type = "file";
actualInputElement.accept = this._acceptType;
actualInputElement.name = "picField";
actualInputElement.multiple = true;
actualInputElement.id = "fileselector" + FileSelectorButton._nextid;
FileSelectorButton._nextid++;
2021-06-11 22:51:45 +02:00
2021-06-14 19:21:33 +02:00
label.htmlFor = actualInputElement.id;
actualInputElement.onchange = () => {
if (actualInputElement.files !== null) {
self._value.setData(actualInputElement.files)
}
2021-06-11 22:51:45 +02:00
}
2021-06-14 19:21:33 +02:00
el.addEventListener('submit', e => {
if (actualInputElement.files !== null) {
self._value.setData(actualInputElement.files)
}
e.preventDefault()
})
el.appendChild(actualInputElement)
return el;
2021-06-11 22:51:45 +02:00
}
}