Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=function&page=744&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 7804 results for "function"(571ms)

money_countermain.tsx7 matches

@arfan•Updated 3 months ago
3 SINGLE-FILE VAL CODE
4 1) Imports React, once.
5 2) Declares CSS + server() function
6 3) Declares the <App/> React component
7 4) Declares client() to mount <App/>
298
299/* ------------------------------------------------
300 2) server() function: returns the HTML skeleton
301------------------------------------------------ */
302export default async function server(request: Request): Promise<Response> {
303 return new Response(
304 `
328 3) The React App
329------------------------------------------------ */
330function App() {
331 // States for inputs
332 const [entryName, setEntryName] = useState("#");
365
366 // Helpers
367 function formatNumber(num) {
368 return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
369 }
370 function formatCurrency(num) {
371 return `$${num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, "$&,")}`;
372 }
897 4) Mount the React <App/> client-side
898------------------------------------------------ */
899function client() {
900 createRoot(document.getElementById("root")).render(<App />);
901}

tastefulIvoryWormmain.tsx1 match

@maxm•Updated 3 months ago
4 console.log("after 1s");
5});
6export default async function() {
7 console.log("from within export");
8}

bedtimeStoryMakermain.tsx1 match

@tmcw•Updated 3 months ago
36// );
37
38function parseStory(text) {
39 // Split the text into lines and remove empty lines
40 const lines = text.split("\n").filter(line => line.trim() !== "")

hopefulGoldChinchillamain.tsx11 matches

@charmaine•Updated 3 months ago
73const PoweredByInfo = "";
74
75function Hero({
76 prompt,
77 setPrompt,
94
95 <p className="text-[#bababa] text-center max-w-[25ch] mx-auto my-4 font-dm-sans">
96 Turn your ideas into fully functional apps in{" "}
97 <span className="relative w-fit text-fuchsia-400 z-10 italic font-semibold rounded-full">
98 less than a second
168}
169
170function App() {
171 const previewRef = React.useRef<HTMLDivElement>(null);
172 const [prompt, setPrompt] = useState("");
222 });
223
224 function handleStarterPromptClick(promptItem: typeof prompts[number]) {
225 setLoading(true);
226 setTimeout(() => handleSubmit(promptItem.prompt), 0);
227 }
228
229 async function handleSubmit(e: React.FormEvent | string) {
230 if (typeof e !== "string") {
231 e.preventDefault();
278 }
279
280 function handleVersionChange(direction: "back" | "forward") {
281 const { currentVersionIndex, versions } = versionHistory;
282 if (direction === "back" && currentVersionIndex > 0) {
994);
995
996function client() {
997 const path = window.location.pathname;
998 const root = createRoot(document.getElementById("root")!);
1030}
1031
1032function extractCodeFromFence(text: string): string {
1033 const htmlMatch = text.match(/```html\n([\s\S]*?)\n```/);
1034 return htmlMatch ? htmlMatch[1].trim() : text;
1035}
1036
1037async function generateCode(prompt: string, currentCode: string) {
1038 const starterPrompt = STARTER_PROMPTS.find(p => p.prompt === prompt);
1039 if (starterPrompt) {
1080}
1081
1082export default async function cerebras_coder(req: Request): Promise<Response> {
1083 // Dynamic import for SQLite to avoid client-side import
1084 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
1183 <meta property="og:site_name" content="Cerebras Coder">
1184 <meta property="og:url" content="https://cerebrascoder.com"/>
1185 <meta property="og:description" content="Turn your ideas into fully functional apps in less than a second – powered by Llama3.3-70b on Cerebras's super-fast wafer chips. Code is 100% open-source, hosted on Val Town."">
1186 <meta property="og:type" content="website">
1187 <meta property="og:image" content="https://stevekrouse-blob_admin.web.val.run/api/public/CerebrasCoderOG.jpg">

bluesky_bot_templatemain.tsx5 matches

@alexwein•Updated 3 months ago
6});
7
8// Helper function to convert data URI to Uint8Array
9function convertDataURIToUint8Array(dataURI: string): Uint8Array {
10 const base64Data = dataURI.split(",")[1];
11 const binaryString = atob(base64Data);
17}
18
19// Helper function to fetch SVG and convert to base64
20async function fetchSVGAsBase64(url: string): Promise<string> {
21 const response = await fetch(url);
22 if (!response.ok) {
27}
28
29export default async function(interval: Interval) {
30 // Don't forget to set these environment variables in the val's settings.
31 const username = process.env.BLUESKY_USERNAME;

kanbanTodoListmain.tsx16 matches

@stevekrouse•Updated 3 months ago
8import React, { useEffect, useState } from "https://esm.sh/react@18.2.0";
9
10function TaskBoard() {
11 const [taskLists, setTaskLists] = useState({
12 todo: [],
44 }, []);
45
46 function loadUserPreferences() {
47 const savedDarkMode = localStorage.getItem("app-theme") === "true";
48 setIsDarkMode(savedDarkMode);
59 }
60
61 function updateAppStyle(font, size) {
62 document.body.style.setProperty("--app-font", font);
63 document.body.style.setProperty("--app-font-size", `${size}px`);
64 }
65
66 function saveUserPreferences() {
67 localStorage.setItem("app-font", chosenFont);
68 localStorage.setItem("app-font-size", fontSize.toString());
72 }
73
74 async function fetchTasks() {
75 try {
76 const response = await fetch("/get-tasks");
82 }
83
84 async function addNewTask() {
85 if (!newTaskText.trim()) return;
86
102 }
103
104 async function handleTaskMove(result) {
105 const { destination, source, draggableId } = result;
106 if (!destination) return;
123 }
124
125 async function removeTask(taskId, column) {
126 try {
127 const response = await fetch("/delete-task", {
137 }
138
139 async function moveTaskForward(task, currentColumn) {
140 const currentIndex = listProgression.indexOf(currentColumn);
141 const nextColumn = listProgression[currentIndex + 1];
158 }
159
160 function toggleDarkMode() {
161 const newDarkMode = !isDarkMode;
162 setIsDarkMode(newDarkMode);
165 }
166
167 function openEditModal(task) {
168 setTaskBeingEdited(task);
169 setEditedTaskText(task.title);
171 }
172
173 async function saveEditedTask() {
174 if (!editedTaskText.trim() || !taskBeingEdited) return;
175 try {
191 }
192
193 function handleTaskInteraction(e, task, column) {
194 if (e.button === 1) {
195 e.preventDefault();
432}
433
434function client() {
435 createRoot(document.getElementById("root")).render(<TaskBoard />);
436}
439}
440
441export default async function server(request: Request): Promise<Response> {
442 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
443 const KEY = "kanbanTodoList";
517}
518
519async function getAllTasks(sqlite, KEY, SCHEMA_VERSION) {
520 const todo = await sqlite.execute(
521 `SELECT * FROM ${KEY}_tasks_${SCHEMA_VERSION} WHERE column = 'todo'`,

townieIllustratorPromptmain.tsx4 matches

@charmaine•Updated 3 months ago
3First ask a user what app they would like you to illustrate. Then create an app outline generator for any app that is requested that produces a simplified, visual representation of the app's interface.
4
5Core Functionality
6
7- Accept an app name as input (e.g., "Zoom", "Slack", "Discord")
8- Generate a single val that renders a minimal, branded mockup of the app's main interface
9- Allow the user to export a png screenshot with transparent background with rounded corners (8px radius)
10- Move the `html2canvas` import inside the `client()` function.
11- Wrap the `exportAsPNG` function in a `useEffect` hook to ensure it's only defined on the client-side.
12- Use dynamic import for `html2canvas` inside the `exportAsPNG` function.
13- Make sure html2canvas is only loaded and used on the client-side
14

townieIllustratorPromptREADME.md4 matches

@charmaine•Updated 3 months ago
6First ask a user what app they would like you to illustrate. Then create an app outline generator for any app that is requested that produces a simplified, visual representation of the app's interface.
7
8Core Functionality
9
10- Accept an app name as input (e.g., "Zoom", "Slack", "Discord")
11- Generate a single val that renders a minimal, branded mockup of the app's main interface
12- Allow the user to export a png screenshot with transparent background with rounded corners (8px radius)
13- Move the `html2canvas` import inside the `client()` function.
14- Wrap the `exportAsPNG` function in a `useEffect` hook to ensure it's only defined on the client-side.
15- Use dynamic import for `html2canvas` inside the `exportAsPNG` function.
16- Make sure html2canvas is only loaded and used on the client-side
17

blissfulBrownSmeltmain.tsx2 matches

@charmaine•Updated 3 months ago
34}
35
36async function detectTechnologies(email_address: string): Promise<ShovelResponse> {
37 const domain = email_address.split("@")[1];
38
57}
58
59export async function newUserWelcomeEmail(req: Request): Promise<Response> {
60 // if (req.method === "GET") return html(welcomeEmail);
61 if (req.headers.get("clerkNonSensitive") !== Deno.env.get("clerkNonSensitive"))

emailValHandlermain.tsx10 matches

@charmaine•Updated 3 months ago
3import { pdfText } from "jsr:@pdf/pdftext";
4
5// main controller function
6export async function emailValHandler(receivedEmail) {
7 const openaiUrl = "https://api.openai.com/v1/chat/completions";
8 const apiKey = Deno.env.get("OPENAI_API_KEY"); // replace this entire line with your OpenAI API key as a string, e.g., "sk-123..." or use environment variable: https://docs.val.town/reference/environment-variables/
48
49// extract attachments (if any)
50async function extractAttachments(email) {
51 if (!email.attachments || email.attachments.length === 0) {
52 return [];
64}
65
66async function extractPdfText(attachments) {
67 const pdfTexts = [];
68
97}
98
99// helper function to generate a prompt for openai
100function generatePrompt(email, pdfTexts, emailText) {
101 // extract the first name from the 'from' field if it exists
102 const senderName = email.from.split("<")[0].trim().split(" ")[0] || "";
121}
122
123// helper function to send a request to openai
124async function sendRequestToOpenAI(prompt, openaiUrl, apiKey, model) {
125 try {
126 // prepare the openai messages payload
161}
162
163// helper function to send a response back via email
164async function sendResponseByEmail(toEmail, responseContent) {
165 const subject = "AI Response to Your Email";
166 const text = `${responseContent}`;

getFileEmail4 file matches

@shouser•Updated 6 days ago
A helper function to build a file's email

TwilioHelperFunctions

@vawogbemi•Updated 2 months ago