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
/** This code sets up a styled comment box system using Tailwind CSS.
* It leverages Deno's blob storage for persistence,
* and renders an HTML form to accept new comments,
* while displaying 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[]) => `
<html>
<head>
<title>Comment Box</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white shadow-lg rounded-lg p-6 w-full max-w-md">
<h1 class="text-2xl font-bold mb-4">Comment Box</h1>
<form method="POST" class="mb-4">
<textarea name="comment" rows="4" class="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Type your comment here..."></textarea><br />
<button type="submit" class="mt-2 w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600">Submit</button>
</form>
<h2 class="text-xl font-semibold mb-2">Previous Comments:</h2>
<ul class="space-y-2">
${comments.map(comment => `<li class="bg-gray-200 p-2 rounded">${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" }
});
}