twitch-chat/static/main.js

97 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-03-20 16:01:29 +01:00
const timeout = 120000;
2020-03-20 12:23:27 +01:00
class Message {
constructor(object, onDestroy) {
this.target = object.target;
this.context = object.context;
this.message = object.message;
this.self = object.self;
}
createEl() {
this.element = document.createElement('li');
this.element.className = "item";
this.element.style.position = "relative";
2020-03-20 16:01:29 +01:00
let badges = document.createElement('span');
for (let key in this.context.badges) {
let badge = document.createElement('span');
badge.className = "badge";
badge.innerHTML = '<img src="/static/' + key + '.png">';
badges.appendChild(badge);
}
this.element.appendChild(badges);
2020-03-20 12:23:27 +01:00
let name = document.createElement('span');
name.className = "text name";
name.style.color = this.context.color;
name.innerHTML = escapeHtml(this.context["display-name"]);
this.element.appendChild(name);
let message = document.createElement('span');
2020-03-20 16:01:29 +01:00
let text = escapeHtml(this.message);
for (let key in emotes) {
text = replaceAll(text, escapeHtml(key), '<img src="' + emotes[key].url + '">');;
}
message.innerHTML = text;
2020-03-20 12:23:27 +01:00
message.className = "text message";
this.element.appendChild(message);
setTimeout(() => this.destroy(), timeout);
return this.element;
}
destroy() {
this.element.className += ' destroy';
}
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
2020-03-20 16:01:29 +01:00
function replaceAll(input, from, to) {
const fromLen = from.length;
let output = "";
let pos = 0;
for (;;) {
let matchPos = input.indexOf(from, pos);
if (matchPos === -1) {
output += input.slice(pos);
break;
}
output += input.slice(pos, matchPos);
output += to;
pos = matchPos + fromLen;
}
return output;
}
2020-03-20 12:23:27 +01:00
function addMessage(object) {
messages .className = "";
let message = new Message(object);
messages.appendChild(message.createEl());
messages.style.bottom = '-' + message.element.offsetHeight + 'px';
messages.className = "slide";
};
let messages = document.getElementById('messages');
2020-03-20 16:01:29 +01:00
let emotes = {};
2020-03-20 12:23:27 +01:00
let socket = io();
socket.on('message', addMessage);
2020-03-20 16:01:29 +01:00
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
emotes = JSON.parse(xhr.responseText);
}
}
xhr.open('GET', '/static/emotes.json', true);
xhr.send();