chat-app/webpack/index.ts

85 lines
2.1 KiB
TypeScript

import { Client } from "./Client";
import "./style.scss";
import * as $ from "jquery";
(globalThis as any)['$'] = $;
(() => {
let secure = globalThis.location.protocol == "https";
let protocol = secure ? 'wss' : 'ws';
let hostname = globalThis.location.hostname;
let port = globalThis.location.port;
let uri = `${protocol}://${hostname}:${port}`;
let gClient = new Client(uri); // TODO do this differently
gClient.start();
gClient.on('motd', async message => {
let motd = $("#motd");
motd.fadeOut(() => {
motd.html(message).fadeIn();
});
});
let chat = {
send: (txt: string | number | string[]) => {
console.log(`Sending chat message: ${txt}`);
gClient.sendArray([{
m: 'a',
message: txt
}]);
},
receive: (msg: any) => {
// TODO write chat receive
if (!msg.a) return;
let nameDiv = `<div class="chat-name"></div>`
let messageDiv = `<div class="chat-message"></div>`
let li = `<li>Anonymous: ${msg.a}</li>`;
$('#chat-messages').append(li);
}
}
document.addEventListener('keydown', evt => {
if (evt.code == 'Enter' || evt.code == 'Escape') {
let chatInput = $("#chat-input");
let chatFocused = chatInput.is(':focus');
if (chatFocused == true) {
if (evt.code == 'Enter') {
let text = chatInput.val();
if (text !== '') {
chat.send(text);
chatInput.val('');
}
}
chatInput.trigger('blur');
} else {
chatInput.trigger('focus');
}
}
});
gClient.on('a', msg => {
if (!msg.a) return;
console.log(`Received chat message: ${msg.a}`);
chat.receive(msg);
});
gClient.on('ch', msg => {
console.log(msg._id);
});
(globalThis as any).app = {
client: gClient
}
})();