import { Author, Message } from "./message" import util from "./util" import { BatchTimer } from "./batch-timer" import { AdapterState } from "./adapter" export class AuthorMessagesElement extends HTMLElement { static observedAttributes = [ "data-latest", "data-adapter", "data-target" ]; private _id: string | null = null; private _adapter: string = ""; private _messages: Message[] = []; private _byAuthorTimer: BatchTimer | null = null; constructor() { super(); this.innerHTML = "" } connectedCallback() { this._id = this.getAttribute("data-target"); this._adapter = this.getAttribute("data-adapter") ?? ""; const gateway = this.getAttribute("data-gateway") ?? ""; this._byAuthorTimer = new BatchTimer((ids: string[])=>{ let url = `${gateway}/api/adapters/${this._adapter}/fetch?entity_type=byAuthor`; for (let id of ids) { url += `&entity_id=${id}`; } util.authorizedFetch("GET", url, null); }); } attributeChangedCallback(attr: string, prev: string, next: string) { switch (attr) { case "data-target": if (!next) { return } this._id = next; if (this._byAuthorTimer) { this._byAuthorTimer.queue(next, 100) } break; case "data-latest": let datastore = AdapterState._instance.data.get(this._adapter); if (!datastore) { console.log("no data yet, wait for some to come in maybe..."); return; } let msg = datastore.messages.get(next); if (msg) { // if _messages has this one, and this updated date is greater const existingIdx = this._messages.findIndex(m=>m.id == msg.id && ((m.edited ?? 0) < (msg.edited ?? 0))); if (existingIdx >= 0) { this._messages[existingIdx] = msg; // and update it in the dom } else { this._messages.push(msg); // and insert in into the dom } console.log(JSON.stringify(this._messages)); } } } }