import Messages, { Message } from "Modules/messages"; import Helpers from "Modules/helpers"; export default class Irc { private username: string; private color: string; private readonly messages = new Messages(); private readonly helpers = new Helpers(); readonly input = document.getElementById("msg") as HTMLInputElement; readonly divError = document.getElementById("error") as HTMLDivElement; constructor() { this.username = this.helpers.getUsername; this.color = this.helpers.getRandomColor; if (this.input === null) throw new Error("NoInputError"); this.input.onkeyup = (e: KeyboardEvent) => { if (e.code === "Enter") { if (this.messageExe(this.input.value) === true) { if (this.input.value === "") return; const msg = { text: this.input.value, username: this.username, color: this.color, time: Date.now(), }; this.input.value = ""; this.messages.sendMessage(msg); } } }; this.poll(); } async poll(): Promise { fetch(this.messages.url + "poll") .then(async res => { const msg = await res.json(); this.messages.addMessage(msg); const update = document.activeElement === this.input ? "bottom" : "relative"; this.helpers.updateScrollbar(update); this.poll(); }) .catch(this.poll); } messageExe(msg: string): boolean { if (msg[0] !== "/") return true; const msgToSend: Message = { time: Date.now(), color: "black", username: "Server", text: "", }; msg = msg.slice(1); if (msg.startsWith("quit") === true) { msgToSend.text = `User ${this.username} has left the chat`; this.messages.sendMessage(msgToSend); this.helpers.suicide( "Thank you for using this site, you can now safely close it." ); } else if (msg.startsWith("color") === true) { const color = msg.split(" ")[1]; if (this.helpers.isColor(color) === true) { msgToSend.text = `User ${this.username} has changed his color to ${color}`; this.messages.sendMessage(msgToSend); this.color = color; } else { this.divError.innerText = "You need to give correct color!"; } } else if (msg.startsWith("nick") === true) { const username = msg.slice(4).trim(); if (username === "Server") { this.divError.innerText = "You have to give legal nick!"; } else { msgToSend.text = `User ${this.username} has changed his nick to ${username}`; this.messages.sendMessage(msgToSend); this.username = username; } } else { this.divError.innerText = "Wrong command!"; } setTimeout(() => (this.divError.innerText = ""), 3000); this.input.value = ""; return false; } } new Irc();