72 lines
1.5 KiB
JavaScript
72 lines
1.5 KiB
JavaScript
import m from "mithril";
|
|
import { createWebSocket } from "./websocket";
|
|
|
|
// on new message event, call m.redraw();
|
|
const messages = [];
|
|
const socket = createWebSocket();
|
|
|
|
socket.onmessage = function (event) {
|
|
if (event.type === "message") {
|
|
const message = JSON.parse(event.data);
|
|
messages.push(message);
|
|
m.redraw();
|
|
}
|
|
}
|
|
|
|
function newMessageText(name, message) {
|
|
return [
|
|
m("span.chatter", name + ": "),
|
|
m("span.chatter-message", message)
|
|
];
|
|
}
|
|
|
|
const MessageBox = {
|
|
view: function () {
|
|
return m(".messages", messages.map(function(message) {
|
|
return m(".message", newMessageText(message.chatter, message.message));
|
|
}));
|
|
}
|
|
};
|
|
|
|
function clearMessageBox() {
|
|
const messageBox = document.getElementById("message");
|
|
messageBox.value = "";
|
|
}
|
|
|
|
function sendMessage(e) {
|
|
e.preventDefault();
|
|
|
|
const form = new FormData(e.target);
|
|
const message = {};
|
|
|
|
for (const [key, value] of form.entries()) {
|
|
message[key] = value;
|
|
}
|
|
|
|
socket.send(JSON.stringify(message));
|
|
clearMessageBox();
|
|
}
|
|
|
|
const MessageInput = {
|
|
view: function () {
|
|
return m("div.chat-input", [
|
|
m("form", { method: "post", onsubmit: sendMessage }, [
|
|
m("input", { name: "chatter", placeholder: "Name" }),
|
|
m("input", { name: "message", placeholder: "Message", id: "message", required: true }),
|
|
m("input", { type: "submit", value: "Send" })
|
|
])
|
|
]);
|
|
}
|
|
};
|
|
|
|
const Chat = {
|
|
view: function(vnode) {
|
|
return m("div", [
|
|
m(MessageBox),
|
|
m(MessageInput)
|
|
])
|
|
}
|
|
};
|
|
|
|
m.mount(document.getElementById("app"), Chat);
|