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/$%7BsvgDataUrl%7D?q=function&page=9&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 30501 results for "function"(2665ms)

tanstackReactHonoExampleREADME.md2 matches

@neverstew•Updated 17 hours ago
16In a normal server environment, you would likely use a middleware [like this one](https://hono.dev/docs/getting-started/nodejs#serve-static-files) to serve static files. Some frameworks or deployment platforms automatically make any content inside a `public/` folder public.
17
18However in Val Town you need to handle this yourself, and it can be suprisingly difficult to read and serve files in a Val Town Project. This template uses helper functions from [stevekrouse/utils/serve-public](https://www.val.town/x/stevekrouse/utils/branch/main/code/serve-public/README.md), which handle reading project files in a way that will work across branches and forks, automatically transpiles typescript to javascript, and assigns content-types based on the file's extension.
19
20### `index.html`
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors

tanstackReactHonoExampleREADME.md2 matches

@neverstew•Updated 17 hours ago
4
5* `migrations.ts` - code to set up the database tables the app needs
6* `queries.ts` - functions to run queries against those tables, which are imported and used in the main Hono server in `/backend/index.ts`
7
8## Migrations
18The queries file is where running the migrations happen in this app. It'd also be reasonable for that to happen in index.ts, or as is said above, for that line to be commented out, and only run when actual changes are made to your database schema.
19
20The queries file exports functions to get and write data. It relies on shared types and data imported from the `/shared` directory.

tanstackReactHonoExamplequeries.ts2 matches

@neverstew•Updated 17 hours ago
3
4// Fetch messages query
5export function useMessages(initialData?: Message[]) {
6 return useQuery({
7 queryKey: ["messages"],
20
21// Post message mutation
22export function usePostMessage() {
23 const queryClient = useQueryClient();
24

tanstackReactHonoExamplequeries.ts2 matches

@neverstew•Updated 17 hours ago
11await createTables();
12
13export async function getMessages(limit = MESSAGE_LIMIT) {
14 const messages = await db
15 .select()
22}
23
24export async function insertMessage(content: string) {
25 await db
26 .insert(schema.messages)

tanstackReactHonoExamplemigrations.ts1 match

@neverstew•Updated 17 hours ago
2import { db } from "./db.ts";
3
4export async function createTables() {
5 // Create messages table
6 await db.run(sql`

tanstackReactHonoExampleMessageInput.tsx1 match

@neverstew•Updated 17 hours ago
3import { usePostMessage } from "../lib/queries.ts";
4
5export function MessageInput() {
6 const [message, setMessage] = React.useState("");
7 const postMessage = usePostMessage();

tanstackReactHonoExampleApp.tsx3 matches

@neverstew•Updated 17 hours ago
5import { useMessages } from "../lib/queries.ts";
6
7export function App(
8 { initialMessages = [], thisProjectURL }: { initialMessages?: Message[]; thisProjectURL?: string },
9) {
48}
49
50function MessageList({ messages }: { messages: Message[] }) {
51 const displayedMessages = messages.slice(0, MESSAGE_LIMIT);
52 return (
57}
58
59function MessageItem({ message }) {
60 const formattedDate = new Date(message.timestamp).toLocaleString();
61

ChatHTMLRenderer.tsx6 matches

@c15r•Updated 17 hours ago
22 readResource: (serverName: string, uri: string) => Promise<string>;
23
24 // Utility functions
25 log: (level: "debug" | "info" | "warning" | "error", message: string, data?: any) => void;
26
40 * - Handles iframe communication via postMessage
41 */
42export default function HTMLRenderer({ html, mcpClients = [], className = "" }: HTMLRendererProps) {
43 const iframeRef = useRef<HTMLIFrameElement>(null);
44 const containerRef = useRef<HTMLDivElement>(null);
132 },
133
134 // Utility functions
135 log: (level: "debug" | "info" | "warning" | "error", message: string, data?: any) => {
136 console[level](`[HTMLRenderer] ${message}`, data);
154 }, [mcpClients, isFullscreen]);
155
156 // Fullscreen functionality
157 const enterFullscreen = useCallback(() => {
158 const container = containerRef.current;
218 const methodFunc = (mcpContext as any)[method];
219
220 if (typeof methodFunc !== "function") {
221 throw new Error(`Unknown MCP API method: ${method}`);
222 }
365 <script>
366 // Update fullscreen controls based on state
367 async function updateFullscreenControls() {
368 const controls = document.getElementById('fullscreenControls');
369 const isFs = await window.mcpContext.isFullscreen();

Work_Time_Calculator_2main.tsx7 matches

@willthereader•Updated 18 hours ago
1function parseTimeRanges(daySchedule) {
2 // console.log(`Parsing schedule: ${daySchedule}`);
3 const timeRanges = daySchedule.match(/(\d{1,2}(?::\d{2})?(?:am|pm)?)/g);
53}
54
55function convertTo24HourFormat(time) {
56 if (!time) {
57 throw new Error("Invalid time input: time is undefined or empty");
91}
92
93function calculateDuration(day, startTime, endTime) {
94 console.log(`calculateDuration: Calculating duration on ${day} from ${startTime} to ${endTime}`);
95 const start24 = convertTo24HourFormat(startTime);
112}
113
114function calculateDailyTotal(day, parsedSchedule) {
115 console.log(`calculateDailyTotal: Calculating daily total for ${day}`, parsedSchedule);
116 let totalMinutes = 0;
130}
131
132function calculateWeeklyTotal(day, dailyTotals) {
133 console.log(`calculateWeeklyTotal: Calculating weekly total for daily totals for ${day} is`, dailyTotals);
134 let totalHours = 0;
148}
149
150function isValidDay(day) {
151 const validDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
152 return validDays.includes(day.charAt(0).toUpperCase() + day.slice(1).toLowerCase());
153}
154
155function calculateWorkTime(schedule) {
156 const dailyTotals = [];
157 const scheduleArray = schedule.split("\n").filter(Boolean);

Todomain.tsx22 matches

@svc•Updated 18 hours ago
54 }.`;
55
56function generateHtmlShell(sourceUrl: string): string {
57 return `
58<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AuraTask - AI Todo</title>
72<div class="modal-overlay" id="chat-modal"><div class="modal-content"><div class="chat-header"><h3>Chat with Aura</h3></div><div id="chat-log"></div><form id="chat-form"><input type="text" id="chat-input" placeholder="Ask Aura to do something..." required><button type="submit" class="btn btn-primary">Send</button></form></div></div>
73<script>
74(function() {
75 const API_URL = '${sourceUrl}';
76 const STORE_KEYS = { projects: 'aura_projects_v1', tasks: 'aura_tasks_v1' };
83 const genId = () => Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
84
85 function checkTaskLoad() {
86 if (tasks.filter(t => !t.isCompleted).length >= ACTIVE_TASK_WARNING_THRESHOLD) {
87 return confirm("You have a lot of active tasks. Are you sure you want to add more? It might be a good time to complete some items first.");
90 }
91
92 function loadState() {
93 projects = getStore(STORE_KEYS.projects);
94 tasks = getStore(STORE_KEYS.tasks);
99 }
100
101 function render() {
102 renderSidebar();
103 renderTaskList();
105 }
106
107 function toggleLoading(btn, show) {
108 if (!btn) return;
109 isLoading = show;
112 }
113
114 function updateUIElements() {
115 const todayStr = new Date().toISOString().split("T")[0];
116 const todayTasks = tasks.filter(t => !t.isCompleted && t.dueDate === todayStr);
126 }
127
128 function renderSidebar() {
129 const mainViews = [
130 {id:'today',name:'Today',icon:'M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1z'},
135 }
136
137 function renderTaskList() {
138 const container = $("#task-list");
139 let filteredTasks = [], title = 'Tasks';
158 }
159
160 function renderChatLog() {
161 const log = $("#chat-log");
162 log.innerHTML = conversationHistory.map((msg, idx) => {
170 }
171
172 function addMessageToChat(sender, text, plan = null, requiresConfirmation = false) {
173 conversationHistory.push({ sender, text, plan, requiresConfirmation });
174 renderChatLog();
175 }
176
177 function executePlan(plan) {
178 plan.forEach(action => {
179 if (action.operation === 'CREATE_TASK') {
191 }
192
193 function handleAddTask(e) {
194 e.preventDefault();
195 if (!checkTaskLoad()) return;
204 }
205
206 function handleTaskClick(e) {
207 const target = e.target, taskItem = target.closest(".task-item");
208 if (!taskItem) return;
223 }
224
225 function openEditModal(task) {
226 $("#edit-task-id").value = task.id;
227 $("#edit-task-content").value = task.content;
232 }
233
234 function handleUpdateTask(e) {
235 e.preventDefault();
236 const taskId = $("#edit-task-id").value, task = tasks.find(t => t.id === taskId);
245 }
246
247 async function handleChatSubmit(e) {
248 e.preventDefault();
249 const input = $("#chat-input"), userMessage = input.value.trim();
268 }
269
270 function handlePlanConfirm(e) {
271 const action = e.target.dataset.planAction, idx = e.target.dataset.planIdx;
272 if (!action || !idx) return;
277 }
278
279 async function triggerProjectSynthesis() {
280 if (!checkTaskLoad()) return;
281 const goal = $("#synthesis-goal-input").value.trim();
307 }
308
309 async function triggerDailyRebalance() {
310 const todayStr = new Date().toISOString().split("T")[0];
311 const todayTasks = tasks.filter(t => !t.isCompleted && t.dueDate === todayStr);
339 }
340
341 function bindEventListeners() {
342 document.body.addEventListener('click', e => {
343 if (e.target.closest('[data-view]')) {
371}
372
373export default async function(req: Request): Promise<Response> {
374 const openai = new OpenAI();
375 const url = new URL(req.url);
tuna

tuna9 file matches

@jxnblk•Updated 1 week ago
Simple functional CSS library for Val Town

getFileEmail4 file matches

@shouser•Updated 1 month ago
A helper function to build a file's email
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.