Public
HTTP (deprecated)
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
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
/** @jsxImportSource https://esm.sh/react */
import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
const subreddits = ["IdiotsInCars"];
const fetchWithImage = async (subreddit: string) => {
const { data: { children } } = await fetchJSON(
`https://www.reddit.com/r/${subreddit}.json`,
);
const posts = children
.map((child: any) => child.data)
.filter((post: any) => post.post_hint === "image")
.map((post: any) => ({
title: post.title,
url: post.url,
score: post.score,
subreddit: post.subreddit,
}));
return posts;
};
const fetchAllReddits = async () => {
const posts = (await Promise.all(subreddits.map(fetchWithImage))).flat();
return posts;
};
function ImageGrid({ posts }) {
return (
<div className="image-grid">
{posts.map((post, index) => (
<div key={index} className="image-item">
<img src={post.url} alt={post.title} />
</div>
))}
</div>
);
}
function App() {
const [posts, setPosts] = useState<any[]>([]);
useEffect(() => {
fetch("/api/posts").then(ok => ok.json())
.then(posts => setPosts(posts));
}, []);
return (
<div>
<ImageGrid posts={posts} />
</div>
);
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") { client(); }
export default async function server(req: Request): Promise<Response> {
if (req.url.endsWith("/api/posts")) {
const posts = await fetchAllReddits();
posts.sort((a, b) => b.score - a.score);
return Response.json(posts);
}
return new Response(
`
<html>
<head>
<title>😍 pr0n</title>
<style>${css}</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="${import.meta.url}"></script>
</body>
</html>
`,
{
headers: {
"content-type": "text/html",
},
},
);
}
const css = `
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f0f0f0; }
h1 { text-align: center; color: #333; }
.image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }
.image-item { position: relative; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 8px rgba(0,0,0,0.1); transition: transform 0.3s ease; }
.image-item:hover { transform: scale(1.05); }
.image-item img { width: 100%; height: 250px; object-fit: cover; display: block; }
`;
yawnxyz-redditimagegrab.web.val.run
September 9, 2024