-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.html
416 lines (370 loc) · 12.5 KB
/
chat.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plain Chat</title>
</head>
<!-- This is Plain Chat! My goal here was to 1) Write legible code 2) that works 3) using petite-vue to get my head around Vue concepts
4) using WebSockets and ServerEvents 5) in as few lines as possible. As I write this I'm under 425 lines for the entire app :) Enjoy! -->
<style>
h1, h3 {
margin-top: 8px;
margin-bottom: 8px;
font-family: Tahoma, Verdana, sans-serif;
}
main {
margin-left: auto;
margin-right: auto;
display: flex;
gap: 8px;
}
aside {
width: 20%;
}
article {
width: 60%
}
kbd {
border-radius: 2px;
padding: 2px;
border: 1px solid black;
}
form {
display: flex;
flex-direction: column;
gap: 8px;
}
.code_entry {
margin-bottom: 1rem;
}
.counters {
display: flex;
justify-content: space-around;
}
.message {
padding: 8px;
border: 1px solid black;
border-radius: 4px;
margin-top: 8px;
}
.mine {
margin-left: 120px;
}
.theirs {
margin-right: 120px;
background-color: lightgray;
}
.chat-req-item {
display: flex;
flex-direction: column;
border-top: 1px solid lightgray;
padding-top: 4px;
padding-bottom: 4px;
}
.chat-title {
margin-top: 8px;
margin-bottom: 8px;
display: flex;
gap: 16px;
}
.ul {
display: flex;
flex-direction: column;
gap: 8px;
}
.help-screen {
background-color: white;
position: fixed;
top: 80px;
left: 80px;
right: 80px;
bottom: 160px;
border: 3px outset;
padding: 16px;
display: flex;
flex-direction: column;
}
</style>
<body v-scope @vue:mounted="on_mount" style="display: none;">
<h1>Plain Chat</h1>
<h3>Your Chat Code: {{ your_code }} <button @click="show_help">?</button></h3>
<div style="display: flex; justify-content: space-between;">
<span>Chats on Plain Chat are ephemeral; so is your chat code. Reloading this page will end all your chats and generate a new code.</span>
<span>
<a href="https://github.com/dmitrydwhite/personal-page/blob/main/chat.html" target="_blank">See front end code</a>
<a href="https://glitch.com/edit/#!/topaz-overjoyed-motion" target="_blank">See server code</a>
</span>
</div>
<hr />
<div class="help-screen" v-if="help_visible">
<h3>Plain Chat: How it works</h3>
<div style="flex-grow: 1;">
<p>
To communicate with a friend, either give them your code or get theirs through a different method of communication.
The chat initiator has to send a message along with their request.
This will notify the other person that someone has requested a chat with them, and will provide them with your code.
Any messages that the initiator writes before the other person accepts the request will not be sent.
</p>
<p>Your chats are not saved or stored anywhere.</p>
<p>This app is very much in Alpha; expect bugs.</p>
</div>
<div style="text-align: center;">
<button @click="hide_help">OK</button>
</div>
</div>
<main>
<aside>
<span v-if="chat_reqs.length"><strong>Chat Requests</strong></span>
<div class="ul" v-if="chat_reqs.length">
<div v-for="chat_req in chat_reqs" class="chat-req-item">
<span><strong>From:</strong> {{ chat_req.their_code }}</span>
<span>{{ chat_req.message }}</span>
<span>
<button @click="accept_chat_request(chat_req.chat_code, chat_req.message, chat_req.their_code)">Accept</button>
<button>Decline</button>
</span>
</div>
</div>
<span><strong>Chats</strong></span>
<div class="ul">
<button @click="active_chat = ''">* New Chat</button>
<button v-for="chat in chats" @click="active_chat = chat.chat_id, chat_nickname = ''">
<div>
<span><strong>With:</strong> {{ chat.nickname || chat.their_code }}</span><br>
<span v-if="chat.messages[0].sender === 'me'">You: </span>
<span v-else></span>
<span>{{ chat.messages[0].message }}</span>
</div>
</button>
</div>
</aside>
<article>
<div v-if="active_chat">
<div class="chat-title">
<h3 style="margin: 0;">
Chat with {{active_chat_name}}
</h3>
<input placeholder="Nickname this chat" v-model="chat_nickname" />
<button @click="set_chat_nickname">
✏️ Set chat nickname
</button>
<button @click="end_this_chat">
🚫 End this chat
</button>
</div>
<form @submit.prevent="submit_my_message($el)" @keydown.enter="check_for_submit">
<textarea v-model="entered_msg" ref="message_input"></textarea>
<span>Type <kbd>⌘</kbd> + <kbd>Enter</kbd> or click the button below to send your message</span>
<button type="submit" :disabled="!entered_msg">Send</button>
</form>
<div :class="`message ${msg.sender === 'me' ? 'mine' : 'theirs'}`" v-for="msg in message_hist[active_chat].messages">
{{ msg.message }}
</div>
</div>
<div v-else>
<div>Start a chat with a friend</div>
<div class="code_entry" >
<label>Enter your friend's code</label>
<input v-model="their_code" />
</div>
<div>
<form @submit.prevent="init_chat_request($el)" @keydown.enter="check_for_init_submit">
<textarea v-model="entered_msg" ref="message_input"></textarea>
<span>Type <kbd>⌘</kbd> + <kbd>Enter</kbd> or click the button below to send your message</span>
<button type="submit" :disabled="!(their_code && entered_msg)">Send</button>
</form>
</div>
</div>
</article>
<aside />
</main>
<script type="module">
import { createApp } from 'https://unpkg.com/petite-vue?module';
const CHARS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const B_SIZE = 8;
const C_SIZE = 5;
const method = 'post';
const headers = { 'Content-Type': 'application/json' };
function extend(num) {
return function (str) {
while (str.length < num) {
str = `0${str}`;
}
return str;
};
}
/**
* @param {string} str
*/
function makeCode(str) {
const encVals = str.split('').map(char => char.charCodeAt(0));
const byteLen = encVals.length * B_SIZE;
const overflowBits = byteLen % C_SIZE;
let byteIdx = 0;
let start = 0;
let enc = '';
if (overflowBits) {
enc = CHARS[parseInt(extend(8)(encVals[0].toString(2)).slice(0, overflowBits), 2)];
start = overflowBits;
}
while (byteIdx < encVals.length) {
const bStr = extend(16)(((encVals[byteIdx] << 8) + (encVals[byteIdx + 1] || 0)).toString(2));
enc += CHARS[parseInt(bStr.slice(start, start + C_SIZE), 2)];
start += C_SIZE;
if (start >= B_SIZE) {
byteIdx += 1;
start = start % B_SIZE;
}
}
return `${enc.slice(3, 6)}-${enc.slice(6, 9)}-${enc.slice(9, 16)}`;
}
function generate_random_code() {
const seed = Number(`${Date.now()}`.slice(-5));
const generated = (seed * (((seed % 2) + 1) + Math.random()) * 1000000).toString().replace('.', '');
return makeCode(generated);
}
const app_obj = {
your_code: generate_random_code(),
notif_sock: null,
help_visible: false,
active_chat: '',
active_chat_name: '',
entered_msg: '',
their_code: '',
message_hist: {},
chat_socks: {},
chat_reqs: [],
chat_nickname: '',
get chats() {
const chats_arr = Object.values(this.message_hist);
if (chats_arr.length) {
return chats_arr.sort((a, b) => b.last_update - a.last_update);
}
return [];
},
get active_chat_name() {
if (!this.active_chat) { return ''; }
return this.message_hist[this.active_chat].nickname || this.message_hist[this.active_chat].their_code;
},
show_help() {
this.help_visible = true;
},
hide_help() {
this.help_visible = false;
},
normalize_their_code(entry) {
const normalized = entry
.replace(/[-\s]/g, '')
.replace(/[oO]/g, '0')
.replace(/[iIlL]/g, '1')
.toUpperCase();
return `${normalized.slice(0, 3)}-${normalized.slice(3, 6)}-${normalized.slice(6)}`;
},
check_for_init_submit(event) {
if (event.metaKey) {
event.preventDefault();
this.init_chat_request(document.getElementsByTagName('form')[0]);
}
},
check_for_submit(event) {
if (event.metaKey) {
event.preventDefault();
this.submit_my_message(document.getElementsByTagName('form')[0]);
}
},
handle_event(dataStr) {
if (dataStr === 'ping') { return; }
try {
const { their_code, chat_code, message } = JSON.parse(dataStr);
this.chat_reqs.push({ their_code, chat_code, message });
} catch (err) {
/* noop */
}
},
handle_control(ctrl_obj) {
console.log('handling control', ctrl_obj);
/* noop */
},
set_chat_nickname() {
this.message_hist[this.active_chat].nickname = this.chat_nickname;
this.chat_nickname = '';
},
create_chat_sock(chat_id) {
const chat_sock = new WebSocket(`wss://topaz-overjoyed-motion.glitch.me/chat?c=${chat_id}&m=${this.your_code}`);
chat_sock.onmessage = (ev) => {
const rec_msg = JSON.parse(ev.data);
if (rec_msg.message) {
this.update_chats(chat_id, { message: rec_msg.message, sender: 'them' });
} else {
this.handle_control(rec_msg);
}
};
return chat_sock;
},
init_chat_request($form) {
const their_normalized_code = this.normalize_their_code(this.their_code);
const init_body = {
my_code: this.your_code,
their_code: their_normalized_code,
message: this.entered_msg,
};
$form.getElementsByTagName('button')[0].setAttribute('disabled', true);
fetch('https://topaz-overjoyed-motion.glitch.me/chat', { method, headers, body: JSON.stringify(init_body) })
.then(res => res.json())
.then(({ chat }) => {
if (chat) {
this.update_chats(chat, { sender: 'me', message: this.entered_msg }, their_normalized_code);
this.active_chat = chat;
}
this.entered_msg = '';
this.their_code = '';
this.chat_nickname = '';
})
.catch(err => {
console.log(err);
});
},
accept_chat_request(chat_id, message, from) {
this.update_chats(chat_id, { message, sender: 'them' }, from);
this.chat_reqs = this.chat_reqs.filter(x => x.chat_code !== chat_id);
this.active_chat = chat_id;
},
submit_my_message($form) {
this.update_chats(this.active_chat, { message: this.entered_msg, sender: 'me' });
this.chat_socks[this.active_chat].send(this.entered_msg);
this.entered_msg = '';
$form.getElementsByTagName('textarea')[0].focus();
},
update_chats(chat_id, message_obj, their_code) {
if (this.message_hist[chat_id]) {
this.message_hist[chat_id].last_update = Date.now();
this.message_hist[chat_id].messages.unshift({ ...message_obj, timestamp: Date.now() });
} else {
this.chat_socks[chat_id] = this.create_chat_sock(chat_id);
this.message_hist[chat_id] = {
last_update: Date.now(),
messages: [{ ...message_obj, timestamp: Date.now() }],
their_code,
chat_id,
};
}
},
end_this_chat() {
this.chat_socks[this.active_chat].close();
delete this.message_hist[this.active_chat];
this.active_chat = '';
},
on_mount() {
document.getElementsByTagName('body')[0].removeAttribute('style');
this.notif_sock = new EventSource(`https://topaz-overjoyed-motion.glitch.me/my-code/${this.your_code}`);
this.notif_sock.addEventListener('message', ({ data }) => {
this.handle_event(data);
});
},
};
createApp(app_obj).mount();
</script>
</body>
</html>