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
53
54
55
56
57
58
59
60
/** This code sets up a simple comment box system with Tailwind CSS styling for a prettier interface.
* Leverages Deno's blob storage for persistence,
* Renders an HTML form to accept new comments,
* and displays all existing comments.
*/
import { blob } from "https://esm.town/v/std/blob";
// Key for blob storage
const COMMENTS_KEY = "comments_storage";
// HTML template for the form and comments list
const getHtml = (comments: string[]) => `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comment Box</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="flex items-center justify-center min-h-screen bg-gray-100">
<div class="bg-white p-8 rounded shadow-md w-full max-w-lg">
<h1 class="text-2xl font-bold mb-4">Comment Box</h1>
<form method="POST" class="mb-6">
<textarea name="comment" rows="4" class="w-full p-2 border rounded mb-4" placeholder="Write a comment..."></textarea>
<button type="submit" class="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600">Submit</button>
</form>
<h2 class="text-xl font-semibold mb-2">Previous Comments:</h2>
<ul class="space-y-4">
${comments.map(comment => `<li class="p-4 border rounded shadow-sm">"${comment}"</li>`).join('')}
</ul>
</div>
</body>
</html>
`;
export default async function main(req: Request): Promise<Response> {
// Fetch existing comments
let comments: string[] = await blob.getJSON(COMMENTS_KEY) || [];
if (req.method === "POST") {
const formData = await req.formData();
const newComment = formData.get("comment")?.toString().trim();
if (newComment) {
// Append the new comment and save to blob storage
comments.push(newComment);
await blob.setJSON(COMMENTS_KEY, comments);
// Redirect to avoid resubmission on page refresh
return Response.redirect(new URL(req.url).origin);
}
}
// Return the HTML with comments
return new Response(getHtml(comments), {
headers: { "Content-Type": "text/html" }
});
}
janpaul123-valle_tmp_679889573882008811461733353061443.web.val.run
July 17, 2024