-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
88 lines (79 loc) · 2.57 KB
/
Copy pathindex.html
File metadata and controls
88 lines (79 loc) · 2.57 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html>
<head>
<title>Chat - api-ape</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<chat-app></chat-app>
<script src="https://unpkg.com/hyperhtml"></script>
<script src="https://unpkg.com/hyper-element"></script>
<script src="/api/ape.js"></script>
<script>
customElements.define('chat-app', class extends hyperElement {
setup(attachStore) {
this.user = 'User' + Math.random().toString(36).slice(2, 6)
this.messages = []
this.onStoreChange = attachStore(() => this.messages)
// Subscribe to init with history + user count on connect
api.init(data => {
this.messages = data.history || []
this.users = data.users || 0
this.onStoreChange()
})
// Subscribe to user count updates
api.users(data => {
this.users = data.count
this.onStoreChange()
})
// Subscribe to new messages from others
api.message(data => {
this.messages.push(data)
this.onStoreChange()
})
}
send(e) {
if (e.key !== 'Enter' || !e.target.value) return
const msg = { user: this.user, text: e.target.value }
api.message(msg).then(() => {
this.messages.push(msg)
this.onStoreChange()
})
e.target.value = ''
}
render(Html, messages) {
messages = messages || []
Html`
<div class="chat-container">
<div class="header">
<span class="title">💬 Chat</span>
<span class="online-count">🟢 ${this.users || 0} online</span>
<span class="user-badge">● ${this.user}</span>
</div>
<div class="messages">
${messages.length === 0
? Html.wire()`<div class="empty-state">No messages yet...</div>`
: messages.map(m => Html.wire(m, ':msg')`
<div class="${'message' + (m.user === this.user ? ' mine' : '')}">
<span class="username">${m.user}</span>
<span class="text">${m.text}</span>
</div>
`)
}
</div>
<div class="input-area">
<input
class="message-input"
placeholder="Type a message..."
onkeydown=${e => this.send(e)}
autofocus
>
</div>
</div>
`
}
})
</script>
</body>
</html>