-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
52 lines (44 loc) · 1.31 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Chat using Deno</title>
</head>
<body>
<div id="app" />
<script type="module">
import { html, render, useEffect, useState } from 'https://unpkg.com/htm/preact/standalone.module.js'
let ws
function Chat() {
// Messages
const [messages, setMessages] = useState([])
const onReceiveMessage = ({ data }) => setMessages(m => ([...m, data]))
const onSendMessage = e => {
const msg = e.target[0].value
e.preventDefault()
ws.send(msg)
e.target[0].value = ''
}
// Websocket connection + events
useEffect(() => {
if (ws) ws.close()
ws = new WebSocket(`ws://${window.location.host}/ws`)
ws.addEventListener("message", onReceiveMessage)
return () => {
ws.removeEventListener("message", onReceiveMessage)
}
}, [])
return html`
${messages.map(message => html`
<div>${message}</div>
`)}
<form onSubmit=${onSendMessage}>
<input type="text" />
<button>Send</button>
</form>
`
}
render(html`<${Chat} />`, document.getElementById('app'))
</script>
</body>
</html>