underbbs/frontend/ts/create-message-element.ts

101 lines
3.1 KiB
TypeScript
Raw Normal View History

import { Doer } from './doer'
export class CreateMessageElement extends HTMLElement {
private _gateway: string = "";
private _adapter: string = ""
private _doer: Doer | null = null;
static observedAttributes = [ "data-replyto" ];
constructor() {
super();
this.innerHTML = `<form onsubmit="return false"><input readonly class="createmessage_replyto"></input><textarea class="createmessage_content"></textarea><details><summary>attachment?</summary><input type="file" class="createmessage_file"></input><input class="createmessage_desc"></input></details><input type="submit" value="post"></input></form>`
}
connectedCallback() {
this._gateway = this.getAttribute("data-gateway") ?? "";
this._adapter = this.getAttribute("data-adapter") ?? "";
this._doer = new Doer(this._gateway, this._adapter);
const postBtn = this.querySelector(`input[type="submit"]`);
if (postBtn) {
postBtn.addEventListener("click", this.doPost.bind(this));
}
}
attributeChangedCallback(attr: string, prev: string, next: string) {
switch (attr) {
// when we implement replies, we'll come back here
case "data-replyto":
const e = this.querySelector(".createmessage_replyto") as HTMLInputElement;
if (e) {
e.value = next;
}
default:
break;
}
}
resetInput(r: Response) {
if (r.ok) {
const f = this.querySelector("form") as HTMLFormElement;
if (f) {
f.reset();
}
}
}
doPost() {
const msgContent = this.querySelector(".createmessage_content") as HTMLTextAreaElement;
const msgAttachment = this.querySelector(".createmessage_file") as HTMLInputElement;
const msgAttachmentDesc = this.querySelector(".createmessage_desc") as HTMLInputElement;
const msgReplyTo = this.querySelector(".createmessage_replyto") as HTMLInputElement;
const doReq: any = {};
doReq.action = "post";
doReq.content = msgContent.value ?? "";
if (msgReplyTo && msgReplyTo.value) {
doReq.replyto = msgReplyTo.value;
}
if (msgAttachment.files && msgAttachment.files[0]) {
const r = new FileReader();
const self = this;
doReq.desc = msgAttachmentDesc.value ?? "";
r.onload = ()=>{
if (self && self._doer) {
doReq.file = r.result;
self._doer.do(doReq)
.then(r=>{
if (r.ok) {
msgContent.value = '';
msgAttachment.value = '';
msgAttachmentDesc.value = '';
msgReplyTo.value = '';
}
})
.catch(err=>{
// try to display an error locally on the component
});
}
}
r.readAsDataURL(msgAttachment.files[0]);
return;
}
if (this._doer) {
this._doer.do(doReq)
.then(r=>{
if (r.ok) {
msgContent.value = '';
msgAttachment.value = '';
msgAttachmentDesc.value = '';
msgReplyTo.value = '';
}
})
.catch(err=>{
// try to display an error locally on the component
});;
}
}
}