1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-27 17:49:08 -05:00
denoland-deno/std/examples/chat/index.html

82 lines
2.4 KiB
HTML
Raw Normal View History

<html lang="en">
2020-02-22 18:51:04 -05:00
<head>
<meta charset="UTF-8" />
2020-02-22 18:51:04 -05:00
<title>ws chat example</title>
</head>
<body>
<div>
<input type="text" id="input" />
<button id="sendButton" disabled>send</button>
<button id="connectButton" disabled>connect</button>
<button id="closeButton" disabled>close</button>
</div>
<div id="status"></div>
<ul id="timeline"></ul>
2020-02-22 18:51:04 -05:00
<script>
let ws;
function messageDom(msg) {
const div = document.createElement("li");
div.className = "message";
div.innerText = msg;
return div;
}
const timeline = document.getElementById("timeline");
const sendButton = document.getElementById("sendButton");
sendButton.onclick = send;
const closeButton =document.getElementById("closeButton");
closeButton.onclick=close;
const connectButton = document.getElementById("connectButton");
connectButton.onclick=connect;
const status = document.getElementById("status");
const input = document.getElementById("input");
2020-05-15 17:00:31 -04:00
input.addEventListener("keydown", keyDownEvent);
2020-02-22 18:51:04 -05:00
function send() {
const msg = input.value;
ws.send(msg);
2020-05-15 17:00:31 -04:00
applyState({inputValue: ""});
}
function keyDownEvent(e) {
if (e.keyCode === 13) return send();
2020-02-22 18:51:04 -05:00
}
function connect() {
if (ws) ws.close();
ws = new WebSocket(`ws://${location.host}/ws`);
2020-02-22 18:51:04 -05:00
ws.addEventListener("open", () => {
console.log("open", ws);
applyState({connected: true});
});
ws.addEventListener("message", ({data}) => {
timeline.appendChild(messageDom(data));
});
ws.addEventListener("close", () => {
applyState({connect: false});
});
}
function close() {
ws.close();
applyState({connected: false});
}
function applyState({connected, status, inputValue}) {
if (inputValue != null) {
input.value = inputValue;
}
if(status != null) {
status.innerText = status;
}
if (connected != null) {
if (connected) {
sendButton.disabled = false;
connectButton.disabled = true;
closeButton.disabled= false;
} else {
sendButton.disabled= true;
connectButton.disabled=false;
closeButton.disabled=true;
}
}
}
connect();
</script>
</body>
</html>