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=757&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 24488 results for "function"(1714ms)

blob_adminapp.tsx7 matches

@stevekrouse•Updated 4 weeks ago
10}
11
12function Tooltip({ children, content }: TooltipProps) {
13 const [isVisible, setIsVisible] = useState(false);
14 const tooltipRef = useRef<HTMLDivElement>(null);
49}
50
51function formatBytes(bytes: number, decimals = 2) {
52 if (bytes === 0) return "0 Bytes";
53 const k = 1024;
58}
59
60function copyToClipboard(text: string) {
61 navigator.clipboard.writeText(text).then(() => {
62 console.log("Text copied to clipboard");
66}
67
68function ActionMenu({ blob, onDownload, onRename, onDelete, onMoveToPublic, onMoveOutOfPublic }) {
69 const [isOpen, setIsOpen] = useState(false);
70 const menuRef = useRef(null);
73
74 useEffect(() => {
75 function handleClickOutside(event) {
76 if (menuRef.current && !menuRef.current.contains(event.target)) {
77 event.stopPropagation();
155}
156
157function BlobItem({ blob, onSelect, isSelected, onDownload, onRename, onDelete, onMoveToPublic, onMoveOutOfPublic }) {
158 const [isLoading, setIsLoading] = useState(false);
159 const decodedKey = decodeURIComponent(blob.key);
216}
217
218function App({ initialEmail, initialProfile, sourceURL }) {
219 const encodeKey = (key: string) => encodeURIComponent(key);
220 const decodeKey = (key: string) => decodeURIComponent(key);

storymain.tsx24 matches

@Get•Updated 4 weeks ago
55];
56
57// --- OpenAI Generation Function ---
58// Asynchronously fetches race data from OpenAI's Chat Completion API.
59async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
60 // Initialize the OpenAI client (using API key from Val Town secrets)
61 // Ensure the 'openai' secret is configured in your Val Town settings.
174
175// --- Main HTTP Handler (Val Town Entry Point) ---
176// This function handles incoming HTTP requests and returns the HTML for the game.
177export default async function server(request: Request): Promise<Response> {
178 // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error.
179 const activeRaceData = await generateRaceDataWithOpenAI();
525// CLIENT-SIDE LOGIC (JavaScript - runs in the browser)
526// =============================================================================
527(function() {
528 'use strict';
529
625 let availableChallenges = [];
626
627 // --- Core Functions ---
628
629 /** Creates the race cards and adds listeners */
630 function createCards() {
631 carouselTrack.innerHTML = ''; // Clear loading message
632 cardElements = [];
681
682 /** Handles clicking the active card to select race */
683 function handleCardClick(e) {
684 if (gameState.phase !== 'selecting_race' || isTransitioning) return;
685
700
701 /** Updates card positions and applies classes */
702 function updateCardPositions(useTransition = true) {
703 if (!cardElements.length) return;
704 isTransitioning = useTransition;
744
745 /** Creates spark effects originating near the center */
746 function createSparks(effectContainer, numSparks = NUM_SPARKS_SUCCESS) {
747 if (!effectContainer) return;
748 const cardElement = effectContainer.parentElement;
787
788 /** Triggers visual effects on the active card */
789 function triggerEffect(type = 'success') {
790 const activeCard = cardElements[currentIndex];
791 if (!activeCard) return;
838
839 /** Moves carousel during selection phase */
840 function moveCarousel(direction) {
841 if (gameState.phase !== 'selecting_race' || isTransitioning || cardElements.length <= 1) return;
842 const numCards = cardElements.length;
846
847 /** Navigates directly to a specific card index during selection */
848 function navigateToIndex(index) {
849 if (gameState.phase !== 'selecting_race' || isTransitioning || index === currentIndex || index < 0 || index >= cardElements.length) return;
850 currentIndex = index;
852 }
853
854 // --- NEW: Game Logic Functions ---
855
856 /** Starts the adventure game */
857 function startGame(raceName, effectColor) {
858 if (gameState.phase !== 'selecting_race') return; // Prevent restarting mid-game
859
892
893 /** Updates the Score, Multiplier, Lives display */
894 function updateGameUI() {
895 scoreDisplay.textContent = \`Score: \${gameState.score}\`;
896 multiplierDisplay.textContent = \`x\${gameState.multiplier.toFixed(1)}\`;
899
900 /** Selects and displays the next challenge */
901 function presentNextChallenge() {
902 if (gameState.lives <= 0 || gameState.phase === 'game_over') return; // Should be caught earlier, but safety check
903
922
923 /** Handles the outcome of a challenge swipe */
924 function handleChallengeOutcome(swipeDirection) {
925 if (gameState.phase !== 'facing_challenge' || !gameState.currentChallenge) return;
926
965
966 /** Ends the game and shows the final score */
967 function gameOver() {
968 console.log("--- Game Over ---");
969 gameState.phase = 'game_over';
979 // --- Event Handlers ---
980
981 function handleDragStart(e) {
982 // Prevent dragging if game is over or during specific transitions
983 if (gameState.phase === 'game_over' || gameState.phase === 'starting_game') return;
1010 }
1011
1012 function handleDragMove(e) {
1013 if (!isDragging) return;
1014
1026 }
1027
1028 function handleDragEnd(e) {
1029 if (!isDragging) return;
1030 isDragging = false;
1077
1078 /** Attaches global event listeners */
1079 function addGlobalListeners() {
1080 console.log("Client Script: Adding global listeners...");
1081 // Keyboard Input
1122
1123 // --- Initialization ---
1124 function init() {
1125 console.log("Client Script: Initializing adventure...");
1126 challengeText.textContent = "Loading Heroes..."; // Initial loading message
cerebras_coder

cerebras_coderstarter-prompts.js2 matches

@Parvezalam6•Updated 4 weeks ago
4 "title": "Todo App",
5 "code":
6 "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Task Master</title>\n <link href=\"https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css\" rel=\"stylesheet\">\n</head>\n<body class=\"bg-gray-100\">\n <div class=\"max-w-md mx-auto mt-12 p-6 rounded-lg shadow-md bg-white\">\n <div class=\"flex justify-between items-center mb-6\">\n <h2 class=\"text-2xl font-bold\">Task Master</h2>\n <span class=\"text-gray-600\">Manage your tasks efficiently</span>\n </div>\n <ul class=\"todo-list\" id=\"todo-list\"></ul>\n <div class=\"add-todo mt-6 flex justify-between items-center\">\n <input type=\"text\" id=\"todo-input\" placeholder=\"Add new task\" class=\"w-full py-2 pl-10 text-sm text-gray-800 border border-gray-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-gray-600 bg-gray-50\">\n <button type=\"button\" id=\"add-todo-btn\" class=\"ml-4 px-4 py-2 bg-green-500 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-green-700 hover:shadow-lg focus:bg-green-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-green-800 active:shadow-lg transition duration-150 ease-in-out\">Add Task</button>\n </div>\n <div class=\"mt-6 text-center text-gray-600\">\n Built on <a href=\"https://cerebrascoder.com\" target=\"_blank\" class=\"text-gray-900 underline\">Cerebras Coder</a>\n </div>\n </div>\n\n <script>\n // Get the todo list and add todo button elements\n const todoList = document.getElementById('todo-list');\n const addTodoBtn = document.getElementById('add-todo-btn');\n const todoInput = document.getElementById('todo-input');\n\n // Load todos from local storage\n let todos = JSON.parse(localStorage.getItem('todos')) || [];\n\n // Function to render the todo list\n function renderTodoList() {\n todoList.innerHTML = '';\n todos.forEach((todo, index) => {\n const todoItem = document.createElement('li');\n todoItem.innerHTML = `\n <div class=\"flex justify-between items-center py-4 border-b border-gray-300\">\n <div class=\"flex items-center\">\n <input type=\"checkbox\" id=\"todo-${index}\" class=\"mr-4\" ${todo.completed ? 'checked' : ''}>\n <span class=\"todo-text ${todo.completed ? 'text-gray-400 line-through' : 'text-gray-600'}\">${todo.text}</span>\n </div>\n <button type=\"button\" class=\"px-4 py-2 bg-red-500 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-red-700 hover:shadow-lg focus:bg-red-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-red-800 active:shadow-lg transition duration-150 ease-in-out delete-todo\" data-index=\"${index}\">Delete</button>\n </div>\n `;\n todoList.appendChild(todoItem);\n });\n }\n\n // Render the initial todo list\n renderTodoList();\n\n // Add event listener to the add todo button\n addTodoBtn.addEventListener('click', () => {\n const todoText = todoInput.value.trim();\n if (todoText) {\n todos.push({ text: todoText, completed: false });\n localStorage.setItem('todos', JSON.stringify(todos));\n todoInput.value = '';\n renderTodoList();\n }\n });\n\n // Add event listener to the todo list\n todoList.addEventListener('change', (e) => {\n if (e.target.type === 'checkbox') {\n const index = parseInt(e.target.id.split('-')[1]);\n todos[index].completed = e.target.checked;\n localStorage.setItem('todos', JSON.stringify(todos));\n renderTodoList();\n }\n });\n\n // Add event listener to the delete todo buttons\n todoList.addEventListener('click', (e) => {\n if (e.target.classList.contains('delete-todo')) {\n const index = parseInt(e.target.dataset.index);\n todos.splice(index, 1);\n localStorage.setItem('todos', JSON.stringify(todos));\n renderTodoList();\n }\n });\n </script>\n</body>\n</html>",
7 "performance": {
8 "tokensPerSecond": 2298.56,
26 "title": "Markdown Editor",
27 "code":
28 "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Markdown Editor</title>\n <link href=\"https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css\" rel=\"stylesheet\">\n</head>\n<body class=\"bg-white\">\n <div class=\"max-w-full mx-auto p-4 pt-6 md:p-6 lg:p-8\">\n <h1 class=\"text-3xl text-center mb-4\">Markdown Editor</h1>\n <div class=\"flex flex-row\">\n <div class=\"editor p-4 rounded-lg border border-gray-200 w-full md:w-1/2\">\n <textarea id=\"editor\" class=\"w-full h-screen p-2 border border-gray-200 rounded-lg\" placeholder=\"Type your Markdown here...\"></textarea>\n </div>\n <div class=\"preview p-4 rounded-lg border border-gray-200 w-full md:w-1/2 ml-2 md:ml-4 lg:ml-8\">\n <div id=\"preview\"></div>\n </div>\n </div>\n <p class=\"text-center mt-4\">Built on <a href=\"https://cerebrascoder.com\">Cerebras Coder</a></p>\n </div>\n\n <script>\n const editor = document.getElementById('editor');\n const preview = document.getElementById('preview');\n\n // Initialize textarea with default markdown\n const defaultMarkdown = `\n# Introduction to Markdown\nMarkdown is a lightweight markup language that is easy to read and write. It is often used for formatting text in plain text editors, chat applications, and even web pages.\n\n## Headers\nHeaders are denoted by the # symbol followed by a space. The number of # symbols determines the level of the header:\n# Heading 1\n## Heading 2\n### Heading 3\n\n## Emphasis\nYou can use emphasis to make your text **bold** or *italic*:\n*Italics*\n**Bold**\n\n## Lists\nYou can use lists to organize your text:\n* Item 1\n* Item 2\n* Item 3\nOr\n1. Item 1\n2. Item 2\n3. Item 3\n\n## Links\nYou can use links to reference external resources:\n[Google](https://www.google.com)\n\n## Images\nYou can use images to add visual content:\n![Markdown Logo](https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Markdown-mark.svg/208px-Markdown-mark.svg.png)\n`;\n editor.value = defaultMarkdown;\n\n // Update preview on input\n editor.addEventListener('input', () => {\n const markdown = editor.value;\n const html = markdownToHtml(markdown);\n preview.innerHTML = html;\n });\n\n // Initialize preview with default markdown\n const defaultHtml = markdownToHtml(defaultMarkdown);\n preview.innerHTML = defaultHtml;\n\n // Function to convert Markdown to HTML\n function markdownToHtml(markdown) {\n // Bold\n markdown = markdown.replace(/\\*\\*(.*?)\\*\\*/g, '<b>$1</b>');\n\n // Italic\n markdown = markdown.replace(/\\*(.*?)\\*/g, '<i>$1</i>');\n\n // Links\n markdown = markdown.replace(/\\[(.*?)\\]\\((.*?)\\)/g, '<a href=\"$2\">$1</a>');\n\n // Images\n markdown = markdown.replace(/!\\[(.*?)\\]\\((.*?)\\)/g, '<img src=\"$2\" alt=\"$1\">');\n\n // Headings\n markdown = markdown.replace(/(^#{1,6} )(.*)/gm, (match, level, text) => {\n return `<h${level.length}>${text}</h${level.length}>`;\n });\n\n // Lists\n markdown = markdown.replace(/^(\\*|\\d+\\.) (.*)/gm, (match, marker, text) => {\n if (marker.startsWith('*')) {\n return `<li>${text}</li>`;\n } else {\n return `<li>${text}</li>`;\n }\n });\n\n // Line breaks\n markdown = markdown.replace(/\\n/g, '<br>');\n\n // Fix for nested lists\n markdown = markdown.replace(/<li><li>/g, '<li>');\n markdown = markdown.replace(/<\\/li><\\/li>/g, '</li>');\n\n // Wrap lists in ul\n markdown = markdown.replace(/(<li>.*<\\/li>)/g, '<ul>$1</ul>');\n\n return markdown;\n }\n </script>\n</body>\n</html>",
29 "performance": {
30 "tokensPerSecond": 4092.96,
cerebras_coder

cerebras_coderqueries.ts5 matches

@Parvezalam6•Updated 4 weeks ago
2import { ITERATIONS_TABLE, KEY, PROJECTS_TABLE, SCHEMA_VERSION } from "./migrations.ts";
3
4export async function createProject(prompt: string) {
5 const projectResult = await sqlite.execute(
6 `INSERT INTO ${PROJECTS_TABLE} (initial_prompt) VALUES (?)`,
11}
12
13export async function getNextVersionNumber(projectId: number) {
14 const data = await sqlite.execute(
15 `SELECT version_number FROM ${ITERATIONS_TABLE}
21}
22
23export async function insertVersion(projectId: number, versionNumber: number, prompt: string, code: string) {
24 await sqlite.execute(
25 `INSERT INTO ${ITERATIONS_TABLE}
29}
30
31export async function getCodeInner(table: string, project: string, version?: string) {
32 let data;
33 if (version === undefined) {
50}
51
52export async function getCode(project: string, version?: string) {
53 // try to get code in the new table partition first
54 const code = await getCodeInner(ITERATIONS_TABLE, project, version);
cerebras_coder

cerebras_codermigrations.ts1 match

@Parvezalam6•Updated 4 weeks ago
7export const ITERATIONS_TABLE = "cerebras_coder_iterations";
8
9export async function createTables() {
10 await sqlite.execute(`
11 CREATE TABLE IF NOT EXISTS ${PROJECTS_TABLE} (
cerebras_coder

cerebras_codermain.tsx1 match

@Parvezalam6•Updated 4 weeks ago
6await createTables();
7
8export default async function cerebras_coder(req: Request): Promise<Response> {
9 if (req.method === "POST") {
10 let { prompt, currentCode, versionHistory, projectId } = await req.json();
cerebras_coder

cerebras_coderindex.ts7 matches

@Parvezalam6•Updated 4 weeks ago
23);
24
25function Hero({
26 prompt,
27 setPrompt,
44
45 <p className="text-[#bababa] text-center max-w-[25ch] mx-auto my-4 font-dm-sans">
46 Turn your ideas into fully functional apps in{" "}
47 <span className="relative w-fit text-fuchsia-400 z-10 italic font-semibold rounded-full">
48 less than a second
115}
116
117function App() {
118 const previewRef = React.useRef<HTMLDivElement>(null);
119 const [prompt, setPrompt] = useState("");
169 });
170
171 function handleStarterPromptClick(promptItem: typeof prompts[number]) {
172 setLoading(true);
173 setTimeout(() => handleSubmit(promptItem.prompt), 0);
174 }
175
176 async function handleSubmit(e: React.FormEvent | string) {
177 if (typeof e !== "string") {
178 e.preventDefault();
225 }
226
227 function handleVersionChange(direction: "back" | "forward") {
228 const { currentVersionIndex, versions } = versionHistory;
229 if (direction === "back" && currentVersionIndex > 0) {
973);
974
975function client() {
976 const path = window.location.pathname;
977 const root = createRoot(document.getElementById("root")!);
cerebras_coder

cerebras_coderindex.html1 match

@Parvezalam6•Updated 4 weeks ago
19 <meta property="og:site_name" content="Cerebras Coder">
20 <meta property="og:url" content="https://cerebrascoder.com"/>
21 <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."">
22 <meta property="og:type" content="website">
23 <meta property="og:image" content="https://stevekrouse-blob_admin.web.val.run/api/public/CerebrasCoderOG.jpg">
cerebras_coder

cerebras_codergenerate-code.ts2 matches

@Parvezalam6•Updated 4 weeks ago
2import STARTER_PROMPTS from "../public/starter-prompts.js";
3
4function extractCodeFromFence(text: string): string {
5 const htmlMatch = text.match(/```html\n([\s\S]*?)\n```/);
6 return htmlMatch ? htmlMatch[1].trim() : text;
7}
8
9export async function generateCode(prompt: string, currentCode: string) {
10 const starterPrompt = STARTER_PROMPTS.find(p => p.prompt === prompt);
11 if (starterPrompt) {

guidemain.tsx15 matches

@Get•Updated 4 weeks ago
58];
59
60// --- OpenAI Generation Function ---
61// Asynchronously fetches race data from OpenAI's Chat Completion API.
62async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
63 // Initialize the OpenAI client (using API key from Val Town secrets)
64 const openai = new OpenAI();
144
145// --- Main HTTP Handler (Val Town Entry Point) ---
146// This function handles incoming HTTP requests and returns an HTML response.
147export default async function server(request: Request): Promise<Response> {
148 // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error.
149 const activeRaceData = await generateRaceDataWithOpenAI();
375// CLIENT-SIDE LOGIC (JavaScript - runs in the browser)
376// =============================================================================
377(function() {
378 'use strict'; // Enforce stricter parsing and error handling
379
406
407 // --- DOM Elements ---
408 // Select crucial elements needed for the carousel to function.
409 const carouselContainer = document.getElementById(CAROUSEL_CONTAINER_ID);
410 const carouselTrack = document.getElementById(CAROUSEL_TRACK_ID);
432 let cardElements = []; // Array to hold references to the created card DOM elements
433
434 // --- Core Functions ---
435
436 /**
437 * Creates the race cards based on the raceData and appends them to the carousel track.
438 */
439 function createCards() {
440 console.log("Client Script: createCards() called. Data:", raceData);
441 // Clear any existing content and reset the card elements array
504 * @param {boolean} useTransition - Whether to apply CSS transitions (true) or update instantly (false).
505 */
506 function updateCardPositions(useTransition = true) {
507 if (!cardElements.length) return; // Don't do anything if no cards exist
508
598 * @param {HTMLElement} effectContainer - The container element for the effects.
599 */
600 function createSparks(effectContainer) {
601 if (!effectContainer) return;
602 const cardElement = effectContainer.parentElement; // Get the parent card
644 * @param {'next' | 'prev'} direction - The direction to move the carousel.
645 */
646 function moveCarousel(direction) {
647 // Prevent moving if already transitioning or if there's only one card
648 if (isTransitioning || cardElements.length <= 1) return;
658 // --- Event Handlers ---
659
660 function handleDragStart(e) {
661 if (isTransitioning) return; // Ignore drags during transitions
662 // Prevent dragging text/images on the page
675 }
676
677 function handleDragMove(e) {
678 if (!isDragging) return;
679
696 }
697
698 function handleDragEnd(e) {
699 if (!isDragging) return; // Make sure drag actually started
700
727 * Attaches all necessary event listeners for user interaction.
728 */
729 function addEventListeners() {
730 console.log("Client Script: Adding event listeners...");
731 // --- Keyboard Navigation ---

getFileEmail4 file matches

@shouser•Updated 1 month ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 1 month ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.