Public
Script
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
import { chatMessages } from "https://esm.town/v/beshkenadze/chatMessages";
// https://api.val.town/express/@beshkenadze.chat
export const chat = (req, res) => {
const messages = chatMessages
.map(
({ message, sender }) =>
`<li><span class="font-semibold text-gray-900">${sender}: </span>${message}</li>`
)
.reverse()
.join("");
res.set("Content-Type", "text/html");
res.send(`
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<script>
const handleSend = async () => {
const sender = document.getElementById("sender-input").value || "Anonymous";
const message = document.getElementById("message-input").value;
document.getElementById("message-input").value = '';
const ul = document.getElementById("inbox");
const data = await fetch("https://api.val.town/eval/@nimalu.sendChatMessage('" + message + "','"+ sender + "')")
.then(res => res.json())
.then(res => res.data)
ul.innerHTML = data.reverse().map(
({ message, sender }) =>
'<li><span class="font-semibold text-gray-900">' + sender + ': </span>' + message + '</li>'
).join('')
}
</script>
</head>
<body class="bg-gray-100 text-gray-900 flex items-center justify-center h-screen w-screen">
<div class="p-4 shadow-xl rounded-lg bg-white">
<h1 class="text-fuchsia-600 font-bold text-xl mb-2">Val Town Chat</h1>
<ul id="inbox" class="flex flex-col gap-2 text-gray-500">
${messages}
</ul>
<div class="mt-4 flex justify-between gap-2">
<input id="sender-input" value="Anonymous" class="px-2 py-1 border rouned" placeholder="David">
<input id="message-input" class="px-2 py-1 border rouned" placeholder="Type in your message">
<button onclick="handleSend()" class="bg-fuchsia-600 font-bold text-white px-2 py-1 rounded hover:bg-fuchsia-500 focus:ring">Send</button>
</div>
</div>
</body>
</html>
`);
};
October 23, 2023