107 lines
3.5 KiB
HTML
107 lines
3.5 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>Chat with Websockets</title>
|
|
<link rel="stylesheet" href="/css/default.css">
|
|
</head>
|
|
<body>
|
|
<div id="titlebar">
|
|
<div class="content">
|
|
<a href="/" class="tb-home">Home</a>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="content">
|
|
<h1 class="content-title">Chat with websockets</h1>
|
|
|
|
<div class="content-body">
|
|
<input autofocus label="Nick" id="nick"></input>
|
|
<textarea hidden disabled id="wfc-output"></textarea>
|
|
<input hidden id="wfc-input"></input>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
let nelt = document.getElementById('nick');
|
|
let ielt = document.getElementById('wfc-input');
|
|
let oelt = document.getElementById('wfc-output');
|
|
let ws = new WebSocket("/ws/chat");
|
|
let nick = '';
|
|
|
|
// when user hits any key while typing in nick
|
|
function on_nick(evt) {
|
|
if (evt.key === 'Enter') {
|
|
// don't do default thing
|
|
evt.preventDefault();
|
|
// grab contents
|
|
let contents = nelt.value;
|
|
let trimmed = contents.trim();
|
|
// if contents are nonempty
|
|
let nonempty_contents = trimmed.length > 0;
|
|
if (nonempty_contents) {
|
|
nick = trimmed;
|
|
let msg_obj = ['nick', nick];
|
|
let msg_str = JSON.stringify(msg_obj);
|
|
console.log('message to server:', contents.trim());
|
|
// query backend for result
|
|
ws.send(msg_str);
|
|
|
|
// delete element from dom
|
|
nelt.remove();
|
|
oelt.hidden = false;
|
|
ielt.hidden = false;
|
|
ielt.autofocus = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// when user hits any key while typing in ielt
|
|
function on_input_key(evt) {
|
|
if (evt.key === 'Enter') {
|
|
// don't do default thing
|
|
evt.preventDefault();
|
|
// grab contents
|
|
let contents = ielt.value;
|
|
let trimmed = contents.trim();
|
|
// if contents are nonempty
|
|
let nonempty_contents = trimmed.length > 0;
|
|
if (nonempty_contents) {
|
|
let msg_obj = ['chat', trimmed];
|
|
let msg_str = JSON.stringify(msg_obj);
|
|
console.log('message to server:', contents.trim());
|
|
// query backend for result
|
|
ws.send(msg_str);
|
|
|
|
// clear input
|
|
ielt.value = '';
|
|
|
|
// add to output
|
|
oelt.value += '> ';
|
|
oelt.value += trimmed;
|
|
oelt.value += '\n';
|
|
}
|
|
}
|
|
}
|
|
|
|
function main() {
|
|
nelt.addEventListener('keydown', on_nick);
|
|
ielt.addEventListener('keydown', on_input_key);
|
|
ws.onmessage =
|
|
function (msg_evt) {
|
|
console.log('message from server:', msg_evt);
|
|
let msg_str = msg_evt.data;
|
|
let msg_obj = JSON.parse(msg_str);
|
|
|
|
oelt.value += msg_obj.nick;
|
|
oelt.value += '> ';
|
|
oelt.value += msg_obj.msg;
|
|
oelt.value += '\n';
|
|
};
|
|
}
|
|
|
|
main();
|
|
</script>
|
|
</body>
|
|
</html>
|