repo
stringlengths
7
64
file_url
stringlengths
81
338
file_path
stringlengths
5
257
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:25:31
2026-01-05 01:50:38
truncated
bool
2 classes
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/related-prompts/route.ts
src/app/api/admin/related-prompts/route.ts
import { NextResponse } from "next/server"; import { Prisma } from "@prisma/client"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { findAndSaveRelatedPrompts } from "@/lib/ai/embeddings"; import { getConfig } from "@/lib/config"; export async function POST() { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Check if user is admin const user = await db.user.findUnique({ where: { id: session.user.id }, select: { role: true }, }); if (user?.role !== "ADMIN") { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } // Check if AI search is enabled const config = await getConfig(); if (!config.features.aiSearch) { return NextResponse.json( { error: "AI search is not enabled" }, { status: 400 } ); } // Get all public prompts with embeddings const prompts = await db.prompt.findMany({ where: { isPrivate: false, isUnlisted: false, deletedAt: null, embedding: { not: Prisma.DbNull }, }, select: { id: true }, orderBy: { createdAt: "desc" }, }); if (prompts.length === 0) { return NextResponse.json({ error: "No prompts to process" }, { status: 400 }); } // Create a streaming response const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(controller) { let success = 0; let failed = 0; for (let i = 0; i < prompts.length; i++) { const prompt = prompts[i]; try { await findAndSaveRelatedPrompts(prompt.id); success++; } catch (error) { console.error(`Failed to generate related prompts for ${prompt.id}:`, error); failed++; } // Send progress update const progress = { current: i + 1, total: prompts.length, success, failed, }; controller.enqueue(encoder.encode(`data: ${JSON.stringify(progress)}\n\n`)); } // Send final result const result = { done: true, success, failed }; controller.enqueue(encoder.encode(`data: ${JSON.stringify(result)}\n\n`)); controller.close(); }, }); return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); } catch (error) { console.error("Related prompts generation error:", error); return NextResponse.json( { error: "Failed to generate related prompts" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/reports/[id]/route.ts
src/app/api/admin/reports/[id]/route.ts
import { NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const updateSchema = z.object({ status: z.enum(["PENDING", "REVIEWED", "DISMISSED"]), }); export async function PATCH( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; const body = await request.json(); const { status } = updateSchema.parse(body); const report = await db.promptReport.update({ where: { id }, data: { status }, }); return NextResponse.json(report); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json({ error: "Invalid data" }, { status: 400 }); } console.error("Report update error:", error); return NextResponse.json({ error: "Internal server error" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/webhooks/route.ts
src/app/api/admin/webhooks/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Prisma } from "@prisma/client"; const VALID_METHODS = ["GET", "POST", "PUT", "PATCH"] as const; const VALID_EVENTS = ["PROMPT_CREATED", "PROMPT_UPDATED", "PROMPT_DELETED"] as const; type WebhookInput = { name: string; url: string; method?: string; headers?: Record<string, string>; payload: string; events: string[]; isEnabled?: boolean; }; function validateWebhook(body: unknown): { success: true; data: WebhookInput } | { success: false; error: string } { if (!body || typeof body !== "object") { return { success: false, error: "Invalid request body" }; } const data = body as Record<string, unknown>; if (!data.name || typeof data.name !== "string" || data.name.length < 1 || data.name.length > 100) { return { success: false, error: "Name is required (1-100 characters)" }; } if (!data.url || typeof data.url !== "string") { return { success: false, error: "URL is required" }; } try { new URL(data.url); } catch { return { success: false, error: "Invalid URL" }; } const method = (data.method as string) || "POST"; if (!VALID_METHODS.includes(method as typeof VALID_METHODS[number])) { return { success: false, error: "Invalid method" }; } if (!data.payload || typeof data.payload !== "string" || data.payload.length < 1) { return { success: false, error: "Payload is required" }; } if (!Array.isArray(data.events) || data.events.length === 0) { return { success: false, error: "At least one event is required" }; } for (const event of data.events) { if (!VALID_EVENTS.includes(event as typeof VALID_EVENTS[number])) { return { success: false, error: `Invalid event: ${event}` }; } } return { success: true, data: { name: data.name as string, url: data.url as string, method, headers: data.headers as Record<string, string> | undefined, payload: data.payload as string, events: data.events as string[], isEnabled: data.isEnabled !== false, }, }; } // GET all webhooks export async function GET() { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const webhooks = await db.webhookConfig.findMany({ orderBy: { createdAt: "desc" }, }); return NextResponse.json(webhooks); } catch (error) { console.error("Get webhooks error:", error); return NextResponse.json({ error: "server_error" }, { status: 500 }); } } // CREATE webhook export async function POST(request: Request) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const body = await request.json(); const parsed = validateWebhook(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: parsed.error }, { status: 400 } ); } const createData: Record<string, unknown> = { name: parsed.data.name, url: parsed.data.url, method: parsed.data.method || "POST", headers: parsed.data.headers || Prisma.JsonNull, payload: parsed.data.payload, events: parsed.data.events, isEnabled: parsed.data.isEnabled ?? true, }; const webhook = await db.webhookConfig.create({ data: createData as Prisma.WebhookConfigCreateInput, }); return NextResponse.json(webhook); } catch (error) { console.error("Create webhook error:", error); return NextResponse.json({ error: "server_error" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/webhooks/[id]/route.ts
src/app/api/admin/webhooks/[id]/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Prisma } from "@prisma/client"; const VALID_METHODS = ["GET", "POST", "PUT", "PATCH"]; const VALID_EVENTS = ["PROMPT_CREATED", "PROMPT_UPDATED", "PROMPT_DELETED"]; interface UpdateWebhookData { name?: string; url?: string; method?: string; headers?: Record<string, string> | null; payload?: string; events?: string[]; isEnabled?: boolean; } function validateUpdateWebhook(body: unknown): { success: true; data: UpdateWebhookData } | { success: false; error: string } { if (typeof body !== "object" || body === null) { return { success: false, error: "Invalid request body" }; } const data = body as Record<string, unknown>; const result: UpdateWebhookData = {}; if (data.name !== undefined) { if (typeof data.name !== "string" || data.name.length < 1 || data.name.length > 100) { return { success: false, error: "Name must be a string between 1 and 100 characters" }; } result.name = data.name; } if (data.url !== undefined) { if (typeof data.url !== "string") { return { success: false, error: "URL must be a string" }; } try { new URL(data.url); } catch { return { success: false, error: "Invalid URL format" }; } result.url = data.url; } if (data.method !== undefined) { if (typeof data.method !== "string" || !VALID_METHODS.includes(data.method)) { return { success: false, error: `Method must be one of: ${VALID_METHODS.join(", ")}` }; } result.method = data.method; } if (data.headers !== undefined) { if (data.headers !== null && typeof data.headers !== "object") { return { success: false, error: "Headers must be an object or null" }; } result.headers = data.headers as Record<string, string> | null; } if (data.payload !== undefined) { if (typeof data.payload !== "string" || data.payload.length < 1) { return { success: false, error: "Payload must be a non-empty string" }; } result.payload = data.payload; } if (data.events !== undefined) { if (!Array.isArray(data.events) || !data.events.every(e => typeof e === "string" && VALID_EVENTS.includes(e))) { return { success: false, error: `Events must be an array of: ${VALID_EVENTS.join(", ")}` }; } result.events = data.events; } if (data.isEnabled !== undefined) { if (typeof data.isEnabled !== "boolean") { return { success: false, error: "isEnabled must be a boolean" }; } result.isEnabled = data.isEnabled; } return { success: true, data: result }; } // GET single webhook export async function GET( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const { id } = await params; const webhook = await db.webhookConfig.findUnique({ where: { id }, }); if (!webhook) { return NextResponse.json({ error: "not_found" }, { status: 404 }); } return NextResponse.json(webhook); } catch (error) { console.error("Get webhook error:", error); return NextResponse.json({ error: "server_error" }, { status: 500 }); } } // UPDATE webhook export async function PATCH( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const { id } = await params; const body = await request.json(); const validation = validateUpdateWebhook(body); if (!validation.success) { return NextResponse.json( { error: "validation_error", details: validation.error }, { status: 400 } ); } // Build update data with proper Prisma types const updateData: Record<string, unknown> = { ...validation.data }; if (validation.data.headers === null) { updateData.headers = Prisma.JsonNull; } const webhook = await db.webhookConfig.update({ where: { id }, data: updateData as Prisma.WebhookConfigUpdateInput, }); return NextResponse.json(webhook); } catch (error) { console.error("Update webhook error:", error); return NextResponse.json({ error: "server_error" }, { status: 500 }); } } // DELETE webhook export async function DELETE( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const { id } = await params; await db.webhookConfig.delete({ where: { id }, }); return NextResponse.json({ success: true }); } catch (error) { console.error("Delete webhook error:", error); return NextResponse.json({ error: "server_error" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/webhooks/[id]/test/route.ts
src/app/api/admin/webhooks/[id]/test/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; export async function POST( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } const { id } = await params; // Get the webhook configuration const webhook = await db.webhookConfig.findUnique({ where: { id }, }); if (!webhook) { return NextResponse.json({ error: "Webhook not found" }, { status: 404 }); } // Replace placeholders with test values (must match WEBHOOK_PLACEHOLDERS) let payload = webhook.payload; const siteUrl = process.env.NEXT_PUBLIC_APP_URL || "https://prompts.chat"; const testData: Record<string, string> = { "{{PROMPT_ID}}": "test-prompt-id-12345", "{{PROMPT_TITLE}}": "Test Prompt Title", "{{PROMPT_DESCRIPTION}}": "This is a test description for the webhook.", "{{PROMPT_CONTENT}}": "This is the test prompt content. It demonstrates how your webhook will receive data when a new prompt is created.", "{{PROMPT_TYPE}}": "TEXT", "{{PROMPT_URL}}": `${siteUrl}/prompts/test-prompt-id-12345`, "{{PROMPT_MEDIA_URL}}": "https://example.com/media/test-image.png", "{{AUTHOR_USERNAME}}": "testuser", "{{AUTHOR_NAME}}": "Test User", "{{AUTHOR_AVATAR}}": "https://avatars.githubusercontent.com/u/1234567", "{{CATEGORY_NAME}}": "Development", "{{TAGS}}": "testing, webhook, automation", "{{TIMESTAMP}}": new Date().toLocaleDateString("en-US", { weekday: "short", year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }), "{{SITE_URL}}": siteUrl, "{{CHATGPT_URL}}": `https://chat.openai.com/?prompt=${encodeURIComponent("This is the test prompt content. It demonstrates how your webhook will receive data when a new prompt is created.")}`, }; for (const [placeholder, value] of Object.entries(testData)) { payload = payload.replaceAll(placeholder, value); } // Parse the payload as JSON let parsedPayload; try { parsedPayload = JSON.parse(payload); } catch { return NextResponse.json( { error: "Invalid JSON payload" }, { status: 400 } ); } // Send the test request const response = await fetch(webhook.url, { method: webhook.method, headers: { "Content-Type": "application/json", ...(webhook.headers as Record<string, string> | null), }, body: webhook.method !== "GET" ? JSON.stringify(parsedPayload) : undefined, }); if (!response.ok) { const text = await response.text(); return NextResponse.json( { error: `Webhook returned ${response.status}: ${text}` }, { status: 400 } ); } return NextResponse.json({ success: true }); } catch (error) { console.error("Test webhook error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to test webhook" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/prompts/route.ts
src/app/api/admin/prompts/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // GET - List all prompts for admin with pagination and search export async function GET(request: NextRequest) { try { const session = await auth(); // Check if user is authenticated if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "Authentication required" }, { status: 401 } ); } // Check if user is admin if (session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "Admin access required" }, { status: 403 } ); } const { searchParams } = new URL(request.url); const page = parseInt(searchParams.get("page") || "1"); const limit = parseInt(searchParams.get("limit") || "20"); const search = searchParams.get("search") || ""; const sortBy = searchParams.get("sortBy") || "createdAt"; const sortOrder = searchParams.get("sortOrder") || "desc"; const filter = searchParams.get("filter") || "all"; // Validate pagination const validPage = Math.max(1, page); const validLimit = Math.min(Math.max(1, limit), 100); const skip = (validPage - 1) * validLimit; // Build filter conditions type WhereCondition = { OR?: Array<{ title?: { contains: string; mode: "insensitive" }; content?: { contains: string; mode: "insensitive" } }>; isUnlisted?: boolean; isPrivate?: boolean; isFeatured?: boolean; deletedAt?: { not: null } | null; reports?: { some: object }; }; const filterConditions: WhereCondition = {}; switch (filter) { case "unlisted": filterConditions.isUnlisted = true; break; case "private": filterConditions.isPrivate = true; break; case "featured": filterConditions.isFeatured = true; break; case "deleted": filterConditions.deletedAt = { not: null }; break; case "reported": filterConditions.reports = { some: {} }; break; case "public": filterConditions.isPrivate = false; filterConditions.isUnlisted = false; filterConditions.deletedAt = null; break; default: // "all" - no filter break; } // Build where clause combining search and filters const where: WhereCondition = { ...filterConditions, ...(search && { OR: [ { title: { contains: search, mode: "insensitive" as const } }, { content: { contains: search, mode: "insensitive" as const } }, ], }), }; // Build orderBy const validSortFields = ["createdAt", "updatedAt", "title", "viewCount"]; const orderByField = validSortFields.includes(sortBy) ? sortBy : "createdAt"; const orderByDirection = sortOrder === "asc" ? "asc" : "desc"; // Fetch prompts and total count const [prompts, total] = await Promise.all([ db.prompt.findMany({ where, skip, take: validLimit, orderBy: { [orderByField]: orderByDirection }, select: { id: true, title: true, slug: true, type: true, isPrivate: true, isUnlisted: true, isFeatured: true, viewCount: true, createdAt: true, updatedAt: true, deletedAt: true, author: { select: { id: true, username: true, name: true, avatar: true, }, }, category: { select: { id: true, name: true, slug: true, }, }, _count: { select: { votes: true, reports: true, }, }, }, }), db.prompt.count({ where }), ]); return NextResponse.json({ prompts, pagination: { page: validPage, limit: validLimit, total, totalPages: Math.ceil(total / validLimit), }, }); } catch (error) { console.error("Admin list prompts error:", error); return NextResponse.json( { error: "server_error", message: "Failed to fetch prompts" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/prompts/[id]/route.ts
src/app/api/admin/prompts/[id]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // DELETE - Hard delete a prompt (admin only) export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); // Check if user is authenticated if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "Authentication required" }, { status: 401 } ); } // Check if user is admin if (session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "Admin access required" }, { status: 403 } ); } const { id } = await params; // Validate prompt ID if (!id || typeof id !== "string") { return NextResponse.json( { error: "invalid_request", message: "Valid prompt ID is required" }, { status: 400 } ); } // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id }, select: { id: true, title: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Hard delete the prompt (cascades to related records due to schema relations) await db.prompt.delete({ where: { id }, }); return NextResponse.json({ success: true, message: "Prompt deleted successfully", deletedPrompt: { id: prompt.id, title: prompt.title, }, }); } catch (error) { console.error("Admin delete prompt error:", error); return NextResponse.json( { error: "server_error", message: "Failed to delete prompt" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/categories/route.ts
src/app/api/admin/categories/route.ts
import { NextRequest, NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // Create category export async function POST(request: NextRequest) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const body = await request.json(); const { name, slug, description, icon, parentId, pinned } = body; if (!name || !slug) { return NextResponse.json({ error: "Name and slug are required" }, { status: 400 }); } const category = await db.category.create({ data: { name, slug, description: description || null, icon: icon || null, parentId: parentId || null, pinned: pinned || false, }, }); revalidateTag("categories", "max"); return NextResponse.json(category); } catch (error) { console.error("Error creating category:", error); return NextResponse.json({ error: "Failed to create category" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/categories/[id]/route.ts
src/app/api/admin/categories/[id]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // Update category export async function PATCH( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; const body = await request.json(); const { name, slug, description, icon, parentId, pinned } = body; const category = await db.category.update({ where: { id }, data: { ...(name && { name }), ...(slug && { slug }), description: description ?? undefined, icon: icon ?? undefined, parentId: parentId === null ? null : (parentId || undefined), ...(typeof pinned === "boolean" && { pinned }), }, }); revalidateTag("categories", "max"); return NextResponse.json(category); } catch (error) { console.error("Error updating category:", error); return NextResponse.json({ error: "Failed to update category" }, { status: 500 }); } } // Delete category export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; await db.category.delete({ where: { id }, }); revalidateTag("categories", "max"); return NextResponse.json({ success: true }); } catch (error) { console.error("Error deleting category:", error); return NextResponse.json({ error: "Failed to delete category" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/users/route.ts
src/app/api/admin/users/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // GET - List all users for admin with pagination and search export async function GET(request: NextRequest) { try { const session = await auth(); // Check if user is authenticated if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "Authentication required" }, { status: 401 } ); } // Check if user is admin if (session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "Admin access required" }, { status: 403 } ); } const { searchParams } = new URL(request.url); const page = parseInt(searchParams.get("page") || "1"); const limit = parseInt(searchParams.get("limit") || "20"); const search = searchParams.get("search") || ""; const sortBy = searchParams.get("sortBy") || "createdAt"; const sortOrder = searchParams.get("sortOrder") || "desc"; const filter = searchParams.get("filter") || "all"; // Validate pagination const validPage = Math.max(1, page); const validLimit = Math.min(Math.max(1, limit), 100); const skip = (validPage - 1) * validLimit; // Build filter conditions type WhereCondition = { OR?: Array<{ email?: { contains: string; mode: "insensitive" }; username?: { contains: string; mode: "insensitive" }; name?: { contains: string; mode: "insensitive" } }>; role?: "ADMIN" | "USER"; verified?: boolean; flagged?: boolean; }; const filterConditions: WhereCondition = {}; switch (filter) { case "admin": filterConditions.role = "ADMIN"; break; case "user": filterConditions.role = "USER"; break; case "verified": filterConditions.verified = true; break; case "unverified": filterConditions.verified = false; break; case "flagged": filterConditions.flagged = true; break; default: // "all" - no filter break; } // Build where clause combining search and filters const where: WhereCondition = { ...filterConditions, ...(search && { OR: [ { email: { contains: search, mode: "insensitive" as const } }, { username: { contains: search, mode: "insensitive" as const } }, { name: { contains: search, mode: "insensitive" as const } }, ], }), }; // Build orderBy const validSortFields = ["createdAt", "email", "username", "name"]; const orderByField = validSortFields.includes(sortBy) ? sortBy : "createdAt"; const orderByDirection = sortOrder === "asc" ? "asc" : "desc"; // Fetch users and total count const [users, total] = await Promise.all([ db.user.findMany({ where, skip, take: validLimit, orderBy: { [orderByField]: orderByDirection }, select: { id: true, email: true, username: true, name: true, avatar: true, role: true, verified: true, flagged: true, flaggedAt: true, flaggedReason: true, dailyGenerationLimit: true, generationCreditsRemaining: true, createdAt: true, _count: { select: { prompts: true, }, }, }, }), db.user.count({ where }), ]); return NextResponse.json({ users, pagination: { page: validPage, limit: validLimit, total, totalPages: Math.ceil(total / validLimit), }, }); } catch (error) { console.error("Admin list users error:", error); return NextResponse.json( { error: "server_error", message: "Failed to fetch users" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/users/[id]/route.ts
src/app/api/admin/users/[id]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // Update user (role change or verification) export async function PATCH( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; const body = await request.json(); const { role, verified, flagged, flaggedReason, dailyGenerationLimit } = body; // Build update data const updateData: { role?: "ADMIN" | "USER"; verified?: boolean; flagged?: boolean; flaggedAt?: Date | null; flaggedReason?: string | null; dailyGenerationLimit?: number; generationCreditsRemaining?: number; } = {}; if (role !== undefined) { if (!["ADMIN", "USER"].includes(role)) { return NextResponse.json({ error: "Invalid role" }, { status: 400 }); } updateData.role = role; } if (verified !== undefined) { updateData.verified = verified; } if (flagged !== undefined) { updateData.flagged = flagged; if (flagged) { updateData.flaggedAt = new Date(); updateData.flaggedReason = flaggedReason || null; } else { updateData.flaggedAt = null; updateData.flaggedReason = null; } } if (dailyGenerationLimit !== undefined) { const limit = parseInt(dailyGenerationLimit, 10); if (isNaN(limit) || limit < 0) { return NextResponse.json({ error: "Invalid daily generation limit" }, { status: 400 }); } updateData.dailyGenerationLimit = limit; // Also reset remaining credits to the new limit updateData.generationCreditsRemaining = limit; } const user = await db.user.update({ where: { id }, data: updateData, select: { id: true, email: true, username: true, name: true, avatar: true, role: true, verified: true, flagged: true, flaggedAt: true, flaggedReason: true, dailyGenerationLimit: true, generationCreditsRemaining: true, createdAt: true, }, }); return NextResponse.json(user); } catch (error) { console.error("Error updating user:", error); return NextResponse.json({ error: "Failed to update user" }, { status: 500 }); } } // Delete user export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; // Don't allow deleting yourself if (id === session.user.id) { return NextResponse.json({ error: "Cannot delete yourself" }, { status: 400 }); } await db.user.delete({ where: { id }, }); return NextResponse.json({ success: true }); } catch (error) { console.error("Error deleting user:", error); return NextResponse.json({ error: "Failed to delete user" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/admin/embeddings/route.ts
src/app/api/admin/embeddings/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { generateAllEmbeddings, isAISearchEnabled } from "@/lib/ai/embeddings"; export async function POST(request: NextRequest) { try { const session = await auth(); if (!session?.user || session.user.role !== "ADMIN") { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const enabled = await isAISearchEnabled(); if (!enabled) { return NextResponse.json( { error: "AI Search is not enabled or OPENAI_API_KEY is not set" }, { status: 400 } ); } // Check if regenerate mode const { searchParams } = new URL(request.url); const regenerate = searchParams.get("regenerate") === "true"; // Create a streaming response for progress updates const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(controller) { try { const result = await generateAllEmbeddings( (current, total, success, failed) => { const progress = JSON.stringify({ current, total, success, failed, done: false }); controller.enqueue(encoder.encode(`data: ${progress}\n\n`)); }, regenerate ); const final = JSON.stringify({ ...result, done: true }); controller.enqueue(encoder.encode(`data: ${final}\n\n`)); controller.close(); } catch (error) { const errorMsg = JSON.stringify({ error: "Failed to generate embeddings", done: true }); controller.enqueue(encoder.encode(`data: ${errorMsg}\n\n`)); controller.close(); } }, }); return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", }, }); } catch (error) { console.error("Generate embeddings error:", error); return NextResponse.json( { error: "Failed to generate embeddings" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/reports/route.ts
src/app/api/reports/route.ts
import { NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const reportSchema = z.object({ promptId: z.string().min(1), reason: z.enum(["SPAM", "INAPPROPRIATE", "COPYRIGHT", "MISLEADING", "RELIST_REQUEST", "OTHER"]), details: z.string().optional(), }); export async function POST(request: Request) { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const body = await request.json(); const { promptId, reason, details } = reportSchema.parse(body); // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { id: true, authorId: true }, }); if (!prompt) { return NextResponse.json({ error: "Prompt not found" }, { status: 404 }); } // Prevent self-reporting (except for relist requests) if (prompt.authorId === session.user.id && reason !== "RELIST_REQUEST") { return NextResponse.json( { error: "You cannot report your own prompt" }, { status: 400 } ); } // Check if user already reported this prompt const existingReport = await db.promptReport.findFirst({ where: { promptId, reporterId: session.user.id, status: "PENDING", }, }); if (existingReport) { return NextResponse.json( { error: "You have already reported this prompt" }, { status: 400 } ); } // Create the report await db.promptReport.create({ data: { promptId, reporterId: session.user.id, reason, details: details || null, }, }); return NextResponse.json({ success: true }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json( { error: "Invalid request data" }, { status: 400 } ); } console.error("Report creation error:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/upload/route.ts
src/app/api/upload/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { getStoragePlugin } from "@/lib/plugins/registry"; import sharp from "sharp"; const MAX_IMAGE_SIZE = 4 * 1024 * 1024; // 4MB for images const MAX_VIDEO_SIZE = 4 * 1024 * 1024; // 4MB for videos (Vercel serverless limit) const ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]; const ALLOWED_VIDEO_TYPES = ["video/mp4"]; async function compressToJpg(buffer: Buffer): Promise<Buffer> { return await sharp(buffer) .jpeg({ quality: 90, mozjpeg: true }) .toBuffer(); } export async function POST(request: NextRequest) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const enabledStorage = process.env.ENABLED_STORAGE || "url"; if (enabledStorage === "url") { return NextResponse.json( { error: "File upload is not enabled. Using URL storage mode." }, { status: 400 } ); } const storagePlugin = getStoragePlugin(enabledStorage); if (!storagePlugin) { return NextResponse.json( { error: `Storage plugin "${enabledStorage}" not found` }, { status: 500 } ); } if (!storagePlugin.isConfigured()) { return NextResponse.json( { error: `Storage plugin "${enabledStorage}" is not configured` }, { status: 500 } ); } try { const formData = await request.formData(); const file = formData.get("file") as File | null; if (!file) { return NextResponse.json({ error: "No file provided" }, { status: 400 }); } // Determine if file is image or video const isImage = ALLOWED_IMAGE_TYPES.includes(file.type); const isVideo = ALLOWED_VIDEO_TYPES.includes(file.type); // Validate file type if (!isImage && !isVideo) { return NextResponse.json( { error: "Invalid file type. Only JPEG, PNG, GIF, WebP images and MP4 videos are allowed." }, { status: 400 } ); } // Validate file size based on type const maxSize = isVideo ? MAX_VIDEO_SIZE : MAX_IMAGE_SIZE; if (file.size > maxSize) { return NextResponse.json( { error: `File too large. Maximum size is 4MB.` }, { status: 400 } ); } // Convert to buffer const arrayBuffer = await file.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); // Generate filename const timestamp = Date.now(); const randomId = Math.random().toString(36).substring(2, 8); let uploadBuffer: Buffer; let filename: string; let mimeType: string; if (isVideo) { // For videos, upload as-is without compression uploadBuffer = buffer; filename = `prompt-media-${timestamp}-${randomId}.mp4`; mimeType = "video/mp4"; } else { // For images, compress to JPG uploadBuffer = await compressToJpg(buffer); filename = `prompt-media-${timestamp}-${randomId}.jpg`; mimeType = "image/jpeg"; } // Upload to storage const result = await storagePlugin.upload(uploadBuffer, { filename, mimeType, folder: "prompt-media", }); return NextResponse.json({ url: result.url, size: result.size, }); } catch (error) { console.error("Upload error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Upload failed" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/route.ts
src/app/api/prompts/route.ts
import { NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { triggerWebhooks } from "@/lib/webhook"; import { generatePromptEmbedding, findAndSaveRelatedPrompts } from "@/lib/ai/embeddings"; import { generatePromptSlug } from "@/lib/slug"; import { checkPromptQuality } from "@/lib/ai/quality-check"; import { isSimilarContent, normalizeContent } from "@/lib/similarity"; const promptSchema = z.object({ title: z.string().min(1).max(200), description: z.string().max(500).optional(), content: z.string().min(1), type: z.enum(["TEXT", "IMAGE", "VIDEO", "AUDIO", "SKILL"]), // Output type or SKILL structuredFormat: z.enum(["JSON", "YAML"]).nullish(), // Input type indicator categoryId: z.string().optional(), tagIds: z.array(z.string()), contributorIds: z.array(z.string()).optional(), isPrivate: z.boolean(), mediaUrl: z.string().url().optional().or(z.literal("")), requiresMediaUpload: z.boolean().optional(), requiredMediaType: z.enum(["IMAGE", "VIDEO", "DOCUMENT"]).optional(), requiredMediaCount: z.number().int().min(1).max(10).optional(), }); // Create prompt export async function POST(request: Request) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const body = await request.json(); const parsed = promptSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: "Invalid input", details: parsed.error.issues }, { status: 400 } ); } const { title, description, content, type, structuredFormat, categoryId, tagIds, contributorIds, isPrivate, mediaUrl, requiresMediaUpload, requiredMediaType, requiredMediaCount } = parsed.data; // Check if user is flagged (for auto-delisting and daily limit) const currentUser = await db.user.findUnique({ where: { id: session.user.id }, select: { flagged: true }, }); const isUserFlagged = currentUser?.flagged ?? false; // Daily limit for flagged users: 5 prompts per day if (isUserFlagged) { const startOfDay = new Date(); startOfDay.setHours(0, 0, 0, 0); const todayPromptCount = await db.prompt.count({ where: { authorId: session.user.id, createdAt: { gte: startOfDay }, }, }); if (todayPromptCount >= 5) { return NextResponse.json( { error: "daily_limit", message: "You have reached the daily limit of 5 prompts" }, { status: 429 } ); } } // Rate limit: Check if user created a prompt in the last 30 seconds const thirtySecondsAgo = new Date(Date.now() - 30 * 1000); const recentPrompt = await db.prompt.findFirst({ where: { authorId: session.user.id, createdAt: { gte: thirtySecondsAgo }, }, select: { id: true }, }); if (recentPrompt) { return NextResponse.json( { error: "rate_limit", message: "Please wait 30 seconds before creating another prompt" }, { status: 429 } ); } // Check for duplicate title or content from the same user const userDuplicate = await db.prompt.findFirst({ where: { authorId: session.user.id, deletedAt: null, OR: [ { title: { equals: title, mode: "insensitive" } }, { content: content }, ], }, select: { id: true, slug: true, title: true }, }); if (userDuplicate) { return NextResponse.json( { error: "duplicate_prompt", message: "You already have a prompt with the same title or content", existingPromptId: userDuplicate.id, existingPromptSlug: userDuplicate.slug, }, { status: 409 } ); } // Check for similar content system-wide (any user) // First, get a batch of public prompts to check similarity against const normalizedNewContent = normalizeContent(content); // Only check if normalized content has meaningful length if (normalizedNewContent.length > 50) { // Get recent public prompts to check for similarity (limit to avoid performance issues) const publicPrompts = await db.prompt.findMany({ where: { deletedAt: null, isPrivate: false, }, select: { id: true, slug: true, title: true, content: true, author: { select: { username: true } } }, orderBy: { createdAt: "desc" }, take: 1000, // Check against last 1000 public prompts }); // Find similar content using our similarity algorithm const similarPrompt = publicPrompts.find(p => isSimilarContent(content, p.content)); if (similarPrompt) { return NextResponse.json( { error: "content_exists", message: "A prompt with similar content already exists", existingPromptId: similarPrompt.id, existingPromptSlug: similarPrompt.slug, existingPromptTitle: similarPrompt.title, existingPromptAuthor: similarPrompt.author.username, }, { status: 409 } ); } } // Generate slug from title (translated to English) const slug = await generatePromptSlug(title); // Create prompt with tags // Auto-delist if user is flagged const prompt = await db.prompt.create({ data: { title, slug, description: description || null, content, type, structuredFormat: structuredFormat || null, isPrivate, mediaUrl: mediaUrl || null, requiresMediaUpload: requiresMediaUpload || false, requiredMediaType: requiresMediaUpload ? requiredMediaType : null, requiredMediaCount: requiresMediaUpload ? requiredMediaCount : null, authorId: session.user.id, categoryId: categoryId || null, // Auto-delist prompts from flagged users ...(isUserFlagged && { isUnlisted: true, unlistedAt: new Date(), delistReason: "UNUSUAL_ACTIVITY", }), tags: { create: tagIds.map((tagId) => ({ tagId, })), }, ...(contributorIds && contributorIds.length > 0 && { contributors: { connect: contributorIds.map((id) => ({ id })), }, }), }, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: true, }, }, tags: { include: { tag: true, }, }, }, }); // Create initial version await db.promptVersion.create({ data: { promptId: prompt.id, version: 1, content, changeNote: "Initial version", createdBy: session.user.id, }, }); // Trigger webhooks for new prompt (non-blocking) if (!isPrivate) { triggerWebhooks("PROMPT_CREATED", { id: prompt.id, title: prompt.title, description: prompt.description, content: prompt.content, type: prompt.type, mediaUrl: prompt.mediaUrl, isPrivate: prompt.isPrivate, author: prompt.author, category: prompt.category, tags: prompt.tags, }); } // Generate embedding for AI search (non-blocking) // Only for public prompts - the function checks if aiSearch is enabled // After embedding is generated, find and save related prompts if (!isPrivate) { generatePromptEmbedding(prompt.id) .then(() => findAndSaveRelatedPrompts(prompt.id)) .catch((err) => console.error("Failed to generate embedding/related prompts for:", prompt.id, err) ); } // Run quality check for auto-delist (non-blocking for public prompts) // This runs in the background and will delist the prompt if quality issues are found if (!isPrivate) { console.log(`[Quality Check] Starting check for prompt ${prompt.id}`); checkPromptQuality(title, content, description).then(async (result) => { console.log(`[Quality Check] Result for prompt ${prompt.id}:`, JSON.stringify(result)); if (result.shouldDelist && result.reason) { console.log(`[Quality Check] Auto-delisting prompt ${prompt.id}: ${result.reason} - ${result.details}`); await db.prompt.update({ where: { id: prompt.id }, data: { isUnlisted: true, unlistedAt: new Date(), delistReason: result.reason, }, }); console.log(`[Quality Check] Prompt ${prompt.id} delisted successfully`); } }).catch((err) => { console.error("[Quality Check] Failed to run quality check for prompt:", prompt.id, err); }); } else { console.log(`[Quality Check] Skipped - prompt ${prompt.id} is private`); } // Revalidate caches (prompts, categories, tags counts change) revalidateTag("prompts", "max"); revalidateTag("categories", "max"); revalidateTag("tags", "max"); return NextResponse.json(prompt); } catch (error) { console.error("Create prompt error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // List prompts (for API access) export async function GET(request: Request) { try { const { searchParams } = new URL(request.url); const page = parseInt(searchParams.get("page") || "1"); const perPage = parseInt(searchParams.get("perPage") || "24"); const type = searchParams.get("type"); const categoryId = searchParams.get("category"); const tag = searchParams.get("tag"); const sort = searchParams.get("sort"); const q = searchParams.get("q"); const where: Record<string, unknown> = { isPrivate: false, isUnlisted: false, // Exclude unlisted prompts from public API deletedAt: null, // Exclude soft-deleted prompts }; if (type) { where.type = type; } if (categoryId) { where.categoryId = categoryId; } if (tag) { where.tags = { some: { tag: { slug: tag }, }, }; } if (q) { where.OR = [ { title: { contains: q, mode: "insensitive" } }, { content: { contains: q, mode: "insensitive" } }, { description: { contains: q, mode: "insensitive" } }, ]; } // Build order by clause // eslint-disable-next-line @typescript-eslint/no-explicit-any let orderBy: any = { createdAt: "desc" }; if (sort === "oldest") { orderBy = { createdAt: "asc" }; } else if (sort === "upvotes") { orderBy = { votes: { _count: "desc" } }; } const [promptsRaw, total] = await Promise.all([ db.prompt.findMany({ where, orderBy, skip: (page - 1) * perPage, take: perPage, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: { select: { id: true, name: true, slug: true }, }, }, }, tags: { include: { tag: true, }, }, contributors: { select: { id: true, username: true, name: true, avatar: true, }, }, _count: { select: { votes: true, contributors: true }, }, }, }), db.prompt.count({ where }), ]); // Transform to include voteCount and contributorCount, exclude internal fields const prompts = promptsRaw.map(({ embedding: _e, isPrivate: _p, isUnlisted: _u, unlistedAt: _ua, deletedAt: _d, ...p }) => ({ ...p, voteCount: p._count.votes, contributorCount: p._count.contributors, contributors: p.contributors, })); return NextResponse.json({ prompts, total, page, perPage, totalPages: Math.ceil(total / perPage), }); } catch (error) { console.error("List prompts error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/translate/route.ts
src/app/api/prompts/translate/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { translateContent } from "@/lib/ai/generation"; import { z } from "zod"; const translateSchema = z.object({ content: z.string().min(1), targetLanguage: z.string().min(1), }); export async function POST(request: NextRequest) { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "Unauthorized" }, { status: 401 } ); } try { const body = await request.json(); const { content, targetLanguage } = translateSchema.parse(body); const translatedContent = await translateContent(content, targetLanguage); return NextResponse.json({ translatedContent }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json( { error: "Invalid request body" }, { status: 400 } ); } console.error("Translation error:", error); return NextResponse.json( { error: "Failed to translate content" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/route.ts
src/app/api/prompts/[id]/route.ts
import { NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { generatePromptEmbedding, findAndSaveRelatedPrompts } from "@/lib/ai/embeddings"; import { generatePromptSlug } from "@/lib/slug"; import { checkPromptQuality } from "@/lib/ai/quality-check"; const updatePromptSchema = z.object({ title: z.string().min(1).max(200).optional(), description: z.string().max(500).optional(), content: z.string().min(1).optional(), type: z.enum(["TEXT", "IMAGE", "VIDEO", "AUDIO", "SKILL"]).optional(), // Output type or SKILL structuredFormat: z.enum(["JSON", "YAML"]).optional().nullable(), categoryId: z.string().optional().nullable(), tagIds: z.array(z.string()).optional(), contributorIds: z.array(z.string()).optional(), isPrivate: z.boolean().optional(), mediaUrl: z.string().url().optional().or(z.literal("")).nullable(), requiresMediaUpload: z.boolean().optional(), requiredMediaType: z.enum(["IMAGE", "VIDEO", "DOCUMENT"]).optional().nullable(), requiredMediaCount: z.number().int().min(1).max(10).optional().nullable(), }); // Get single prompt export async function GET( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await auth(); const prompt = await db.prompt.findUnique({ where: { id }, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: true, }, }, tags: { include: { tag: true, }, }, versions: { orderBy: { version: "desc" }, take: 10, }, _count: { select: { votes: true }, }, }, }); if (!prompt || prompt.deletedAt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Check if user can view private prompt if (prompt.isPrivate && prompt.authorId !== session?.user?.id) { return NextResponse.json( { error: "forbidden", message: "This prompt is private" }, { status: 403 } ); } // Check if logged-in user has voted let hasVoted = false; if (session?.user?.id) { const vote = await db.promptVote.findUnique({ where: { userId_promptId: { userId: session.user.id, promptId: id, }, }, }); hasVoted = !!vote; } // Omit embedding from response (it's large binary data) const { embedding: _embedding, ...promptWithoutEmbedding } = prompt; return NextResponse.json({ ...promptWithoutEmbedding, voteCount: prompt._count.votes, hasVoted, }); } catch (error) { console.error("Get prompt error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // Update prompt export async function PATCH( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } // Check if prompt exists and user owns it const existing = await db.prompt.findUnique({ where: { id }, select: { authorId: true, content: true }, }); if (!existing) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } if (existing.authorId !== session.user.id && session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "You can only edit your own prompts" }, { status: 403 } ); } const body = await request.json(); const parsed = updatePromptSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: "Invalid input", details: parsed.error.issues }, { status: 400 } ); } const { tagIds, contributorIds, categoryId, mediaUrl, title, ...data } = parsed.data; // Regenerate slug if title changed let newSlug: string | undefined; if (title) { newSlug = await generatePromptSlug(title); } // Convert empty strings to null for optional foreign keys const cleanedData = { ...data, ...(title && { title }), ...(newSlug && { slug: newSlug }), ...(categoryId !== undefined && { categoryId: categoryId || null }), ...(mediaUrl !== undefined && { mediaUrl: mediaUrl || null }), }; // Update prompt const prompt = await db.prompt.update({ where: { id }, data: { ...cleanedData, ...(tagIds && { tags: { deleteMany: {}, create: tagIds.map((tagId) => ({ tagId })), }, }), ...(contributorIds !== undefined && { contributors: { set: contributorIds.map((id) => ({ id })), }, }), }, include: { author: { select: { id: true, name: true, username: true, }, }, category: { include: { parent: true, }, }, tags: { include: { tag: true, }, }, }, }); // Create new version if content changed if (data.content && data.content !== existing.content) { const latestVersion = await db.promptVersion.findFirst({ where: { promptId: id }, orderBy: { version: "desc" }, }); await db.promptVersion.create({ data: { promptId: id, version: (latestVersion?.version || 0) + 1, content: data.content, changeNote: "Content updated", createdBy: session.user.id, }, }); } // Regenerate embedding if content, title, or description changed (non-blocking) // Only for public prompts - the function checks if aiSearch is enabled // After embedding is regenerated, update related prompts const contentChanged = data.content || title || data.description !== undefined; if (contentChanged && !prompt.isPrivate) { generatePromptEmbedding(id) .then(() => findAndSaveRelatedPrompts(id)) .catch((err) => console.error("Failed to regenerate embedding/related prompts for:", id, err) ); } // Run quality check for auto-delist on content changes (non-blocking) // Only for public prompts that aren't already delisted if (contentChanged && !prompt.isPrivate && !prompt.isUnlisted) { const checkTitle = title || prompt.title; const checkContent = data.content || prompt.content; const checkDescription = data.description !== undefined ? data.description : prompt.description; console.log(`[Quality Check] Starting check for updated prompt ${id}`); checkPromptQuality(checkTitle, checkContent, checkDescription).then(async (result) => { console.log(`[Quality Check] Result for prompt ${id}:`, JSON.stringify(result)); if (result.shouldDelist && result.reason) { console.log(`[Quality Check] Auto-delisting prompt ${id}: ${result.reason} - ${result.details}`); await db.prompt.update({ where: { id }, data: { isUnlisted: true, unlistedAt: new Date(), delistReason: result.reason, }, }); console.log(`[Quality Check] Prompt ${id} delisted successfully`); } }).catch((err) => { console.error("[Quality Check] Failed to run quality check for prompt:", id, err); }); } // Revalidate prompts cache revalidateTag("prompts", "max"); return NextResponse.json(prompt); } catch (error) { console.error("Update prompt error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // Soft delete prompt // - Admins can delete any prompt // - Owners can delete their own delisted prompts (auto-delisted for quality issues) export async function DELETE( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } // Check if prompt exists and get ownership/delist status const existing = await db.prompt.findUnique({ where: { id }, select: { id: true, deletedAt: true, authorId: true, isUnlisted: true, delistReason: true, }, }); if (!existing) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } if (existing.deletedAt) { return NextResponse.json( { error: "already_deleted", message: "Prompt is already deleted" }, { status: 400 } ); } const isAdmin = session.user.role === "ADMIN"; const isOwner = existing.authorId === session.user.id; const isDelisted = existing.isUnlisted && existing.delistReason; // Owners can only delete their own delisted prompts (quality issues) // Admins can delete any prompt if (!isAdmin && !(isOwner && isDelisted)) { return NextResponse.json( { error: "forbidden", message: isOwner ? "You can only delete prompts that have been delisted for quality issues. Contact an admin for other deletions." : "Prompts are released under CC0 and cannot be deleted. Contact an admin if there is an issue." }, { status: 403 } ); } // Soft delete by setting deletedAt timestamp await db.prompt.update({ where: { id }, data: { deletedAt: new Date() }, }); // Revalidate caches (prompts, categories, tags counts change) revalidateTag("prompts", "max"); revalidateTag("categories", "max"); revalidateTag("tags", "max"); return NextResponse.json({ success: true, message: isOwner && isDelisted ? "Delisted prompt deleted successfully" : "Prompt soft deleted" }); } catch (error) { console.error("Delete prompt error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/vote/route.ts
src/app/api/prompts/[id]/vote/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // POST - Upvote a prompt export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId } = await params; // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id: promptId }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Check if already voted const existing = await db.promptVote.findUnique({ where: { userId_promptId: { userId: session.user.id, promptId, }, }, }); if (existing) { return NextResponse.json( { error: "already_voted", message: "You have already upvoted this prompt" }, { status: 400 } ); } // Create vote await db.promptVote.create({ data: { userId: session.user.id, promptId, }, }); // Get updated vote count const voteCount = await db.promptVote.count({ where: { promptId }, }); return NextResponse.json({ voted: true, voteCount }); } catch (error) { console.error("Vote error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // DELETE - Remove upvote from a prompt export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId } = await params; // Delete vote await db.promptVote.deleteMany({ where: { userId: session.user.id, promptId, }, }); // Get updated vote count const voteCount = await db.promptVote.count({ where: { promptId }, }); return NextResponse.json({ voted: false, voteCount }); } catch (error) { console.error("Unvote error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/connections/route.ts
src/app/api/prompts/[id]/connections/route.ts
import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const createConnectionSchema = z.object({ targetId: z.string().min(1), label: z.string().min(1).max(100), order: z.number().int().min(0).optional(), }); interface RouteParams { params: Promise<{ id: string }>; } export async function GET(request: NextRequest, { params }: RouteParams) { const { id } = await params; try { const prompt = await db.prompt.findUnique({ where: { id, deletedAt: null }, select: { id: true, isPrivate: true, authorId: true }, }); if (!prompt) { return NextResponse.json({ error: "Prompt not found" }, { status: 404 }); } // Get all connections where this prompt is involved (source or target) // Exclude "related" label connections - those are for Related Prompts feature, not Prompt Flow const outgoingConnections = await db.promptConnection.findMany({ where: { sourceId: id, label: { not: "related" } }, orderBy: { order: "asc" }, include: { target: { select: { id: true, title: true, slug: true, isPrivate: true, authorId: true, }, }, }, }); const incomingConnections = await db.promptConnection.findMany({ where: { targetId: id, label: { not: "related" } }, orderBy: { order: "asc" }, include: { source: { select: { id: true, title: true, slug: true, isPrivate: true, authorId: true, }, }, }, }); // Filter out private prompts the user can't see const session = await auth(); const userId = session?.user?.id; const filteredOutgoing = outgoingConnections.filter( (c: typeof outgoingConnections[number]) => !c.target.isPrivate || c.target.authorId === userId ); const filteredIncoming = incomingConnections.filter( (c: typeof incomingConnections[number]) => !c.source.isPrivate || c.source.authorId === userId ); return NextResponse.json({ outgoing: filteredOutgoing, incoming: filteredIncoming, }); } catch (error) { console.error("Failed to fetch connections:", error); return NextResponse.json( { error: "Failed to fetch connections" }, { status: 500 } ); } } export async function POST(request: NextRequest, { params }: RouteParams) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id } = await params; try { const body = await request.json(); const { targetId, label, order } = createConnectionSchema.parse(body); // Verify source prompt exists and user owns it const sourcePrompt = await db.prompt.findUnique({ where: { id, deletedAt: null }, select: { authorId: true }, }); if (!sourcePrompt) { return NextResponse.json( { error: "Source prompt not found" }, { status: 404 } ); } if ( sourcePrompt.authorId !== session.user.id && session.user.role !== "ADMIN" ) { return NextResponse.json( { error: "You can only add connections to your own prompts" }, { status: 403 } ); } // Verify target prompt exists and belongs to the user const targetPrompt = await db.prompt.findUnique({ where: { id: targetId, deletedAt: null }, select: { id: true, title: true, authorId: true }, }); if (!targetPrompt) { return NextResponse.json( { error: "Target prompt not found" }, { status: 404 } ); } // Verify user owns the target prompt (users can only connect their own prompts) if ( targetPrompt.authorId !== session.user.id && session.user.role !== "ADMIN" ) { return NextResponse.json( { error: "You can only connect to your own prompts" }, { status: 403 } ); } // Prevent self-connection if (id === targetId) { return NextResponse.json( { error: "Cannot connect a prompt to itself" }, { status: 400 } ); } // Check if connection already exists const existing = await db.promptConnection.findUnique({ where: { sourceId_targetId: { sourceId: id, targetId } }, }); if (existing) { return NextResponse.json( { error: "Connection already exists" }, { status: 400 } ); } // Calculate order if not provided let connectionOrder = order; if (connectionOrder === undefined) { const lastConnection = await db.promptConnection.findFirst({ where: { sourceId: id }, orderBy: { order: "desc" }, select: { order: true }, }); connectionOrder = (lastConnection?.order ?? -1) + 1; } const connection = await db.promptConnection.create({ data: { sourceId: id, targetId, label, order: connectionOrder, }, include: { target: { select: { id: true, title: true, slug: true, }, }, }, }); return NextResponse.json(connection, { status: 201 }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json({ error: error.issues }, { status: 400 }); } console.error("Failed to create connection:", error); return NextResponse.json( { error: "Failed to create connection" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/connections/[connectionId]/route.ts
src/app/api/prompts/[id]/connections/[connectionId]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { revalidatePath } from "next/cache"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const updateConnectionSchema = z.object({ label: z.string().min(1).max(100).optional(), order: z.number().int().min(0).optional(), }); interface RouteParams { params: Promise<{ id: string; connectionId: string }>; } export async function DELETE(request: NextRequest, { params }: RouteParams) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id, connectionId } = await params; try { const connection = await db.promptConnection.findUnique({ where: { id: connectionId }, include: { source: { select: { authorId: true }, }, }, }); if (!connection) { return NextResponse.json( { error: "Connection not found" }, { status: 404 } ); } if (connection.sourceId !== id) { return NextResponse.json( { error: "Connection does not belong to this prompt" }, { status: 400 } ); } if ( connection.source.authorId !== session.user.id && session.user.role !== "ADMIN" ) { return NextResponse.json( { error: "You can only delete connections from your own prompts" }, { status: 403 } ); } await db.promptConnection.delete({ where: { id: connectionId }, }); // Revalidate the prompt page cache revalidatePath(`/prompts/${id}`); return NextResponse.json({ success: true }); } catch (error) { console.error("Failed to delete connection:", error); return NextResponse.json( { error: "Failed to delete connection" }, { status: 500 } ); } } export async function PATCH(request: NextRequest, { params }: RouteParams) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id, connectionId } = await params; try { const body = await request.json(); const data = updateConnectionSchema.parse(body); const connection = await db.promptConnection.findUnique({ where: { id: connectionId }, include: { source: { select: { authorId: true }, }, }, }); if (!connection) { return NextResponse.json( { error: "Connection not found" }, { status: 404 } ); } if (connection.sourceId !== id) { return NextResponse.json( { error: "Connection does not belong to this prompt" }, { status: 400 } ); } if ( connection.source.authorId !== session.user.id && session.user.role !== "ADMIN" ) { return NextResponse.json( { error: "You can only update connections on your own prompts" }, { status: 403 } ); } const updated = await db.promptConnection.update({ where: { id: connectionId }, data, include: { target: { select: { id: true, title: true, slug: true, }, }, }, }); return NextResponse.json(updated); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json({ error: error.issues }, { status: 400 }); } console.error("Failed to update connection:", error); return NextResponse.json( { error: "Failed to update connection" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/restore/route.ts
src/app/api/prompts/[id]/restore/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; export async function POST( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Only admins can restore deleted prompts if (session.user.role !== "ADMIN") { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } const { id } = await params; // Check if prompt exists and is deleted const prompt = await db.prompt.findUnique({ where: { id }, select: { id: true, deletedAt: true }, }); if (!prompt) { return NextResponse.json({ error: "Prompt not found" }, { status: 404 }); } if (!prompt.deletedAt) { return NextResponse.json({ error: "Prompt is not deleted" }, { status: 400 }); } // Restore the prompt by setting deletedAt to null await db.prompt.update({ where: { id }, data: { deletedAt: null }, }); return NextResponse.json({ success: true }); } catch (error) { console.error("Restore prompt error:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/raw/route.ts
src/app/api/prompts/[id]/raw/route.ts
import { NextRequest, NextResponse } from "next/server"; import { db } from "@/lib/db"; type OutputFormat = "md" | "yml"; type FileType = "prompt" | "skill"; /** * Extracts the prompt ID, format, and file type from a URL parameter * Supports formats: "abc123.prompt.md", "abc123_some-slug.prompt.md", "abc123.prompt.yml" * Also supports: "abc123.SKILL.md", "abc123_some-slug.SKILL.md" (SKILL only has .md format) */ function parseIdParam(idParam: string): { id: string; format: OutputFormat; fileType: FileType } { let param = idParam; let format: OutputFormat = "md"; let fileType: FileType = "prompt"; if (param.endsWith(".SKILL.md")) { format = "md"; fileType = "skill"; param = param.slice(0, -".SKILL.md".length); } else if (param.endsWith(".prompt.yml")) { format = "yml"; param = param.slice(0, -".prompt.yml".length); } else if (param.endsWith(".prompt.md")) { format = "md"; param = param.slice(0, -".prompt.md".length); } // If the param contains an underscore, extract the ID (everything before first underscore) const underscoreIndex = param.indexOf("_"); if (underscoreIndex !== -1) { param = param.substring(0, underscoreIndex); } return { id: param, format, fileType }; } /** * Converts ${variable:default} placeholders to {{variable}} format */ function convertVariables(str: string): string { return str.replace(/\$\{([^}:]+)(?::[^}]*)?\}/g, "{{$1}}"); } /** * Escapes a string for YAML output */ function yamlEscape(str: string): string { if (str.includes("\n") || str.includes(":") || str.includes("#") || str.startsWith(" ")) { return `|\n${str.split("\n").map(line => ` ${line}`).join("\n")}`; } return str; } export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const { id: idParam } = await params; const { id, format, fileType } = parseIdParam(idParam); // Unlisted prompts are accessible via direct link (like YouTube unlisted videos) const prompt = await db.prompt.findFirst({ where: { id, deletedAt: null, isPrivate: false }, select: { title: true, description: true, content: true, type: true }, }); if (!prompt) { return new NextResponse("Prompt not found", { status: 404 }); } let output: string; let contentType: string; // Use skill format if requested via .SKILL.md URL or if prompt type is SKILL const isSkill = fileType === "skill" || prompt.type === "SKILL"; if (format === "yml") { // YAML format (only for regular prompts, not skills) const lines = [ `name: ${prompt.title}`, ]; if (prompt.description) { lines.push(`description: ${prompt.description}`); } lines.push( `model: openai/gpt-4o-mini`, `modelParameters:`, ` temperature: 0.5`, `messages:`, ` - role: system`, ` content: ${yamlEscape(convertVariables(prompt.content))}`, ); output = lines.join("\n"); contentType = "text/yaml; charset=utf-8"; } else { if (isSkill) { // Format as SKILL.md (Agent Skills specification) const frontmatter = [ "---", `name: ${prompt.title}`, prompt.description ? `description: ${prompt.description}` : null, "---", ].filter(Boolean).join("\n"); output = `${frontmatter}\n\n${prompt.content}`; } else { // Format as markdown with YAML frontmatter const frontmatter = [ "---", `name: ${prompt.title}`, prompt.description ? `description: ${prompt.description}` : null, "---", ].filter(Boolean).join("\n"); output = `${frontmatter}\n${prompt.content}`; } contentType = "text/plain; charset=utf-8"; } return new NextResponse(output, { headers: { "Content-Type": contentType, }, }); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/pin/route.ts
src/app/api/prompts/[id]/pin/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const MAX_PINNED_PROMPTS = 3; export async function POST( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id: promptId } = await params; // Check if prompt exists and belongs to user const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { authorId: true, isPrivate: true }, }); if (!prompt) { return NextResponse.json({ error: "Prompt not found" }, { status: 404 }); } if (prompt.authorId !== session.user.id) { return NextResponse.json( { error: "You can only pin your own prompts" }, { status: 403 } ); } // Check if already pinned const existingPin = await db.pinnedPrompt.findUnique({ where: { userId_promptId: { userId: session.user.id, promptId, }, }, }); if (existingPin) { return NextResponse.json({ error: "Prompt already pinned" }, { status: 400 }); } // Check pin limit const pinnedCount = await db.pinnedPrompt.count({ where: { userId: session.user.id }, }); if (pinnedCount >= MAX_PINNED_PROMPTS) { return NextResponse.json( { error: `You can only pin up to ${MAX_PINNED_PROMPTS} prompts` }, { status: 400 } ); } // Get next order number const maxOrder = await db.pinnedPrompt.aggregate({ where: { userId: session.user.id }, _max: { order: true }, }); const nextOrder = (maxOrder._max.order ?? -1) + 1; // Create pin await db.pinnedPrompt.create({ data: { userId: session.user.id, promptId, order: nextOrder, }, }); return NextResponse.json({ success: true, pinned: true }); } catch (error) { console.error("Failed to pin prompt:", error); return NextResponse.json({ error: "Failed to pin prompt" }, { status: 500 }); } } export async function DELETE( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { id: promptId } = await params; // Delete the pin await db.pinnedPrompt.deleteMany({ where: { userId: session.user.id, promptId, }, }); return NextResponse.json({ success: true, pinned: false }); } catch (error) { console.error("Failed to unpin prompt:", error); return NextResponse.json({ error: "Failed to unpin prompt" }, { status: 500 }); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/feature/route.ts
src/app/api/prompts/[id]/feature/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // POST /api/prompts/[id]/feature - Toggle featured status (admin only) export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Check if user is admin const user = await db.user.findUnique({ where: { id: session.user.id }, select: { role: true }, }); if (user?.role !== "ADMIN") { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } const { id } = await params; // Get current prompt const prompt = await db.prompt.findUnique({ where: { id }, select: { isFeatured: true }, }); if (!prompt) { return NextResponse.json({ error: "Prompt not found" }, { status: 404 }); } // Toggle featured status const updatedPrompt = await db.prompt.update({ where: { id }, data: { isFeatured: !prompt.isFeatured, featuredAt: !prompt.isFeatured ? new Date() : null, }, }); return NextResponse.json({ success: true, isFeatured: updatedPrompt.isFeatured, }); } catch (error) { console.error("Error toggling featured status:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/comments/route.ts
src/app/api/prompts/[id]/comments/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { getConfig } from "@/lib/config"; import { z } from "zod"; const createCommentSchema = z.object({ content: z.string().min(1).max(10000), parentId: z.string().optional(), }); // GET - Get all comments for a prompt export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const { id: promptId } = await params; const session = await auth(); // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id: promptId, deletedAt: null }, select: { id: true, isPrivate: true, authorId: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Check if user can view private prompt if (prompt.isPrivate && prompt.authorId !== session?.user?.id) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } const isAdmin = session?.user?.role === "ADMIN"; const userId = session?.user?.id; // Get all comments with cached score and user's vote const comments = await db.comment.findMany({ where: { promptId, deletedAt: null, }, include: { author: { select: { id: true, name: true, username: true, avatar: true, role: true, }, }, votes: session?.user ? { where: { userId: session.user.id }, select: { value: true }, } : false, _count: { select: { replies: true }, }, }, orderBy: { createdAt: "asc" }, }); // Transform and filter comments // Shadow-ban: flagged comments only visible to admins and the comment author const transformedComments = comments .filter((comment: typeof comments[number]) => { // Admins see all comments if (isAdmin) return true; // Non-flagged comments visible to everyone if (!comment.flagged) return true; // Flagged comments only visible to their author (shadow-ban) return comment.authorId === userId; }) .map((comment: typeof comments[number]) => { const userVote = session?.user && comment.votes && Array.isArray(comment.votes) && comment.votes.length > 0 ? (comment.votes[0] as { value: number }).value : 0; return { id: comment.id, content: comment.content, createdAt: comment.createdAt, updatedAt: comment.updatedAt, parentId: comment.parentId, // Only admins see the flagged status flagged: isAdmin ? comment.flagged : false, author: comment.author, score: comment.score, userVote, replyCount: comment._count.replies, }; }); return NextResponse.json({ comments: transformedComments }); } catch (error) { console.error("Get comments error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // POST - Create a new comment export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId } = await params; const body = await request.json(); const validation = createCommentSchema.safeParse(body); if (!validation.success) { return NextResponse.json( { error: "validation_error", message: validation.error.issues[0].message }, { status: 400 } ); } const { content, parentId } = validation.data; // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id: promptId, deletedAt: null }, select: { id: true, isPrivate: true, authorId: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Check if user can view private prompt if (prompt.isPrivate && prompt.authorId !== session.user.id) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // If replying to a comment, verify parent exists and belongs to same prompt if (parentId) { const parentComment = await db.comment.findUnique({ where: { id: parentId, deletedAt: null }, select: { id: true, promptId: true }, }); if (!parentComment || parentComment.promptId !== promptId) { return NextResponse.json( { error: "invalid_parent", message: "Parent comment not found" }, { status: 400 } ); } } // Create comment const comment = await db.comment.create({ data: { content, promptId, authorId: session.user.id, parentId: parentId || null, }, include: { author: { select: { id: true, name: true, username: true, avatar: true, role: true, }, }, }, }); // Create notification for prompt owner (if not commenting on own prompt) if (prompt.authorId !== session.user.id) { await db.notification.create({ data: { type: "COMMENT", userId: prompt.authorId, actorId: session.user.id, promptId, commentId: comment.id, }, }); } // If replying to a comment, also notify the parent comment author if (parentId) { const parentComment = await db.comment.findUnique({ where: { id: parentId }, select: { authorId: true }, }); // Notify parent comment author (if not replying to self and not the prompt owner who already got notified) if (parentComment && parentComment.authorId !== session.user.id && parentComment.authorId !== prompt.authorId) { await db.notification.create({ data: { type: "REPLY", userId: parentComment.authorId, actorId: session.user.id, promptId, commentId: comment.id, }, }); } } return NextResponse.json({ comment: { id: comment.id, content: comment.content, createdAt: comment.createdAt, updatedAt: comment.updatedAt, parentId: comment.parentId, flagged: false, // New comments are never flagged author: comment.author, score: 0, userVote: 0, replyCount: 0, }, }); } catch (error) { console.error("Create comment error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/comments/[commentId]/route.ts
src/app/api/prompts/[id]/comments/[commentId]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { getConfig } from "@/lib/config"; // DELETE - Delete a comment (author or admin only) export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string; commentId: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId, commentId } = await params; // Find the comment const comment = await db.comment.findUnique({ where: { id: commentId, deletedAt: null }, select: { id: true, promptId: true, authorId: true, }, }); if (!comment || comment.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Comment not found" }, { status: 404 } ); } // Check if user can delete (author or admin) const isAuthor = comment.authorId === session.user.id; const isAdmin = session.user.role === "ADMIN"; if (!isAuthor && !isAdmin) { return NextResponse.json( { error: "forbidden", message: "You cannot delete this comment" }, { status: 403 } ); } // Soft delete the comment await db.comment.update({ where: { id: commentId }, data: { deletedAt: new Date() }, }); return NextResponse.json({ deleted: true }); } catch (error) { console.error("Delete comment error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/comments/[commentId]/vote/route.ts
src/app/api/prompts/[id]/comments/[commentId]/vote/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { getConfig } from "@/lib/config"; import { z } from "zod"; const voteSchema = z.object({ value: z.number().refine((v) => v === 1 || v === -1, { message: "Vote value must be 1 (upvote) or -1 (downvote)", }), }); // POST - Vote on a comment (upvote or downvote) export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string; commentId: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId, commentId } = await params; const body = await request.json(); const validation = voteSchema.safeParse(body); if (!validation.success) { return NextResponse.json( { error: "validation_error", message: validation.error.issues[0].message }, { status: 400 } ); } const { value } = validation.data; // Check if comment exists const comment = await db.comment.findUnique({ where: { id: commentId, deletedAt: null }, select: { id: true, promptId: true }, }); if (!comment || comment.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Comment not found" }, { status: 404 } ); } // Check if user already voted const existingVote = await db.commentVote.findUnique({ where: { userId_commentId: { userId: session.user.id, commentId, }, }, }); if (existingVote) { if (existingVote.value === value) { // Same vote - remove it (toggle off) await db.commentVote.delete({ where: { userId_commentId: { userId: session.user.id, commentId, }, }, }); } else { // Different vote - update it await db.commentVote.update({ where: { userId_commentId: { userId: session.user.id, commentId, }, }, data: { value }, }); } } else { // No existing vote - create one await db.commentVote.create({ data: { userId: session.user.id, commentId, value, }, }); } // Calculate and update cached score const votes = await db.commentVote.findMany({ where: { commentId }, select: { value: true }, }); const score = votes.reduce((sum: number, vote: { value: number }) => sum + vote.value, 0); // Update cached score in comment await db.comment.update({ where: { id: commentId }, data: { score }, }); // Get user's current vote const userVote = await db.commentVote.findUnique({ where: { userId_commentId: { userId: session.user.id, commentId, }, }, select: { value: true }, }); return NextResponse.json({ score, userVote: userVote?.value ?? 0, }); } catch (error) { console.error("Vote comment error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // DELETE - Remove vote from a comment export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string; commentId: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { commentId } = await params; // Delete vote await db.commentVote.deleteMany({ where: { userId: session.user.id, commentId, }, }); // Calculate and update cached score const votes = await db.commentVote.findMany({ where: { commentId }, select: { value: true }, }); const score = votes.reduce((sum: number, vote: { value: number }) => sum + vote.value, 0); // Update cached score in comment await db.comment.update({ where: { id: commentId }, data: { score }, }); return NextResponse.json({ score, userVote: 0 }); } catch (error) { console.error("Unvote comment error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/comments/[commentId]/flag/route.ts
src/app/api/prompts/[id]/comments/[commentId]/flag/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { getConfig } from "@/lib/config"; // POST - Flag a comment (admin only) export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string; commentId: string }> } ) { try { const config = await getConfig(); if (config.features.comments === false) { return NextResponse.json( { error: "feature_disabled", message: "Comments are disabled" }, { status: 403 } ); } const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } if (session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "Admin access required" }, { status: 403 } ); } const { id: promptId, commentId } = await params; // Check if comment exists const comment = await db.comment.findUnique({ where: { id: commentId, deletedAt: null }, select: { id: true, promptId: true, flagged: true }, }); if (!comment || comment.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Comment not found" }, { status: 404 } ); } // Toggle flagged status const updated = await db.comment.update({ where: { id: commentId }, data: { flagged: !comment.flagged, flaggedAt: !comment.flagged ? new Date() : null, flaggedBy: !comment.flagged ? session.user.id : null, }, }); return NextResponse.json({ flagged: updated.flagged, }); } catch (error) { console.error("Flag comment error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/unlist/route.ts
src/app/api/prompts/[id]/unlist/route.ts
import { NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // Toggle unlist status (admin only) export async function POST( request: Request, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params; const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } // Only admins can unlist prompts if (session.user.role !== "ADMIN") { return NextResponse.json( { error: "forbidden", message: "Only admins can unlist prompts" }, { status: 403 } ); } // Check if prompt exists const existing = await db.prompt.findUnique({ where: { id }, select: { id: true, isUnlisted: true }, }); if (!existing) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Toggle unlist status const newUnlistedStatus = !existing.isUnlisted; await db.prompt.update({ where: { id }, data: { isUnlisted: newUnlistedStatus, unlistedAt: newUnlistedStatus ? new Date() : null, }, }); // Revalidate caches revalidateTag("prompts", "max"); revalidateTag("categories", "max"); revalidateTag("tags", "max"); return NextResponse.json({ success: true, isUnlisted: newUnlistedStatus, message: newUnlistedStatus ? "Prompt unlisted" : "Prompt relisted" }); } catch (error) { console.error("Unlist prompt error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/changes/route.ts
src/app/api/prompts/[id]/changes/route.ts
import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const createChangeRequestSchema = z.object({ proposedContent: z.string().min(1), proposedTitle: z.string().optional(), reason: z.string().optional(), }); export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId } = await params; // Check if prompt exists const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { id: true, authorId: true, isPrivate: true, content: true, title: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } // Can't create change request for your own prompt if (prompt.authorId === session.user.id) { return NextResponse.json( { error: "forbidden", message: "You cannot create a change request for your own prompt" }, { status: 403 } ); } // Can't create change request for private prompts if (prompt.isPrivate) { return NextResponse.json( { error: "forbidden", message: "Cannot create change request for private prompts" }, { status: 403 } ); } const body = await request.json(); const parsed = createChangeRequestSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: "Invalid input", details: parsed.error.issues }, { status: 400 } ); } const { proposedContent, proposedTitle, reason } = parsed.data; const changeRequest = await db.changeRequest.create({ data: { originalContent: prompt.content, originalTitle: prompt.title, proposedContent, proposedTitle, reason, promptId, authorId: session.user.id, }, }); return NextResponse.json(changeRequest, { status: 201 }); } catch (error) { console.error("Create change request error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const { id: promptId } = await params; const changeRequests = await db.changeRequest.findMany({ where: { promptId }, orderBy: { createdAt: "desc" }, include: { author: { select: { id: true, name: true, username: true, avatar: true, }, }, }, }); return NextResponse.json(changeRequests); } catch (error) { console.error("Get change requests error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/changes/[changeId]/route.ts
src/app/api/prompts/[id]/changes/[changeId]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const updateChangeRequestSchema = z.object({ status: z.enum(["APPROVED", "REJECTED", "PENDING"]), reviewNote: z.string().optional(), }); export async function PATCH( request: NextRequest, { params }: { params: Promise<{ id: string; changeId: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId, changeId } = await params; // Check if prompt exists and user is owner const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { authorId: true, content: true, title: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } if (prompt.authorId !== session.user.id) { return NextResponse.json( { error: "forbidden", message: "Only the prompt owner can review change requests" }, { status: 403 } ); } // Get change request const changeRequest = await db.changeRequest.findUnique({ where: { id: changeId }, select: { id: true, promptId: true, status: true, proposedContent: true, proposedTitle: true, authorId: true, reason: true, author: { select: { username: true }, }, }, }); if (!changeRequest || changeRequest.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Change request not found" }, { status: 404 } ); } const body = await request.json(); const parsed = updateChangeRequestSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: "Invalid input", details: parsed.error.issues }, { status: 400 } ); } const { status, reviewNote } = parsed.data; // Validate state transitions if (changeRequest.status === "PENDING" && status === "PENDING") { return NextResponse.json( { error: "invalid_state", message: "Change request is already pending" }, { status: 400 } ); } if (changeRequest.status === "APPROVED") { return NextResponse.json( { error: "invalid_state", message: "Cannot modify an approved change request" }, { status: 400 } ); } // Allow reopening rejected requests (REJECTED -> PENDING) if (changeRequest.status === "REJECTED" && status !== "PENDING") { return NextResponse.json( { error: "invalid_state", message: "Rejected requests can only be reopened" }, { status: 400 } ); } // If reopening, just update status if (status === "PENDING") { await db.changeRequest.update({ where: { id: changeId }, data: { status, reviewNote: null }, }); return NextResponse.json({ success: true, status }); } // If approving, also update the prompt content if (status === "APPROVED") { // Get current version number const latestVersion = await db.promptVersion.findFirst({ where: { promptId }, orderBy: { version: "desc" }, select: { version: true }, }); const nextVersion = (latestVersion?.version ?? 0) + 1; // Build change note with contributor info const changeNote = changeRequest.reason ? `Contribution by @${changeRequest.author.username}: ${changeRequest.reason}` : `Contribution by @${changeRequest.author.username}`; // Update prompt and create version in transaction await db.$transaction([ // Create version record with the NEW content (the approved change) db.promptVersion.create({ data: { prompt: { connect: { id: promptId } }, content: changeRequest.proposedContent, changeNote, version: nextVersion, author: { connect: { id: changeRequest.authorId } }, }, }), // Update prompt with proposed changes and add contributor db.prompt.update({ where: { id: promptId }, data: { content: changeRequest.proposedContent, ...(changeRequest.proposedTitle && { title: changeRequest.proposedTitle }), contributors: { connect: { id: changeRequest.authorId }, }, }, }), // Update change request status db.changeRequest.update({ where: { id: changeId }, data: { status, reviewNote }, }), ]); } else { // Just update the change request status await db.changeRequest.update({ where: { id: changeId }, data: { status, reviewNote }, }); } return NextResponse.json({ success: true, status }); } catch (error) { console.error("Update change request error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string; changeId: string }> } ) { try { const { id: promptId, changeId } = await params; const changeRequest = await db.changeRequest.findUnique({ where: { id: changeId }, include: { author: { select: { id: true, name: true, username: true, avatar: true, }, }, prompt: { select: { id: true, title: true, content: true, }, }, }, }); if (!changeRequest || changeRequest.prompt.id !== promptId) { return NextResponse.json( { error: "not_found", message: "Change request not found" }, { status: 404 } ); } return NextResponse.json(changeRequest); } catch (error) { console.error("Get change request error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string; changeId: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId, changeId } = await params; // Get change request const changeRequest = await db.changeRequest.findUnique({ where: { id: changeId }, select: { id: true, promptId: true, status: true, authorId: true, }, }); if (!changeRequest || changeRequest.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Change request not found" }, { status: 404 } ); } // Only the author can dismiss their own change request if (changeRequest.authorId !== session.user.id) { return NextResponse.json( { error: "forbidden", message: "Only the author can dismiss their change request" }, { status: 403 } ); } // Can only dismiss pending change requests if (changeRequest.status !== "PENDING") { return NextResponse.json( { error: "invalid_state", message: "Only pending change requests can be dismissed" }, { status: 400 } ); } // Delete the change request await db.changeRequest.delete({ where: { id: changeId }, }); return NextResponse.json({ success: true }); } catch (error) { console.error("Delete change request error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/versions/route.ts
src/app/api/prompts/[id]/versions/route.ts
import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; const createVersionSchema = z.object({ content: z.string().min(1, "Content is required"), changeNote: z.string().max(500).optional(), }); // POST - Create a new version export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId } = await params; // Check if prompt exists and user is owner const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { authorId: true, content: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } if (prompt.authorId !== session.user.id) { return NextResponse.json( { error: "forbidden", message: "You can only add versions to your own prompts" }, { status: 403 } ); } const body = await request.json(); const parsed = createVersionSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "validation_error", message: "Invalid input", details: parsed.error.issues }, { status: 400 } ); } const { content, changeNote } = parsed.data; // Check if content is different if (content === prompt.content) { return NextResponse.json( { error: "no_change", message: "Content is the same as current version" }, { status: 400 } ); } // Get latest version number const latestVersion = await db.promptVersion.findFirst({ where: { promptId }, orderBy: { version: "desc" }, select: { version: true }, }); const newVersionNumber = (latestVersion?.version || 0) + 1; // Create new version and update prompt content in a transaction const [version] = await db.$transaction([ db.promptVersion.create({ data: { promptId, version: newVersionNumber, content, changeNote: changeNote || `Version ${newVersionNumber}`, createdBy: session.user.id, }, include: { author: { select: { name: true, username: true, }, }, }, }), db.prompt.update({ where: { id: promptId }, data: { content }, }), ]); return NextResponse.json(version, { status: 201 }); } catch (error) { console.error("Create version error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // GET - Get all versions export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const { id: promptId } = await params; const versions = await db.promptVersion.findMany({ where: { promptId }, orderBy: { version: "desc" }, include: { author: { select: { name: true, username: true, }, }, }, }); return NextResponse.json(versions); } catch (error) { console.error("Get versions error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/[id]/versions/[versionId]/route.ts
src/app/api/prompts/[id]/versions/[versionId]/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string; versionId: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: promptId, versionId } = await params; // Check if prompt exists and user is owner const prompt = await db.prompt.findUnique({ where: { id: promptId }, select: { authorId: true }, }); if (!prompt) { return NextResponse.json( { error: "not_found", message: "Prompt not found" }, { status: 404 } ); } if (prompt.authorId !== session.user.id) { return NextResponse.json( { error: "forbidden", message: "You can only delete versions of your own prompts" }, { status: 403 } ); } // Check if version exists const version = await db.promptVersion.findUnique({ where: { id: versionId }, select: { id: true, promptId: true }, }); if (!version || version.promptId !== promptId) { return NextResponse.json( { error: "not_found", message: "Version not found" }, { status: 404 } ); } // Delete the version await db.promptVersion.delete({ where: { id: versionId }, }); return NextResponse.json({ success: true }); } catch (error) { console.error("Delete version error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/prompts/search/route.ts
src/app/api/prompts/search/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); const query = searchParams.get("q") || ""; const limit = Math.min(parseInt(searchParams.get("limit") || "10"), 50); const ownerOnly = searchParams.get("ownerOnly") === "true"; if (query.length < 2) { return NextResponse.json({ prompts: [] }); } const session = await auth(); try { const prompts = await db.prompt.findMany({ where: { deletedAt: null, isUnlisted: false, ...(ownerOnly && session?.user ? { authorId: session.user.id } : { OR: [ { isPrivate: false }, ...(session?.user ? [{ authorId: session.user.id }] : []), ], }), title: { contains: query, mode: "insensitive", }, }, select: { id: true, title: true, slug: true, author: { select: { username: true, }, }, }, take: limit, orderBy: [ { isFeatured: "desc" }, { viewCount: "desc" }, ], }); return NextResponse.json({ prompts }); } catch (error) { console.error("Search failed:", error); return NextResponse.json( { error: "Search failed" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/categories/[id]/subscribe/route.ts
src/app/api/categories/[id]/subscribe/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; // POST - Subscribe to a category export async function POST( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: categoryId } = await params; // Check if category exists const category = await db.category.findUnique({ where: { id: categoryId }, }); if (!category) { return NextResponse.json( { error: "not_found", message: "Category not found" }, { status: 404 } ); } // Check if already subscribed const existing = await db.categorySubscription.findUnique({ where: { userId_categoryId: { userId: session.user.id, categoryId, }, }, }); if (existing) { return NextResponse.json( { error: "already_subscribed", message: "Already subscribed to this category" }, { status: 400 } ); } // Create subscription const subscription = await db.categorySubscription.create({ data: { userId: session.user.id, categoryId, }, include: { category: { select: { id: true, name: true, slug: true, }, }, }, }); return NextResponse.json({ subscribed: true, category: subscription.category }); } catch (error) { console.error("Subscribe error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } } // DELETE - Unsubscribe from a category export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { id: categoryId } = await params; // Delete subscription await db.categorySubscription.deleteMany({ where: { userId: session.user.id, categoryId, }, }); return NextResponse.json({ subscribed: false }); } catch (error) { console.error("Unsubscribe error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/users/search/route.ts
src/app/api/users/search/route.ts
import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; export async function GET(request: Request) { try { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "unauthorized", message: "You must be logged in" }, { status: 401 } ); } const { searchParams } = new URL(request.url); const query = searchParams.get("q")?.trim(); if (!query || query.length < 1) { return NextResponse.json([]); } const users = await db.user.findMany({ where: { OR: [ { username: { contains: query, mode: "insensitive" } }, { name: { contains: query, mode: "insensitive" } }, ], }, select: { id: true, username: true, name: true, avatar: true, }, take: 10, orderBy: { username: "asc" }, }); return NextResponse.json(users); } catch (error) { console.error("User search error:", error); return NextResponse.json( { error: "server_error", message: "Something went wrong" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/config/storage/route.ts
src/app/api/config/storage/route.ts
import { NextResponse } from "next/server"; export async function GET() { const enabledStorage = process.env.ENABLED_STORAGE || "url"; return NextResponse.json({ mode: enabledStorage, supportsUpload: enabledStorage !== "url", }); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/search/ai/route.ts
src/app/api/search/ai/route.ts
import { NextRequest, NextResponse } from "next/server"; import { semanticSearch, isAISearchEnabled } from "@/lib/ai/embeddings"; export async function GET(request: NextRequest) { try { const enabled = await isAISearchEnabled(); if (!enabled) { return NextResponse.json( { error: "AI Search is not enabled" }, { status: 400 } ); } const searchParams = request.nextUrl.searchParams; const query = searchParams.get("q"); const limit = parseInt(searchParams.get("limit") || "20"); if (!query || query.trim().length === 0) { return NextResponse.json( { error: "Query is required" }, { status: 400 } ); } const results = await semanticSearch(query, limit); return NextResponse.json({ results, query, count: results.length, }); } catch (error) { console.error("AI Search error:", error); return NextResponse.json( { error: "Search failed" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/media-generate/route.ts
src/app/api/media-generate/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { getMediaGeneratorPlugin, getAvailableModels, isMediaGenerationAvailable, } from "@/lib/plugins/media-generators"; export async function GET() { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const available = isMediaGenerationAvailable(); const imageModels = getAvailableModels("image"); const videoModels = getAvailableModels("video"); const audioModels = getAvailableModels("audio"); // Get user's credit info const user = await db.user.findUnique({ where: { id: session.user.id }, select: { generationCreditsRemaining: true, dailyGenerationLimit: true, flagged: true, }, }); return NextResponse.json({ available, imageModels, videoModels, audioModels, credits: { remaining: user?.generationCreditsRemaining ?? 0, daily: user?.dailyGenerationLimit ?? 0, }, canGenerate: !user?.flagged && (user?.generationCreditsRemaining ?? 0) > 0, }); } export async function POST(request: NextRequest) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } try { // Check user's credits and flagged status const user = await db.user.findUnique({ where: { id: session.user.id }, select: { generationCreditsRemaining: true, flagged: true, }, }); if (!user) { return NextResponse.json({ error: "User not found" }, { status: 404 }); } // Block flagged users if (user.flagged) { return NextResponse.json( { error: "Your account has been flagged. Media generation is disabled." }, { status: 403 } ); } // Check credits if (user.generationCreditsRemaining <= 0) { return NextResponse.json( { error: "No generation credits remaining. Credits reset daily." }, { status: 403 } ); } const body = await request.json(); const { prompt, model, provider, type, inputImageUrl, resolution, aspectRatio } = body; if (!prompt || !model || !provider || !type) { return NextResponse.json( { error: "Missing required fields: prompt, model, provider, type" }, { status: 400 } ); } const plugin = getMediaGeneratorPlugin(provider); if (!plugin) { return NextResponse.json( { error: `Provider "${provider}" not found` }, { status: 404 } ); } if (!plugin.isEnabled()) { return NextResponse.json( { error: `Provider "${provider}" is not enabled` }, { status: 400 } ); } const task = await plugin.startGeneration({ prompt, model, type, inputImageUrl, resolution, aspectRatio, }); // Deduct one credit after successful generation start await db.user.update({ where: { id: session.user.id }, data: { generationCreditsRemaining: { decrement: 1, }, }, }); return NextResponse.json({ success: true, taskId: task.taskId, socketAccessToken: task.socketAccessToken, webSocketUrl: plugin.getWebSocketUrl(), provider, }); } catch (error) { console.error("Media generation error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Generation failed" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/media-generate/status/route.ts
src/app/api/media-generate/status/route.ts
import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { getMediaGeneratorPlugin } from "@/lib/plugins/media-generators"; /** * Polling endpoint for media generation status * Used by providers that don't support WebSocket (e.g., Fal.ai) */ export async function GET(request: NextRequest) { const session = await auth(); if (!session?.user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const searchParams = request.nextUrl.searchParams; const provider = searchParams.get("provider"); const socketAccessToken = searchParams.get("token"); if (!provider || !socketAccessToken) { return NextResponse.json( { error: "Missing provider or token" }, { status: 400 } ); } const plugin = getMediaGeneratorPlugin(provider); if (!plugin) { return NextResponse.json( { error: `Provider "${provider}" not found` }, { status: 404 } ); } if (!plugin.checkStatus) { return NextResponse.json( { error: "Provider does not support polling" }, { status: 400 } ); } try { const result = await plugin.checkStatus(socketAccessToken); return NextResponse.json(result); } catch (error) { console.error("Status check error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Status check failed" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/api/improve-prompt/route.ts
src/app/api/improve-prompt/route.ts
import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { improvePrompt } from "@/lib/ai/improve-prompt"; import { db } from "@/lib/db"; import { isValidApiKeyFormat } from "@/lib/api-key"; import { auth } from "@/lib/auth"; const requestSchema = z.object({ prompt: z.string().min(1, "Prompt is required").max(10000, "Prompt too long"), outputFormat: z.enum(["text", "structured_json", "structured_yaml"]).default("text"), outputType: z.enum(["text", "image", "video", "sound"]).default("text"), }); async function authenticateRequest(request: NextRequest) { // First check session auth const session = await auth(); if (session?.user?.id) { return { id: session.user.id, username: session.user.name || "user" }; } // Fall back to API key auth const apiKey = request.headers.get("x-api-key") || request.headers.get("authorization")?.replace("Bearer ", "") || request.headers.get("prompts-api-key"); if (!apiKey || !isValidApiKeyFormat(apiKey)) { return null; } const user = await db.user.findUnique({ where: { apiKey }, select: { id: true, username: true }, }); return user; } export async function POST(request: NextRequest) { try { // Authenticate request (session or API key) const user = await authenticateRequest(request); if (!user) { return NextResponse.json( { error: "Authentication required. Please log in or provide a valid API key." }, { status: 401 } ); } const body = await request.json(); const validation = requestSchema.safeParse(body); if (!validation.success) { return NextResponse.json( { error: "Invalid request", details: validation.error.flatten() }, { status: 400 } ); } const { prompt, outputFormat, outputType } = validation.data; const result = await improvePrompt({ prompt, outputFormat, outputType }); return NextResponse.json(result); } catch (error) { console.error("Error improving prompt:", error); if (error instanceof Error) { // Handle rate limiting if (error.message.includes("rate limit")) { return NextResponse.json( { error: "Rate limit exceeded. Please try again later." }, { status: 429 } ); } } return NextResponse.json( { error: "An error occurred while improving the prompt" }, { status: 500 } ); } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/feed/page.tsx
src/app/feed/page.tsx
import Link from "next/link"; import { redirect } from "next/navigation"; import { getTranslations } from "next-intl/server"; import { ArrowRight, Bell, FolderOpen, Sparkles } from "lucide-react"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { PromptList } from "@/components/prompts/prompt-list"; export default async function FeedPage() { const t = await getTranslations("feed"); const session = await auth(); // Redirect to login if not authenticated if (!session?.user) { redirect("/login"); } // Get user's subscribed categories const subscriptions = await db.categorySubscription.findMany({ where: { userId: session.user.id }, include: { category: { select: { id: true, name: true, slug: true, }, }, }, }); const subscribedCategoryIds = subscriptions.map((s) => s.categoryId); // Fetch prompts from subscribed categories const promptsRaw = subscribedCategoryIds.length > 0 ? await db.prompt.findMany({ where: { isPrivate: false, isUnlisted: false, deletedAt: null, categoryId: { in: subscribedCategoryIds }, }, orderBy: { createdAt: "desc" }, take: 30, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: { select: { id: true, name: true, slug: true }, }, }, }, tags: { include: { tag: true, }, }, _count: { select: { votes: true, contributors: true }, }, }, }) : []; const prompts = promptsRaw.map((p) => ({ ...p, voteCount: p._count?.votes ?? 0, contributorCount: p._count?.contributors ?? 0, })); // Get all categories for subscription const categories = await db.category.findMany({ orderBy: { name: "asc" }, include: { _count: { select: { prompts: true }, }, }, }); return ( <div className="container py-6"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6"> <div> <h1 className="text-lg font-semibold">{t("yourFeed")}</h1> <p className="text-sm text-muted-foreground"> {t("feedDescription")} </p> </div> <div className="flex items-center gap-2"> <Button variant="outline" size="sm" asChild> <Link href="/prompts"> {t("browseAll")} <ArrowRight className="ml-1.5 h-4 w-4" /> </Link> </Button> <Button variant="outline" size="sm" asChild> <Link href="/discover"> <Sparkles className="mr-1.5 h-4 w-4" /> {t("discover")} </Link> </Button> </div> </div> {/* Subscribed Categories */} {subscriptions.length > 0 && ( <div className="flex flex-wrap gap-2 mb-6"> {subscriptions.map(({ category }) => ( <Link key={category.id} href={`/categories/${category.slug}`}> <Badge variant="secondary" className="gap-1"> <Bell className="h-3 w-3" /> {category.name} </Badge> </Link> ))} </div> )} {/* Feed */} {prompts.length > 0 ? ( <PromptList prompts={prompts} currentPage={1} totalPages={1} /> ) : ( <div className="text-center py-12 border rounded-lg bg-muted/30"> <FolderOpen className="h-10 w-10 text-muted-foreground mx-auto mb-3" /> <h2 className="font-medium mb-1">{t("noPromptsInFeed")}</h2> <p className="text-sm text-muted-foreground mb-4"> {t("subscribeToCategories")} </p> {/* Category suggestions */} <div className="flex flex-wrap justify-center gap-2 max-w-md mx-auto"> {categories.slice(0, 6).map((category) => ( <Link key={category.id} href={`/categories/${category.slug}`}> <Badge variant="outline" className="cursor-pointer hover:bg-accent"> {category.name} <span className="ml-1 text-muted-foreground">({category._count.prompts})</span> </Badge> </Link> ))} </div> <div className="mt-4"> <Button variant="outline" size="sm" asChild> <Link href="/categories">{t("viewAllCategories")}</Link> </Button> </div> </div> )} </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/feed/loading.tsx
src/app/feed/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function FeedLoading() { return ( <div className="container py-6"> {/* Header */} <div className="flex items-center justify-between mb-6"> <Skeleton className="h-6 w-24" /> <Skeleton className="h-9 w-28" /> </div> {/* Feed Items */} <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3"> {Array.from({ length: 6 }).map((_, i) => ( <div key={i} className="border rounded-lg p-4 space-y-3"> <div className="flex items-center gap-2"> <Skeleton className="h-6 w-6 rounded-full" /> <Skeleton className="h-4 w-24" /> </div> <Skeleton className="h-5 w-3/4" /> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-2/3" /> </div> ))} </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/page.tsx
src/app/prompts/page.tsx
import { Metadata } from "next"; import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { unstable_cache } from "next/cache"; import { Suspense } from "react"; import { Plus } from "lucide-react"; import { Button } from "@/components/ui/button" import { InfinitePromptList } from "@/components/prompts/infinite-prompt-list"; import { PromptFilters } from "@/components/prompts/prompt-filters"; import { FilterProvider } from "@/components/prompts/filter-context"; import { PinnedCategories } from "@/components/categories/pinned-categories"; import { HFDataStudioDropdown } from "@/components/prompts/hf-data-studio-dropdown"; import { McpServerPopup } from "@/components/mcp/mcp-server-popup"; import { db } from "@/lib/db"; import { isAISearchEnabled, semanticSearch } from "@/lib/ai/embeddings"; import { isAIGenerationEnabled } from "@/lib/ai/generation"; import config from "@/../prompts.config"; export const metadata: Metadata = { title: "Prompts", description: "Browse and discover AI prompts", }; // Query for categories (cached) const getCategories = unstable_cache( async () => { return db.category.findMany({ orderBy: [{ order: "asc" }, { name: "asc" }], select: { id: true, name: true, slug: true, parentId: true, }, }); }, ["categories"], { tags: ["categories"] } ); // Query for pinned categories (cached) const getPinnedCategories = unstable_cache( async () => { return db.category.findMany({ where: { pinned: true }, orderBy: [{ order: "asc" }, { name: "asc" }], select: { id: true, name: true, slug: true, icon: true, }, }); }, ["pinned-categories"], { tags: ["categories"] } ); // Query for tags (cached) const getTags = unstable_cache( async () => { return db.tag.findMany({ orderBy: { name: "asc" }, }); }, ["tags"], { tags: ["tags"] } ); // Query for prompts list (cached) function getCachedPrompts( where: Record<string, unknown>, // eslint-disable-next-line @typescript-eslint/no-explicit-any orderBy: any, perPage: number ) { // Create a stable cache key from the query parameters const cacheKey = JSON.stringify({ where, orderBy, perPage }); return unstable_cache( async () => { const [promptsRaw, totalCount] = await Promise.all([ db.prompt.findMany({ where, orderBy, skip: 0, take: perPage, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: { select: { id: true, name: true, slug: true }, }, }, }, tags: { include: { tag: true, }, }, contributors: { select: { id: true, username: true, name: true, avatar: true, }, }, _count: { select: { votes: true, contributors: true }, }, }, }), db.prompt.count({ where }), ]); return { // eslint-disable-next-line @typescript-eslint/no-explicit-any prompts: promptsRaw.map((p: any) => ({ ...p, voteCount: p._count.votes, contributorCount: p._count.contributors, contributors: p.contributors, })), total: totalCount, }; }, ["prompts", cacheKey], { tags: ["prompts"] } )(); } interface PromptsPageProps { searchParams: Promise<{ q?: string; type?: string; category?: string; tag?: string; sort?: string; page?: string; ai?: string; }>; } export default async function PromptsPage({ searchParams }: PromptsPageProps) { const t = await getTranslations("prompts"); const tSearch = await getTranslations("search"); const params = await searchParams; const perPage = 24; const aiSearchAvailable = await isAISearchEnabled(); const aiGenerationAvailable = await isAIGenerationEnabled(); const useAISearch = aiSearchAvailable && params.ai === "1" && params.q; // eslint-disable-next-line @typescript-eslint/no-explicit-any let prompts: any[] = []; let total = 0; if (useAISearch && params.q) { // Use AI semantic search try { const aiResults = await semanticSearch(params.q, perPage); prompts = aiResults.map((p) => ({ ...p, contributorCount: 0, })); total = aiResults.length; } catch { // Fallback to regular search on error } } // Regular search if AI search not used or failed if (!useAISearch || prompts.length === 0) { // Build where clause based on filters const where: Record<string, unknown> = { isPrivate: false, isUnlisted: false, // Exclude unlisted prompts deletedAt: null, // Exclude soft-deleted prompts }; if (params.q) { where.OR = [ { title: { contains: params.q, mode: "insensitive" } }, { content: { contains: params.q, mode: "insensitive" } }, { description: { contains: params.q, mode: "insensitive" } }, ]; } if (params.type) { where.type = params.type; } if (params.category) { where.categoryId = params.category; } if (params.tag) { where.tags = { some: { tag: { slug: params.tag, }, }, }; } // Build order by clause const isUpvoteSort = params.sort === "upvotes"; // eslint-disable-next-line @typescript-eslint/no-explicit-any let orderBy: any = { createdAt: "desc" }; if (params.sort === "oldest") { orderBy = { createdAt: "asc" }; } else if (isUpvoteSort) { // Sort by vote count descending orderBy = { votes: { _count: "desc" } }; } // Fetch initial prompts (first page) - cached const result = await getCachedPrompts(where, orderBy, perPage); prompts = result.prompts; total = result.total; } // Fetch categories, pinned categories, and tags for filter const [categories, pinnedCategories, tags] = await Promise.all([ getCategories(), getPinnedCategories(), getTags(), ]); return ( <div className="container py-6"> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4"> <div className="flex items-baseline gap-2"> <h1 className="text-lg font-semibold">{t("title")}</h1> <span className="text-xs text-muted-foreground">{tSearch("found", { count: total })}</span> </div> <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2"> {!config.homepage?.useCloneBranding && ( <div className="flex items-center gap-2"> <HFDataStudioDropdown aiGenerationEnabled={aiGenerationAvailable} /> {config.features.mcp !== false && <McpServerPopup showOfficialBranding />} </div> )} <Button size="sm" className="h-8 text-xs w-full sm:w-auto" asChild> <Link href="/prompts/new"> <Plus className="h-3.5 w-3.5 mr-1" /> {t("create")} </Link> </Button> </div> </div> <FilterProvider> <Suspense fallback={null}> <div className="mb-4"> <PinnedCategories categories={pinnedCategories} currentCategoryId={params.category} /> </div> </Suspense> <div className="flex flex-col lg:flex-row gap-6"> <aside className="w-full lg:w-56 shrink-0 lg:sticky lg:top-16 lg:self-start lg:max-h-[calc(100vh-5rem)] lg:overflow-y-auto"> <PromptFilters categories={categories} tags={tags} currentFilters={params} aiSearchEnabled={aiSearchAvailable} /> </aside> <main className="flex-1 min-w-0"> <InfinitePromptList initialPrompts={prompts} initialTotal={total} filters={{ q: params.q, type: params.type, category: params.category, tag: params.tag, sort: params.sort, }} /> </main> </div> </FilterProvider> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/loading.tsx
src/app/prompts/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; function PromptCardSkeleton() { return ( <div className="border rounded-lg p-4 space-y-3"> <div className="flex items-start justify-between"> <Skeleton className="h-5 w-3/4" /> <Skeleton className="h-5 w-5 rounded" /> </div> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-5/6" /> <Skeleton className="h-4 w-2/3" /> <div className="flex items-center gap-2 pt-2"> <Skeleton className="h-6 w-6 rounded-full" /> <Skeleton className="h-4 w-24" /> </div> <div className="flex gap-2"> <Skeleton className="h-5 w-14 rounded-full" /> <Skeleton className="h-5 w-16 rounded-full" /> </div> </div> ); } export default function PromptsLoading() { return ( <div className="container py-6"> {/* Header */} <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4"> <div className="flex items-baseline gap-2"> <Skeleton className="h-6 w-24" /> <Skeleton className="h-4 w-16" /> </div> <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2"> <Skeleton className="h-8 w-32" /> <Skeleton className="h-8 w-28" /> </div> </div> <div className="flex flex-col lg:flex-row gap-6"> {/* Sidebar Filters Skeleton */} <aside className="w-full lg:w-56 shrink-0"> <div className="space-y-4 p-4 border rounded-lg"> <div className="flex items-center justify-between"> <Skeleton className="h-4 w-16" /> <Skeleton className="h-6 w-12" /> </div> <Skeleton className="h-9 w-full" /> <Skeleton className="h-9 w-full" /> <Skeleton className="h-9 w-full" /> <Skeleton className="h-9 w-full" /> <div className="flex items-center gap-2"> <Skeleton className="h-5 w-9 rounded-full" /> <Skeleton className="h-4 w-20" /> </div> <div className="space-y-2"> <Skeleton className="h-4 w-12" /> <div className="flex flex-wrap gap-1"> {Array.from({ length: 8 }).map((_, i) => ( <Skeleton key={i} className="h-6 w-16 rounded-full" /> ))} </div> </div> </div> </aside> {/* Main Content - Prompt Grid Skeleton */} <main className="flex-1 min-w-0"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {Array.from({ length: 12 }).map((_, i) => ( <PromptCardSkeleton key={i} /> ))} </div> </main> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/new/page.tsx
src/app/prompts/new/page.tsx
import { Metadata } from "next"; import { redirect } from "next/navigation"; import { getTranslations } from "next-intl/server"; import { Info } from "lucide-react"; import { auth } from "@/lib/auth"; import { PromptForm } from "@/components/prompts/prompt-form"; import { db } from "@/lib/db"; import { isAIGenerationEnabled, getAIModelName } from "@/lib/ai/generation"; import { Alert, AlertDescription } from "@/components/ui/alert"; export const metadata: Metadata = { title: "Create Prompt", description: "Create a new prompt", }; interface PageProps { searchParams: Promise<{ prompt?: string; title?: string; content?: string; type?: "TEXT" | "IMAGE" | "VIDEO" | "AUDIO"; format?: "JSON" | "YAML"; }>; } export default async function NewPromptPage({ searchParams }: PageProps) { const session = await auth(); const t = await getTranslations("prompts"); const { prompt: initialPromptRequest, title, content, type, format } = await searchParams; if (!session?.user) { redirect("/login"); } // Fetch categories for the form (with parent info for nesting) const categories = await db.category.findMany({ orderBy: [{ order: "asc" }, { name: "asc" }], select: { id: true, name: true, slug: true, parentId: true, }, }); // Fetch tags for the form const tags = await db.tag.findMany({ orderBy: { name: "asc" }, }); // Check if AI generation is enabled const aiGenerationEnabled = await isAIGenerationEnabled(); const aiModelName = getAIModelName(); return ( <div className="container max-w-3xl py-8"> <Alert className="mb-6"> <Info className="h-4 w-4" /> <AlertDescription> {t("createInfo")} </AlertDescription> </Alert> <PromptForm categories={categories} tags={tags} aiGenerationEnabled={aiGenerationEnabled} aiModelName={aiModelName} initialPromptRequest={initialPromptRequest} initialData={(title || content || type || format) ? { title: title || "", content: content || "", type: type || "TEXT", structuredFormat: format || undefined, } : undefined} /> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/new/loading.tsx
src/app/prompts/new/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function NewPromptLoading() { return ( <> <div className="container max-w-3xl py-8"> <div className="space-y-4"> {/* Header: Page title + Private Switch */} <div className="flex items-center justify-between mb-2"> <Skeleton className="h-6 w-24" /> <div className="flex items-center gap-3"> {/* AI Builder button - hidden on mobile since panel is closed by default */} <Skeleton className="hidden sm:block h-7 w-28" /> {/* Private switch */} <div className="flex items-center gap-2"> <Skeleton className="h-5 w-9 rounded-full" /> <Skeleton className="h-4 w-14" /> </div> </div> </div> {/* ===== METADATA SECTION ===== */} <div className="space-y-4 pb-6 border-b"> {/* Row 1: Title + Category */} <div className="flex flex-col sm:flex-row sm:items-start gap-4"> <div className="flex-1 space-y-2"> <Skeleton className="h-4 w-12" /> <Skeleton className="h-10 w-full" /> </div> <div className="w-full sm:w-64 space-y-2"> <Skeleton className="h-4 w-16" /> <Skeleton className="h-10 w-full" /> </div> </div> {/* Row 2: Description */} <div className="space-y-2"> <Skeleton className="h-4 w-20" /> <Skeleton className="h-16 w-full" /> </div> {/* Tags */} <div className="space-y-2"> <Skeleton className="h-4 w-10" /> <Skeleton className="h-10 w-full" /> </div> {/* Contributors */} <div className="space-y-2"> <Skeleton className="h-4 w-24" /> <Skeleton className="h-3 w-48" /> <Skeleton className="h-10 w-full" /> </div> </div> {/* ===== INPUT SECTION ===== */} <div className="space-y-4 py-6"> <Skeleton className="h-5 w-20" /> {/* Input Type & Format selectors */} <div className="flex flex-col sm:flex-row sm:items-center gap-3"> <Skeleton className="h-9 w-48" /> <div className="flex items-center gap-2 sm:ml-auto"> <Skeleton className="h-5 w-9 rounded-full" /> <Skeleton className="h-4 w-32" /> </div> </div> {/* Prompt Content - Variable toolbar + Textarea */} <div className="rounded-md border overflow-hidden"> <div className="flex items-center gap-1 p-2 border-b bg-muted/30"> <Skeleton className="h-7 w-7" /> <Skeleton className="h-7 w-7" /> <Skeleton className="h-7 w-7" /> </div> <Skeleton className="h-[150px] w-full rounded-none" /> </div> </div> {/* ===== LLM PROCESSING ARROW ===== */} <div className="flex flex-col items-center py-4"> <div className="flex items-center gap-2"> <Skeleton className="h-px w-16" /> <Skeleton className="h-7 w-40 rounded-full" /> <Skeleton className="h-px w-16" /> </div> </div> {/* ===== OUTPUT SECTION ===== */} <div className="space-y-4 py-6 border-t"> <Skeleton className="h-5 w-24" /> {/* Output Type buttons */} <div className="inline-flex rounded-md border divide-x"> <Skeleton className="h-10 w-20 rounded-l-md rounded-r-none" /> <Skeleton className="h-10 w-20 rounded-none" /> <Skeleton className="h-10 w-20 rounded-none" /> <Skeleton className="h-10 w-20 rounded-r-md rounded-l-none" /> </div> {/* Media URL */} <div className="space-y-2"> <Skeleton className="h-4 w-20" /> <Skeleton className="h-10 w-full" /> </div> </div> {/* Submit Button */} <div className="flex justify-end pt-4"> <Skeleton className="h-10 w-32" /> </div> </div> </div> {/* Agent Panel Skeleton - only visible on desktop (sm+) since it's closed by default on mobile */} <div className="hidden sm:flex fixed z-50 bg-background shadow-lg flex-col right-0 left-auto top-12 bottom-auto h-[calc(100vh-3rem)] w-[400px] border-l border-t"> {/* Header */} <div className="flex items-center justify-between px-3 py-1.5 border-b"> <div className="flex items-center gap-1.5"> <Skeleton className="h-3 w-3" /> <Skeleton className="h-3 w-24" /> </div> <Skeleton className="h-6 w-6" /> </div> {/* Messages area */} <div className="flex-1 overflow-hidden p-4"> <div className="text-center py-8"> <Skeleton className="h-8 w-8 mx-auto mb-3 rounded" /> <Skeleton className="h-4 w-32 mx-auto mb-1" /> <Skeleton className="h-3 w-48 mx-auto" /> <div className="mt-4 space-y-2"> <Skeleton className="h-3 w-24 mx-auto" /> <div className="flex flex-wrap gap-1.5 justify-center"> <Skeleton className="h-6 w-24 rounded-full" /> <Skeleton className="h-6 w-28 rounded-full" /> <Skeleton className="h-6 w-20 rounded-full" /> </div> </div> </div> </div> {/* Input */} <div className="p-2 border-t"> <div className="rounded-lg bg-muted/50 border px-2.5 py-2"> <Skeleton className="h-8 w-full" /> <div className="flex items-center justify-between mt-1.5"> <div className="flex items-center gap-1"> <Skeleton className="h-2.5 w-2.5" /> <Skeleton className="h-2.5 w-16" /> </div> <Skeleton className="h-6 w-6 rounded-full" /> </div> </div> </div> </div> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/opengraph-image.tsx
src/app/prompts/[id]/opengraph-image.tsx
import { ImageResponse } from "next/og"; import { db } from "@/lib/db"; import { getConfig } from "@/lib/config"; export const alt = "Prompt Preview"; export const size = { width: 1200, height: 630, }; export const contentType = "image/png"; const typeLabels: Record<string, string> = { TEXT: "Text Prompt", IMAGE: "Image Prompt", VIDEO: "Video Prompt", AUDIO: "Audio Prompt", STRUCTURED: "Structured", }; const typeColors: Record<string, string> = { TEXT: "#3b82f6", IMAGE: "#8b5cf6", VIDEO: "#ec4899", AUDIO: "#f59e0b", STRUCTURED: "#10b981", }; const radiusMap: Record<string, number> = { none: 0, sm: 8, md: 12, lg: 16, }; /** * Extracts the prompt ID from a URL parameter that may contain a slug */ function extractPromptId(idParam: string): string { const underscoreIndex = idParam.indexOf("_"); if (underscoreIndex !== -1) { return idParam.substring(0, underscoreIndex); } return idParam; } export default async function OGImage({ params }: { params: Promise<{ id: string }> }) { const { id: idParam } = await params; const id = extractPromptId(idParam); const config = await getConfig(); const radius = radiusMap[config.theme?.radius || "sm"] || 8; const radiusLg = radius * 2; // For larger elements like content box const prompt = await db.prompt.findUnique({ where: { id }, include: { author: { select: { name: true, username: true, avatar: true, }, }, category: { select: { name: true, icon: true, }, }, _count: { select: { votes: true, contributors: true }, }, }, }); if (!prompt) { return new ImageResponse( ( <div style={{ height: "100%", width: "100%", display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "#0a0a0a", color: "#fff", fontSize: 48, fontWeight: 600, }} > Prompt Not Found </div> ), { ...size } ); } // For structured prompts, try to prettify JSON/YAML let displayContent = prompt.content; if (prompt.type === "STRUCTURED") { try { if (prompt.structuredFormat === "JSON") { const parsed = JSON.parse(prompt.content); displayContent = JSON.stringify(parsed, null, 2); } } catch { // Keep original if parsing fails } } const truncatedContent = displayContent.length > 400 ? displayContent.slice(0, 400) + "..." : displayContent; const isImagePrompt = prompt.type === "IMAGE" && prompt.mediaUrl; const isStructuredPrompt = prompt.type === "STRUCTURED"; const voteCount = prompt._count.votes; const contributorCount = prompt._count.contributors; return new ImageResponse( ( <div style={{ height: "100%", width: "100%", display: "flex", flexDirection: "column", backgroundColor: "#ffffff", padding: "48px 56px", }} > {/* Top Bar */} <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24, }} > {/* Left: Branding */} <div style={{ display: "flex", alignItems: "center", gap: 16 }}> <span style={{ fontSize: 24, fontWeight: 600, color: config.theme?.colors?.primary || "#6366f1" }}> {config.branding.name} </span> </div> {/* Right: Stats */} <div style={{ display: "flex", alignItems: "center", gap: 24 }}> {/* Upvotes */} <div style={{ display: "flex", alignItems: "center", gap: 8 }}> <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={config.theme?.colors?.primary || "#6366f1"} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"> <path d="m18 15-6-6-6 6" /> </svg> <span style={{ fontSize: 24, fontWeight: 600, color: config.theme?.colors?.primary || "#6366f1" }}> {voteCount} </span> </div> {/* Contributors */} {contributorCount > 0 && ( <div style={{ display: "flex", alignItems: "center", gap: 8 }}> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"> <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /> <circle cx="9" cy="7" r="4" /> <path d="M22 21v-2a4 4 0 0 0-3-3.87" /> <path d="M16 3.13a4 4 0 0 1 0 7.75" /> </svg> <span style={{ fontSize: 20, color: "#71717a" }}> +{contributorCount} </span> </div> )} </div> </div> {/* Main Content Area */} <div style={{ display: "flex", flex: 1, gap: 40, }} > {/* Left Content */} <div style={{ display: "flex", flexDirection: "column", flex: 1, }} > {/* Title Row with Category and Type Badge */} <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 20, marginBottom: 16, }} > <div style={{ display: "flex", fontSize: 48, fontWeight: 700, color: "#18181b", lineHeight: 1.2, letterSpacing: "-0.02em", flex: 1, }} > {prompt.title} </div> <div style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}> {/* Category Badge */} {prompt.category && ( <div style={{ display: "flex", alignItems: "center", gap: 6, backgroundColor: "#f4f4f5", color: "#71717a", padding: "8px 14px", borderRadius: radius * 2.5, fontSize: 20, fontWeight: 500, }} > {prompt.category.icon && <span>{prompt.category.icon}</span>} <span>{prompt.category.name}</span> </div> )} {/* Type Badge */} <div style={{ display: "flex", alignItems: "center", gap: 6, backgroundColor: typeColors[prompt.type] + "30", color: typeColors[prompt.type], padding: "8px 16px", borderRadius: radius * 2.5, fontSize: 20, fontWeight: 600, }} > {typeLabels[prompt.type] || prompt.type} </div> </div> </div> {/* Content Preview */} <div style={{ display: "flex", flexDirection: "column", fontSize: isStructuredPrompt ? 18 : 22, color: "#3f3f46", lineHeight: isStructuredPrompt ? 1.4 : 1.6, flex: 1, backgroundColor: "#fafafa", padding: "12px 14px", borderRadius: radius, border: `2px solid ${config.theme?.colors?.primary || "#6366f1"}20`, overflow: "hidden", }} > {isStructuredPrompt && ( <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, paddingBottom: 12, borderBottom: "1px solid #e4e4e7", }} > <span style={{ color: config.theme?.colors?.primary || "#6366f1", fontWeight: 600, fontSize: 14 }}> {prompt.structuredFormat || "JSON"} </span> </div> )} <div style={{ display: "flex", whiteSpace: isStructuredPrompt ? "pre" : "pre-wrap" }}> {truncatedContent} </div> </div> {/* Footer - Author Info */} <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", marginTop: 20, }} > <div style={{ display: "flex", alignItems: "center", gap: 14 }}> {/* Avatar */} {prompt.author.avatar ? ( <img src={prompt.author.avatar} width={48} height={48} style={{ borderRadius: 24, border: "2px solid #e4e4e7" }} /> ) : ( <div style={{ width: 48, height: 48, borderRadius: 24, backgroundColor: "#f4f4f5", display: "flex", alignItems: "center", justifyContent: "center", color: "#71717a", fontSize: 20, fontWeight: 600, border: "2px solid #e4e4e7", }} > {(prompt.author.name || prompt.author.username).charAt(0).toUpperCase()} </div> )} <div style={{ display: "flex", flexDirection: "column" }}> <span style={{ color: "#18181b", fontSize: 20, fontWeight: 600 }}> {prompt.author.name || prompt.author.username} </span> <span style={{ color: "#71717a", fontSize: 16 }}> @{prompt.author.username} </span> </div> </div> </div> </div> {/* Image Preview (for image prompts) */} {isImagePrompt && ( <img src={prompt.mediaUrl!} width={280} height={420} style={{ borderRadius: radiusLg, objectFit: "cover", objectPosition: "center", border: "2px solid #e4e4e7", }} /> )} </div> </div> ), { ...size } ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/page.tsx
src/app/prompts/[id]/page.tsx
import { Metadata } from "next"; import { notFound } from "next/navigation"; import Link from "next/link"; import { getTranslations, getLocale } from "next-intl/server"; import { formatDistanceToNow } from "@/lib/date"; import { Clock, Edit, History, GitPullRequest, Check, X, Users, ImageIcon, Video, FileText, Shield, Trash2 } from "lucide-react"; import { AnimatedDate } from "@/components/ui/animated-date"; import { ShareDropdown } from "@/components/prompts/share-dropdown"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { InteractivePromptContent } from "@/components/prompts/interactive-prompt-content"; import { UpvoteButton } from "@/components/prompts/upvote-button"; import { AddVersionForm } from "@/components/prompts/add-version-form"; import { DeleteVersionButton } from "@/components/prompts/delete-version-button"; import { VersionCompareModal } from "@/components/prompts/version-compare-modal"; import { VersionCompareButton } from "@/components/prompts/version-compare-button"; import { FeaturePromptButton } from "@/components/prompts/feature-prompt-button"; import { UnlistPromptButton } from "@/components/prompts/unlist-prompt-button"; import { MediaPreview } from "@/components/prompts/media-preview"; import { DelistBanner } from "@/components/prompts/delist-banner"; import { RestorePromptButton } from "@/components/prompts/restore-prompt-button"; import { CommentSection } from "@/components/comments"; import { PromptFlowSection } from "@/components/prompts/prompt-flow-section"; import { RelatedPrompts } from "@/components/prompts/related-prompts"; import { getConfig } from "@/lib/config"; import { StructuredData } from "@/components/seo/structured-data"; interface PromptPageProps { params: Promise<{ id: string }>; } /** * Extracts the prompt ID from a URL parameter that may contain a slug * Supports formats: "abc123", "abc123_some-slug", or "abc123_some-slug.prompt.md" */ function extractPromptId(idParam: string): string { let param = idParam; // Strip .prompt.md suffix if present if (param.endsWith(".prompt.md")) { param = param.slice(0, -".prompt.md".length); } // If the param contains an underscore, extract the ID (everything before first underscore) const underscoreIndex = param.indexOf("_"); if (underscoreIndex !== -1) { return param.substring(0, underscoreIndex); } return param; } export async function generateMetadata({ params }: PromptPageProps): Promise<Metadata> { const { id: idParam } = await params; const id = extractPromptId(idParam); const prompt = await db.prompt.findUnique({ where: { id }, select: { title: true, description: true }, }); if (!prompt) { return { title: "Prompt Not Found" }; } return { title: prompt.title, description: prompt.description || `View the prompt: ${prompt.title}`, }; } export default async function PromptPage({ params }: PromptPageProps) { const { id: idParam } = await params; const id = extractPromptId(idParam); const session = await auth(); const config = await getConfig(); const t = await getTranslations("prompts"); const locale = await getLocale(); const isAdmin = session?.user?.role === "ADMIN"; // Admins can view deleted prompts, others cannot const prompt = await db.prompt.findFirst({ where: { id, ...(isAdmin ? {} : { deletedAt: null }) }, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: true, }, }, tags: { include: { tag: true, }, }, versions: { orderBy: { version: "desc" }, select: { id: true, version: true, content: true, changeNote: true, createdAt: true, author: { select: { name: true, username: true, }, }, }, }, _count: { select: { votes: true }, }, contributors: { select: { id: true, username: true, name: true, avatar: true, }, }, }, }); // Check if user has voted const userVote = session?.user ? await db.promptVote.findUnique({ where: { userId_promptId: { userId: session.user.id, promptId: id, }, }, }) : null; // Fetch related prompts (via PromptConnection with label "related") const relatedConnections = await db.promptConnection.findMany({ where: { sourceId: id, label: "related", }, orderBy: { order: "asc" }, include: { target: { select: { id: true, title: true, slug: true, description: true, type: true, isPrivate: true, isUnlisted: true, deletedAt: true, author: { select: { id: true, name: true, username: true, avatar: true, }, }, category: { select: { id: true, name: true, slug: true, }, }, _count: { select: { votes: true }, }, }, }, }, }); // Filter out private, unlisted, or deleted related prompts const relatedPrompts = relatedConnections .map((conn) => conn.target) .filter((p) => !p.isPrivate && !p.isUnlisted && !p.deletedAt); if (!prompt) { notFound(); } // Check if user can view private prompt if (prompt.isPrivate && prompt.authorId !== session?.user?.id) { notFound(); } // Unlisted prompts are accessible via direct link (like YouTube unlisted videos) // They just don't appear in public listings, search results, or feeds const isOwner = session?.user?.id === prompt.authorId; const canEdit = isOwner || isAdmin; const voteCount = prompt._count?.votes ?? 0; const hasVoted = !!userVote; // Fetch change requests for this prompt const changeRequests = await db.changeRequest.findMany({ where: { promptId: id }, orderBy: { createdAt: "desc" }, include: { author: { select: { id: true, name: true, username: true, avatar: true, }, }, }, }); const pendingCount = changeRequests.filter((cr) => cr.status === "PENDING").length; const tChanges = await getTranslations("changeRequests"); const statusColors = { PENDING: "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20", APPROVED: "bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20", REJECTED: "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20", }; const statusIcons = { PENDING: Clock, APPROVED: Check, REJECTED: X, }; // Get delist reason (cast to expected type after Prisma migration) const delistReason = (prompt as { delistReason?: string | null }).delistReason as | "TOO_SHORT" | "NOT_ENGLISH" | "LOW_QUALITY" | "NOT_LLM_INSTRUCTION" | "MANUAL" | null; return ( <> {/* Structured Data for Rich Results */} <StructuredData type="prompt" data={{ prompt: { id: prompt.id, name: prompt.title, description: prompt.description || `AI prompt: ${prompt.title}`, content: prompt.content, author: prompt.author.name || prompt.author.username, authorUrl: `${process.env.NEXTAUTH_URL || "https://prompts.chat"}/@${prompt.author.username}`, datePublished: prompt.createdAt.toISOString(), dateModified: prompt.updatedAt.toISOString(), category: prompt.category?.name, tags: prompt.tags.map(({ tag }) => tag.name), voteCount: voteCount, }, }} /> <StructuredData type="breadcrumb" data={{ breadcrumbs: [ { name: "Home", url: "/" }, { name: "Prompts", url: "/prompts" }, ...(prompt.category ? [{ name: prompt.category.name, url: `/categories/${prompt.category.slug}` }] : []), { name: prompt.title, url: `/prompts/${prompt.id}` }, ], }} /> <div className="container max-w-4xl py-8"> {/* Deleted Banner - shown to admins when prompt is deleted */} {prompt.deletedAt && isAdmin && ( <div className="mb-6 p-4 rounded-lg border border-red-500/30 bg-red-500/5"> <div className="flex items-start gap-3"> <Trash2 className="h-5 w-5 text-red-500 shrink-0 mt-0.5" /> <div className="space-y-1 flex-1"> <h3 className="text-sm font-semibold text-red-700 dark:text-red-400"> {t("promptDeleted")} </h3> <p className="text-sm text-red-600 dark:text-red-500"> {t("promptDeletedDescription")} </p> </div> </div> <div className="flex justify-end mt-4"> <RestorePromptButton promptId={prompt.id} /> </div> </div> )} {/* Delist Banner - shown to owner and admins when prompt is delisted */} {prompt.isUnlisted && delistReason && (isOwner || isAdmin) && ( <DelistBanner promptId={prompt.id} delistReason={delistReason} isOwner={isOwner} isDeleted={!!prompt.deletedAt} /> )} {/* Header */} <div className="mb-6"> {/* Title row with upvote button */} <div className="flex items-center gap-4 mb-2"> <div className="shrink-0"> <UpvoteButton promptId={prompt.id} initialVoted={hasVoted} initialCount={voteCount} isLoggedIn={!!session?.user} size="circular" /> </div> <div className="flex-1 flex items-center justify-between gap-4 min-w-0"> <div className="flex items-center gap-2 flex-wrap min-w-0"> <h1 className="text-3xl font-bold">{prompt.title}</h1> {prompt.isPrivate && ( <Badge variant="secondary">{t("promptPrivate")}</Badge> )} </div> <div className="flex items-center gap-2 shrink-0"> {isOwner && ( <> <Button variant="outline" size="icon" asChild className="sm:hidden"> <Link href={`/prompts/${id}/edit`}> <Edit className="h-4 w-4" /> </Link> </Button> <Button variant="outline" asChild className="hidden sm:flex"> <Link href={`/prompts/${id}/edit`}> <Edit className="h-4 w-4 mr-2" /> {t("edit")} </Link> </Button> </> )} </div> </div> </div> {/* Description */} {prompt.description && ( <p className="text-muted-foreground">{prompt.description}</p> )} </div> <div className="border-b mb-6 sm:hidden" /> {/* Meta info */} <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground mb-6"> <div className="flex items-center gap-2"> <div className="flex -space-x-2"> <Link href={`/@${prompt.author.username}`} title={`@${prompt.author.username}`}> <Avatar className="h-6 w-6 border-2 border-background"> <AvatarImage src={prompt.author.avatar || undefined} /> <AvatarFallback className="text-xs">{prompt.author.name?.charAt(0) || prompt.author.username.charAt(0)}</AvatarFallback> </Avatar> </Link> {prompt.contributors.map((contributor) => ( <Link key={contributor.id} href={`/@${contributor.username}`} title={`@${contributor.username}`}> <Avatar className="h-6 w-6 border-2 border-background"> <AvatarImage src={contributor.avatar || undefined} /> <AvatarFallback className="text-xs">{contributor.name?.charAt(0) || contributor.username.charAt(0)}</AvatarFallback> </Avatar> </Link> ))} </div> {prompt.contributors.length > 0 ? ( <Tooltip> <TooltipTrigger asChild> <span className="cursor-default"> <Link href={`/@${prompt.author.username}`} className="hover:underline">@{prompt.author.username}</Link> +{prompt.contributors.length} </span> </TooltipTrigger> <TooltipContent side="bottom" className="p-2"> <div className="space-y-1"> <div className="text-xs font-medium mb-1.5">{t("promptContributors")}</div> {prompt.contributors.map((contributor) => ( <Link key={contributor.id} href={`/@${contributor.username}`} className="flex items-center gap-2 hover:underline rounded px-1 py-0.5 -mx-1" > <Avatar className="h-4 w-4"> <AvatarImage src={contributor.avatar || undefined} /> <AvatarFallback className="text-[8px]"> {contributor.name?.charAt(0) || contributor.username.charAt(0)} </AvatarFallback> </Avatar> <span className="text-xs">@{contributor.username}</span> </Link> ))} </div> </TooltipContent> </Tooltip> ) : ( <Link href={`/@${prompt.author.username}`} className="hover:underline">@{prompt.author.username}</Link> )} </div> {prompt.contributors.length > 0 && ( <div className="flex items-center gap-1.5"> <Users className="h-4 w-4" /> <span>{prompt.contributors.length + 1} {t("contributors")}</span> </div> )} <AnimatedDate date={prompt.createdAt} relativeText={formatDistanceToNow(prompt.createdAt, locale)} locale={locale} /> </div> {/* Category and Tags */} {(prompt.category || prompt.tags.length > 0) && ( <div className="flex flex-wrap items-center gap-2 mb-6"> {prompt.category && ( <Link href={`/categories/${prompt.category.slug}`}> <Badge variant="outline">{prompt.category.name}</Badge> </Link> )} {prompt.category && prompt.tags.length > 0 && ( <span className="text-muted-foreground">•</span> )} {prompt.tags.map(({ tag }) => ( <Link key={tag.id} href={`/tags/${tag.slug}`}> <Badge variant="secondary" style={{ backgroundColor: tag.color + "20", color: tag.color }} > {tag.name} </Badge> </Link> ))} </div> )} {/* Content Tabs */} <Tabs defaultValue="content"> <div className="flex flex-col gap-3 mb-4"> {/* Propose changes button - on top on mobile */} {!isOwner && session?.user && ( <div className="md:hidden"> <Button asChild size="sm" className="w-full"> <Link href={`/prompts/${id}/changes/new`}> <GitPullRequest className="h-4 w-4 mr-1.5" /> {t("createChangeRequest")} </Link> </Button> </div> )} <div className="flex items-center justify-between"> <TabsList> <TabsTrigger value="content">{t("promptContent")}</TabsTrigger> <TabsTrigger value="versions" className="gap-1"> <History className="h-4 w-4" /> {t("versions")} <Badge variant="secondary" className="ml-1 h-5 min-w-5 px-1 text-xs"> {prompt.versions.length > 0 ? prompt.versions[0].version : 1} </Badge> </TabsTrigger> {changeRequests.length > 0 && ( <TabsTrigger value="changes" className="gap-1"> <GitPullRequest className="h-4 w-4" /> <span className="hidden sm:inline">{t("changeRequests")}</span> {pendingCount > 0 && ( <Badge variant="destructive" className="ml-1 h-5 min-w-5 px-1 text-xs"> {pendingCount} </Badge> )} </TabsTrigger> )} </TabsList> {/* Propose changes button - inline on desktop */} {!isOwner && session?.user && ( <Button asChild size="sm" className="hidden md:inline-flex"> <Link href={`/prompts/${id}/changes/new`}> <GitPullRequest className="h-4 w-4 mr-1.5" /> {t("createChangeRequest")} </Link> </Button> )} </div> </div> <TabsContent value="content" className="space-y-4 mt-0"> {/* Media Preview (for image/video prompts) */} {prompt.mediaUrl && ( <MediaPreview mediaUrl={prompt.mediaUrl} title={prompt.title} type={prompt.type} /> )} {/* Prompt Text Content */} <div> {prompt.requiresMediaUpload && prompt.requiredMediaType && prompt.requiredMediaCount && ( <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-400 mb-3"> {prompt.requiredMediaType === "IMAGE" && <ImageIcon className="h-3.5 w-3.5" />} {prompt.requiredMediaType === "VIDEO" && <Video className="h-3.5 w-3.5" />} {prompt.requiredMediaType === "DOCUMENT" && <FileText className="h-3.5 w-3.5" />} <span className="text-xs font-medium"> {prompt.requiredMediaType === "IMAGE" ? t("requiresImage", { count: prompt.requiredMediaCount }) : prompt.requiredMediaType === "VIDEO" ? t("requiresVideo", { count: prompt.requiredMediaCount }) : t("requiresDocument", { count: prompt.requiredMediaCount })} </span> </div> )} {prompt.structuredFormat ? ( <InteractivePromptContent content={prompt.content} isStructured={true} structuredFormat={(prompt.structuredFormat?.toLowerCase() as "json" | "yaml") || "json"} title={t("promptContent")} isLoggedIn={!!session?.user} categoryName={prompt.category?.name} parentCategoryName={prompt.category?.parent?.name} promptId={prompt.id} promptSlug={prompt.slug ?? undefined} promptType={prompt.type} shareTitle={prompt.title} promptTitle={prompt.title} promptDescription={prompt.description ?? undefined} /> ) : ( <InteractivePromptContent content={prompt.content} title={t("promptContent")} isLoggedIn={!!session?.user} categoryName={prompt.category?.name} parentCategoryName={prompt.category?.parent?.name} promptId={prompt.id} promptSlug={prompt.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")} promptType={prompt.type} shareTitle={prompt.title} promptTitle={prompt.title} promptDescription={prompt.description ?? undefined} /> )} </div> {/* Report & Prompt Flow */} <PromptFlowSection promptId={prompt.id} promptTitle={prompt.title} canEdit={canEdit} isOwner={isOwner} isLoggedIn={!!session?.user} /> {/* Related Prompts */} {relatedPrompts.length > 0 && ( <RelatedPrompts prompts={relatedPrompts} /> )} {/* Comments Section */} {config.features.comments !== false && !prompt.isPrivate && ( <CommentSection promptId={prompt.id} currentUserId={session?.user?.id} isAdmin={isAdmin} isLoggedIn={!!session?.user} locale={locale} /> )} </TabsContent> <TabsContent value="versions" className="mt-0"> <div> <div className="flex items-center justify-between mb-3"> <h3 className="text-base font-semibold">{t("versionHistory")}</h3> <div className="flex items-center gap-2"> <VersionCompareModal versions={prompt.versions} currentContent={prompt.content} promptType={prompt.type} structuredFormat={prompt.structuredFormat} /> {canEdit && ( <AddVersionForm promptId={prompt.id} currentContent={prompt.content} /> )} </div> </div> {prompt.versions.length === 0 ? ( <p className="text-muted-foreground py-8 text-center">{t("noVersions")}</p> ) : ( <div className="divide-y border rounded-lg"> {prompt.versions.map((version, index) => { const isLatestVersion = index === 0; return ( <div key={version.id} className="px-4 py-3 flex items-start gap-3" > <div className="flex-1 min-w-0"> <div className="flex items-center gap-2"> <span className="text-sm font-medium">v{version.version}</span> {isLatestVersion && ( <span className="text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium"> {t("currentVersion")} </span> )} <span className="text-xs text-muted-foreground"> {formatDistanceToNow(version.createdAt, locale)} </span> <span className="text-xs text-muted-foreground"> by @{version.author.username} </span> </div> {version.changeNote && ( <p className="text-xs text-muted-foreground mt-0.5 truncate"> {version.changeNote} </p> )} </div> <div className="flex items-center gap-1 shrink-0"> {!isLatestVersion && ( <VersionCompareButton versionContent={version.content} versionNumber={version.version} currentContent={prompt.content} promptType={prompt.type} structuredFormat={prompt.structuredFormat} /> )} {canEdit && !isLatestVersion && ( <DeleteVersionButton promptId={prompt.id} versionId={version.id} versionNumber={version.version} /> )} </div> </div> ); })} </div> )} </div> </TabsContent> {changeRequests.length > 0 && ( <TabsContent value="changes" className="mt-0"> <div> <div className="flex items-center justify-between mb-3"> <h3 className="text-base font-semibold">{t("changeRequests")}</h3> </div> <div className="divide-y border rounded-lg"> {changeRequests.map((cr) => { const StatusIcon = statusIcons[cr.status]; const hasTitleChange = cr.proposedTitle && cr.proposedTitle !== cr.originalTitle; return ( <Link key={cr.id} href={`/prompts/${id}/changes/${cr.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-accent/50 transition-colors first:rounded-t-lg last:rounded-b-lg" > <div className={`p-1.5 rounded-full shrink-0 ${ cr.status === "PENDING" ? "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400" : cr.status === "APPROVED" ? "bg-green-500/10 text-green-600 dark:text-green-400" : "bg-red-500/10 text-red-600 dark:text-red-400" }`}> <StatusIcon className="h-4 w-4" /> </div> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2"> <span className="text-sm font-medium truncate"> {hasTitleChange ? ( <> <span className="line-through text-muted-foreground">{cr.originalTitle}</span> {" → "} <span>{cr.proposedTitle}</span> </> ) : ( tChanges("contentChanges") )} </span> </div> {cr.reason && ( <p className="text-xs text-muted-foreground mt-0.5 line-clamp-1"> {cr.reason} </p> )} </div> <div className="flex items-center gap-3 shrink-0"> <div className="flex items-center gap-2 text-xs text-muted-foreground"> <Avatar className="h-5 w-5"> <AvatarImage src={cr.author.avatar || undefined} /> <AvatarFallback className="text-[9px]"> {cr.author.name?.[0] || cr.author.username[0]} </AvatarFallback> </Avatar> <span className="hidden sm:inline">@{cr.author.username}</span> </div> <span className="text-xs text-muted-foreground hidden sm:inline"> {formatDistanceToNow(cr.createdAt, locale)} </span> <Badge variant="outline" className={`text-[10px] px-1.5 py-0 h-5 ${statusColors[cr.status]}`}> {tChanges(cr.status.toLowerCase())} </Badge> </div> </Link> ); })} </div> </div> </TabsContent> )} </Tabs> {/* Admin Area */} {isAdmin && ( <div className="mt-8 p-4 rounded-lg border border-red-500/30 bg-red-500/5"> <div className="flex items-center gap-2 mb-3"> <Shield className="h-4 w-4 text-red-500" /> <h3 className="text-sm font-semibold text-red-500">{t("adminArea")}</h3> </div> <div className="flex items-center gap-3"> <FeaturePromptButton promptId={prompt.id} isFeatured={prompt.isFeatured} /> <UnlistPromptButton promptId={prompt.id} isUnlisted={prompt.isUnlisted} /> <Button variant="outline" size="sm" asChild> <Link href={`/prompts/${id}/edit`}> <Edit className="h-4 w-4 mr-2" /> {t("edit")} </Link> </Button> </div> </div> )} </div> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/loading.tsx
src/app/prompts/[id]/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function PromptDetailLoading() { return ( <div className="container max-w-4xl py-8"> {/* Breadcrumb */} <div className="flex items-center gap-2 mb-4"> <Skeleton className="h-4 w-16" /> <Skeleton className="h-4 w-4" /> <Skeleton className="h-4 w-24" /> </div> {/* Title & Actions */} <div className="flex items-start justify-between gap-4 mb-4"> <div className="flex-1"> <Skeleton className="h-8 w-3/4 mb-2" /> <div className="flex items-center gap-2"> <Skeleton className="h-6 w-6 rounded-full" /> <Skeleton className="h-4 w-24" /> <Skeleton className="h-4 w-20" /> </div> </div> <div className="flex gap-2"> <Skeleton className="h-9 w-20" /> <Skeleton className="h-9 w-9" /> </div> </div> {/* Description */} <Skeleton className="h-4 w-full mb-2" /> <Skeleton className="h-4 w-2/3 mb-6" /> {/* Tags */} <div className="flex gap-2 mb-6"> <Skeleton className="h-6 w-16 rounded-full" /> <Skeleton className="h-6 w-20 rounded-full" /> <Skeleton className="h-6 w-14 rounded-full" /> </div> {/* Tabs */} <Skeleton className="h-9 w-64 mb-4" /> {/* Content */} <div className="border rounded-lg p-4 space-y-3"> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-3/4" /> <Skeleton className="h-4 w-full" /> <Skeleton className="h-4 w-5/6" /> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/twitter-image.tsx
src/app/prompts/[id]/twitter-image.tsx
export { default, alt, size, contentType } from "./opengraph-image";
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/edit/page.tsx
src/app/prompts/[id]/edit/page.tsx
import { Metadata } from "next"; import { notFound, redirect } from "next/navigation"; import { getTranslations } from "next-intl/server"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { PromptForm } from "@/components/prompts/prompt-form"; import { isAIGenerationEnabled, getAIModelName } from "@/lib/ai/generation"; interface EditPromptPageProps { params: Promise<{ id: string }>; } /** * Extracts the prompt ID from a URL parameter that may contain a slug */ function extractPromptId(idParam: string): string { const underscoreIndex = idParam.indexOf("_"); if (underscoreIndex !== -1) { return idParam.substring(0, underscoreIndex); } return idParam; } export const metadata: Metadata = { title: "Edit Prompt", description: "Edit your prompt", }; export default async function EditPromptPage({ params }: EditPromptPageProps) { const { id: idParam } = await params; const id = extractPromptId(idParam); const session = await auth(); const t = await getTranslations("prompts"); if (!session?.user) { redirect("/login"); } // Fetch the prompt const prompt = await db.prompt.findUnique({ where: { id }, include: { tags: { include: { tag: true, }, }, contributors: { select: { id: true, username: true, name: true, avatar: true, }, }, }, }); if (!prompt) { notFound(); } // Check if user is the author or admin const isAuthor = prompt.authorId === session.user.id; const isAdmin = session.user.role === "ADMIN"; if (!isAuthor && !isAdmin) { redirect(`/prompts/${id}`); } // Fetch categories and tags for the form const [categories, tags] = await Promise.all([ db.category.findMany({ orderBy: [{ order: "asc" }, { name: "asc" }], select: { id: true, name: true, slug: true, parentId: true, }, }), db.tag.findMany({ orderBy: { name: "asc" } }), ]); // Transform prompt data for the form const initialData = { title: prompt.title, description: prompt.description || "", content: prompt.content, type: ((prompt.type === "IMAGE" || prompt.type === "VIDEO" || prompt.type === "AUDIO" || prompt.type === "SKILL") ? prompt.type : "TEXT") as "TEXT" | "IMAGE" | "VIDEO" | "AUDIO" | "SKILL", structuredFormat: prompt.structuredFormat ? (prompt.structuredFormat as "JSON" | "YAML") : undefined, categoryId: prompt.categoryId || undefined, tagIds: prompt.tags.map((t) => t.tagId), isPrivate: prompt.isPrivate, mediaUrl: prompt.mediaUrl || "", requiresMediaUpload: prompt.requiresMediaUpload, requiredMediaType: (prompt.requiredMediaType as "IMAGE" | "VIDEO" | "DOCUMENT") || "IMAGE", requiredMediaCount: prompt.requiredMediaCount || 1, }; // Check if AI generation is enabled const aiGenerationEnabled = await isAIGenerationEnabled(); const aiModelName = getAIModelName(); return ( <div className="container max-w-3xl py-8"> <PromptForm categories={categories} tags={tags} initialData={initialData} initialContributors={prompt.contributors} promptId={id} mode="edit" aiGenerationEnabled={aiGenerationEnabled} aiModelName={aiModelName} /> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/changes/new/page.tsx
src/app/prompts/[id]/changes/new/page.tsx
import { redirect, notFound } from "next/navigation"; import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { ArrowLeft } from "lucide-react"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Button } from "@/components/ui/button"; import { ChangeRequestForm } from "@/components/prompts/change-request-form"; interface NewChangeRequestPageProps { params: Promise<{ id: string }>; } /** * Extracts the prompt ID from a URL parameter that may contain a slug */ function extractPromptId(idParam: string): string { const underscoreIndex = idParam.indexOf("_"); if (underscoreIndex !== -1) { return idParam.substring(0, underscoreIndex); } return idParam; } export default async function NewChangeRequestPage({ params }: NewChangeRequestPageProps) { const session = await auth(); const t = await getTranslations("changeRequests"); if (!session?.user) { redirect("/login"); } const { id: idParam } = await params; const id = extractPromptId(idParam); const prompt = await db.prompt.findUnique({ where: { id }, select: { id: true, title: true, content: true, type: true, structuredFormat: true, authorId: true, isPrivate: true, }, }); if (!prompt) { notFound(); } // Can't create change request for own prompt if (prompt.authorId === session.user.id) { redirect(`/prompts/${id}`); } // Can't create change request for private prompt if (prompt.isPrivate) { notFound(); } return ( <div className="container max-w-3xl py-6"> {/* Header */} <div className="mb-6"> <Button variant="ghost" size="sm" asChild className="mb-4 -ml-2"> <Link href={`/prompts/${id}`}> <ArrowLeft className="h-4 w-4 mr-1.5" /> {t("backToPrompt")} </Link> </Button> <h1 className="text-xl font-semibold">{t("create")}</h1> <p className="text-sm text-muted-foreground mt-1"> {prompt.title} </p> </div> {/* Form */} <ChangeRequestForm promptId={prompt.id} currentContent={prompt.content} currentTitle={prompt.title} promptType={prompt.type} structuredFormat={prompt.structuredFormat} /> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/prompts/[id]/changes/[changeId]/page.tsx
src/app/prompts/[id]/changes/[changeId]/page.tsx
import { notFound } from "next/navigation"; import Link from "next/link"; import { getTranslations, getLocale } from "next-intl/server"; import { formatDistanceToNow } from "@/lib/date"; import { ArrowLeft, Clock, Check, X, FileText } from "lucide-react"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { DiffView } from "@/components/ui/diff-view"; import { ChangeRequestActions } from "@/components/prompts/change-request-actions"; import { ReopenChangeRequestButton } from "@/components/prompts/reopen-change-request-button"; import { DismissChangeRequestButton } from "@/components/prompts/dismiss-change-request-button"; interface ChangeRequestPageProps { params: Promise<{ id: string; changeId: string }>; } /** * Extracts the prompt ID from a URL parameter that may contain a slug */ function extractPromptId(idParam: string): string { const underscoreIndex = idParam.indexOf("_"); if (underscoreIndex !== -1) { return idParam.substring(0, underscoreIndex); } return idParam; } export default async function ChangeRequestPage({ params }: ChangeRequestPageProps) { const session = await auth(); const t = await getTranslations("changeRequests"); const locale = await getLocale(); const { id: idParam, changeId } = await params; const promptId = extractPromptId(idParam); const changeRequest = await db.changeRequest.findUnique({ where: { id: changeId }, include: { author: { select: { id: true, name: true, username: true, avatar: true, }, }, prompt: { select: { id: true, title: true, content: true, authorId: true, }, }, }, }); if (!changeRequest || changeRequest.prompt.id !== promptId) { notFound(); } const isPromptOwner = session?.user?.id === changeRequest.prompt.authorId; const isChangeRequestAuthor = session?.user?.id === changeRequest.author.id; const statusConfig = { PENDING: { color: "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20", icon: Clock, }, APPROVED: { color: "bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20", icon: Check, }, REJECTED: { color: "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20", icon: X, }, }; const StatusIcon = statusConfig[changeRequest.status].icon; const hasTitleChange = changeRequest.proposedTitle && changeRequest.proposedTitle !== changeRequest.originalTitle; return ( <div className="container max-w-3xl py-6"> {/* Header */} <div className="mb-6"> <Button variant="ghost" size="sm" asChild className="mb-4 -ml-2"> <Link href={`/prompts/${promptId}`}> <ArrowLeft className="h-4 w-4 mr-1.5" /> {t("backToPrompt")} </Link> </Button> {/* Title and status */} <div className="flex items-start justify-between gap-4"> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2 flex-wrap"> <h1 className="text-xl font-semibold">{t("title")}</h1> <Badge className={statusConfig[changeRequest.status].color}> <StatusIcon className="h-3 w-3 mr-1" /> {t(changeRequest.status.toLowerCase())} </Badge> </div> <Link href={`/prompts/${promptId}`} className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1.5 mt-1" > <FileText className="h-3.5 w-3.5" /> {changeRequest.prompt.title} </Link> </div> </div> {/* Author and time */} <div className="flex items-center gap-2 mt-4 pt-4 border-t"> <Avatar className="h-6 w-6"> <AvatarImage src={changeRequest.author.avatar || ""} /> <AvatarFallback className="text-xs">{changeRequest.author.name?.[0] || changeRequest.author.username[0]}</AvatarFallback> </Avatar> <span className="text-sm"> <Link href={`/@${changeRequest.author.username}`} className="font-medium hover:underline"> @{changeRequest.author.username} </Link> <span className="text-muted-foreground"> · {formatDistanceToNow(changeRequest.createdAt, locale)}</span> </span> </div> </div> {/* Reason */} {changeRequest.reason && ( <div className="mb-6 p-4 bg-muted/30 rounded-lg border"> <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">{t("reason")}</p> <p className="text-sm whitespace-pre-wrap">{changeRequest.reason}</p> </div> )} {/* Title change */} {hasTitleChange && ( <div className="mb-6 p-4 bg-muted/30 rounded-lg border"> <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">{t("titleChange")}</p> <div className="text-sm"> <span className="text-red-600 dark:text-red-400 line-through">{changeRequest.originalTitle}</span> <span className="text-muted-foreground mx-2">→</span> <span className="text-green-600 dark:text-green-400">{changeRequest.proposedTitle}</span> </div> </div> )} {/* Content diff */} <div className="mb-6"> <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">{t("contentChanges")}</p> <DiffView original={changeRequest.originalContent} modified={changeRequest.proposedContent} /> </div> {/* Review note (if exists) */} {changeRequest.reviewNote && ( <div className="mb-6 p-4 rounded-lg border border-blue-500/20 bg-blue-500/5"> <p className="text-xs font-medium text-blue-600 dark:text-blue-400 uppercase tracking-wide mb-2">{t("reviewNote")}</p> <p className="text-sm whitespace-pre-wrap">{changeRequest.reviewNote}</p> </div> )} {/* Actions for prompt owner */} {isPromptOwner && changeRequest.status === "PENDING" && ( <div className="pt-4 border-t"> <ChangeRequestActions changeRequestId={changeRequest.id} promptId={promptId} /> </div> )} {/* Reopen button for rejected requests */} {isPromptOwner && changeRequest.status === "REJECTED" && ( <div className="pt-4 border-t"> <ReopenChangeRequestButton changeRequestId={changeRequest.id} promptId={promptId} /> </div> )} {/* Dismiss button for change request author (pending only) */} {isChangeRequestAuthor && changeRequest.status === "PENDING" && ( <div className="pt-4 border-t"> <DismissChangeRequestButton changeRequestId={changeRequest.id} promptId={promptId} /> </div> )} </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/categories/page.tsx
src/app/categories/page.tsx
import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { unstable_cache } from "next/cache"; import { FolderOpen, ChevronRight } from "lucide-react"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import { SubscribeButton } from "@/components/categories/subscribe-button"; // Visible prompt filter const visiblePromptFilter = { isPrivate: false, isUnlisted: false, deletedAt: null, }; // Cached categories query with filtered prompt counts const getCategories = unstable_cache( async () => { const categories = await db.category.findMany({ where: { parentId: null }, orderBy: { order: "asc" }, include: { children: { orderBy: { order: "asc" }, }, }, }); // Get all category IDs (parents + children) const allCategoryIds = categories.flatMap((c) => [c.id, ...c.children.map((child) => child.id)]); // Count visible prompts per category in one query const counts = await db.prompt.groupBy({ by: ["categoryId"], where: { categoryId: { in: allCategoryIds }, ...visiblePromptFilter, }, _count: true, }); const countMap = new Map(counts.map((c) => [c.categoryId, c._count])); // Attach counts to categories return categories.map((category) => ({ ...category, promptCount: countMap.get(category.id) || 0, children: category.children.map((child) => ({ ...child, promptCount: countMap.get(child.id) || 0, })), })); }, ["categories-page"], { tags: ["categories"] } ); export default async function CategoriesPage() { const t = await getTranslations("categories"); const session = await auth(); // Fetch root categories (no parent) with their children (cached) const rootCategories = await getCategories(); // Get user's subscriptions if logged in const subscriptions = session?.user ? await db.categorySubscription.findMany({ where: { userId: session.user.id }, select: { categoryId: true }, }) : []; const subscribedIds = new Set(subscriptions.map((s) => s.categoryId)); return ( <div className="container py-6"> <div className="mb-6"> <h1 className="text-lg font-semibold">{t("title")}</h1> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> {rootCategories.length === 0 ? ( <div className="text-center py-12 border rounded-lg bg-muted/30"> <FolderOpen className="h-10 w-10 text-muted-foreground mx-auto mb-3" /> <p className="text-sm text-muted-foreground">{t("noCategories")}</p> </div> ) : ( <div className="divide-y"> {rootCategories.map((category) => ( <section key={category.id} className="py-6 first:pt-0"> {/* Main Category Header */} <div className="flex items-start gap-3 mb-3"> {category.icon && ( <span className="text-xl mt-0.5">{category.icon}</span> )} <div className="min-w-0"> <div className="flex items-center gap-1.5"> <Link href={`/categories/${category.slug}`} className="font-semibold hover:underline inline-flex items-center gap-1" > {category.name} <ChevronRight className="h-4 w-4" /> </Link> {session?.user && ( <SubscribeButton categoryId={category.id} categoryName={category.name} initialSubscribed={subscribedIds.has(category.id)} iconOnly /> )} <span className="text-xs text-muted-foreground"> {category.promptCount} {t("prompts")} </span> </div> {category.description && ( <p className="text-sm text-muted-foreground mt-0.5"> {category.description} </p> )} </div> </div> {/* Subcategories List */} {category.children.length > 0 && ( <div className="ml-8 space-y-1"> {category.children.map((child) => ( <div key={child.id} className="group py-2 px-3 -mx-3 rounded-md hover:bg-muted/50 transition-colors" > <div className="flex items-center gap-2"> {child.icon && ( <span className="text-sm">{child.icon}</span> )} <Link href={`/categories/${child.slug}`} className="text-sm font-medium hover:underline" > {child.name} </Link> {session?.user && ( <SubscribeButton categoryId={child.id} categoryName={child.name} initialSubscribed={subscribedIds.has(child.id)} iconOnly /> )} <span className="text-xs text-muted-foreground"> {child.promptCount} </span> </div> {child.description && ( <p className="text-xs text-muted-foreground mt-1 ml-6 line-clamp-1"> {child.description} </p> )} </div> ))} </div> )} </section> ))} </div> )} </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/categories/loading.tsx
src/app/categories/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function CategoriesLoading() { return ( <div className="container py-6"> {/* Header */} <div className="mb-6"> <Skeleton className="h-6 w-32 mb-2" /> <Skeleton className="h-4 w-48" /> </div> {/* Category List */} <div className="divide-y"> {Array.from({ length: 4 }).map((_, i) => ( <div key={i} className="py-6 first:pt-0"> <div className="flex items-center gap-3 mb-3"> <Skeleton className="h-8 w-8 rounded" /> <Skeleton className="h-5 w-32" /> <Skeleton className="h-5 w-12" /> </div> <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3 pl-11"> {Array.from({ length: 3 }).map((_, j) => ( <Skeleton key={j} className="h-10 w-full rounded-lg" /> ))} </div> </div> ))} </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/categories/[slug]/page.tsx
src/app/categories/[slug]/page.tsx
import { Metadata } from "next"; import { notFound } from "next/navigation"; import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { ArrowLeft } from "lucide-react"; import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; import config from "@/../prompts.config"; import { Button } from "@/components/ui/button"; import { PromptList } from "@/components/prompts/prompt-list"; import { SubscribeButton } from "@/components/categories/subscribe-button"; import { CategoryFilters } from "@/components/categories/category-filters"; import { McpServerPopup } from "@/components/mcp/mcp-server-popup"; interface CategoryPageProps { params: Promise<{ slug: string }>; searchParams: Promise<{ page?: string; sort?: string; q?: string }>; } const PROMPTS_PER_PAGE = 30; export async function generateMetadata({ params }: CategoryPageProps): Promise<Metadata> { const { slug } = await params; const category = await db.category.findUnique({ where: { slug }, select: { name: true, description: true }, }); if (!category) { return { title: "Category Not Found" }; } return { title: category.name, description: category.description || `Browse prompts in ${category.name}`, }; } export default async function CategoryPage({ params, searchParams }: CategoryPageProps) { const { slug } = await params; const { page, sort, q } = await searchParams; const currentPage = Math.max(1, parseInt(page || "1", 10) || 1); const sortOption = sort || "newest"; const session = await auth(); const t = await getTranslations(); const category = await db.category.findUnique({ where: { slug }, include: { _count: { select: { prompts: true, subscribers: true }, }, }, }); if (!category) { notFound(); } // Check if user is subscribed const isSubscribed = session?.user ? await db.categorySubscription.findUnique({ where: { userId_categoryId: { userId: session.user.id, categoryId: category.id, }, }, }) : null; // Build where clause with optional search const whereClause = { categoryId: category.id, isPrivate: false, isUnlisted: false, deletedAt: null, ...(q && { OR: [ { title: { contains: q, mode: "insensitive" as const } }, { content: { contains: q, mode: "insensitive" as const } }, ], }), }; // Build orderBy based on sort option const getOrderBy = () => { switch (sortOption) { case "oldest": return { createdAt: "asc" as const }; case "most_upvoted": return { votes: { _count: "desc" as const } }; case "most_contributors": return { contributors: { _count: "desc" as const } }; default: return { createdAt: "desc" as const }; } }; // Count total prompts for pagination const totalPrompts = await db.prompt.count({ where: whereClause }); const totalPages = Math.ceil(totalPrompts / PROMPTS_PER_PAGE); // Fetch prompts in this category const promptsRaw = await db.prompt.findMany({ where: whereClause, orderBy: getOrderBy(), skip: (currentPage - 1) * PROMPTS_PER_PAGE, take: PROMPTS_PER_PAGE, include: { author: { select: { id: true, name: true, username: true, avatar: true, verified: true, }, }, category: { include: { parent: { select: { id: true, name: true, slug: true }, }, }, }, tags: { include: { tag: true, }, }, _count: { select: { votes: true, contributors: true }, }, }, }); const prompts = promptsRaw.map((p) => ({ ...p, voteCount: p._count.votes, contributorCount: p._count.contributors, })); return ( <div className="container py-6"> {/* Header */} <div className="mb-6"> <Button variant="ghost" size="sm" className="mb-4 -ml-2" asChild> <Link href="/categories"> <ArrowLeft className="h-4 w-4 mr-1" /> {t("categories.allCategories")} </Link> </Button> <div className="flex items-start justify-between gap-4"> <div> <div className="flex items-center gap-2"> <h1 className="text-xl font-semibold">{category.name}</h1> {session?.user && ( <SubscribeButton categoryId={category.id} categoryName={category.name} initialSubscribed={!!isSubscribed} pill /> )} </div> {category.description && ( <p className="text-sm text-muted-foreground mt-1"> {category.description} </p> )} <div className="flex items-center gap-3 mt-2 text-sm text-muted-foreground"> <span>{t("categories.promptCount", { count: totalPrompts })}</span> <span>•</span> <span>{t("categories.subscriberCount", { count: category._count.subscribers })}</span> </div> </div> <div className="hidden md:flex items-center gap-2"> <CategoryFilters categorySlug={slug} /> {config.features.mcp !== false && <McpServerPopup initialCategories={[slug]} showOfficialBranding={!config.homepage?.useCloneBranding} />} </div> </div> {/* Mobile filters */} <div className="flex md:hidden items-center gap-2 mt-4"> <CategoryFilters categorySlug={slug} /> {config.features.mcp !== false && <McpServerPopup initialCategories={[slug]} showOfficialBranding={!config.homepage?.useCloneBranding} />} </div> </div> {/* Prompts */} <PromptList prompts={prompts} currentPage={currentPage} totalPages={totalPages} /> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/docs/self-hosting/page.tsx
src/app/docs/self-hosting/page.tsx
import Link from "next/link"; import Image from "next/image"; import { Server, Database, Key, Palette, Globe, Settings, Cpu } from "lucide-react"; import DeepWikiIcon from "@/../public/deepwiki.svg"; import Context7Icon from "@/../public/context7.svg"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; export const metadata = { title: "Self-Hosting Guide - prompts.chat", description: "Deploy your own prompts.chat instance with customizable branding, themes, and authentication", }; export default function SelfHostingPage() { return ( <div className="container max-w-4xl py-10"> <h1 className="text-2xl font-bold mb-2">Self-Hosting Guide</h1> <p className="text-muted-foreground mb-8"> Deploy your own prompts.chat instance with customizable branding, themes, and authentication. </p> <div className="prose prose-neutral dark:prose-invert max-w-none space-y-10"> {/* Features */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Server className="h-5 w-5" /> What You Get </h2> <ul className="list-disc list-inside text-muted-foreground space-y-1"> <li>Curated prompt library with 100+ community-tested prompts</li> <li>Custom branding, logos, and themes</li> <li>Multiple auth providers (GitHub, Google, Azure, credentials)</li> <li>AI-powered semantic search and generation (optional)</li> <li>Multi-language support (11 locales)</li> <li>CC0 licensed - use freely for any purpose</li> </ul> </section> {/* Using Documentation AI-Agents */} <section className="space-y-6"> <h2 className="text-xl font-bold">Using Documentation AI-Agents</h2> <div className="grid md:grid-cols-2 gap-6"> {/* DeepWiki */} <div className="space-y-4"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Image src={DeepWikiIcon} alt="" width={20} height={20} /> DeepWiki </h3> <p className="text-muted-foreground"> <Link href="https://deepwiki.com/f/awesome-chatgpt-prompts" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > DeepWiki </Link> {" "}provides AI-powered documentation and insights for this repository. </p> <ul className="list-disc list-inside text-muted-foreground space-y-1 text-sm"> <li>AI-generated documentation from source code</li> <li>Interactive codebase exploration</li> <li>Architecture diagrams and component relationships</li> <li>Available as an MCP server</li> </ul> </div> {/* Context7 */} <div className="space-y-4"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Image src={Context7Icon} alt="" width={20} height={20} className="rounded" /> Context7 </h3> <p className="text-muted-foreground"> <Link href="https://context7.com/f/awesome-chatgpt-prompts?tab=chat" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > Context7 </Link> {" "}is an AI-powered chat interface for exploring and understanding this repository. </p> <ul className="list-disc list-inside text-muted-foreground space-y-1 text-sm"> <li>Chat with the codebase using natural language</li> <li>Get answers with code references</li> <li>Understand implementation details quickly</li> <li>Available as an MCP server</li> </ul> </div> </div> </section> {/* Manually */} <section className="space-y-6"> <h2 className="text-xl font-bold">Manually</h2> {/* Prerequisites */} <div className="space-y-4"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Database className="h-5 w-5" /> Prerequisites </h3> <ul className="list-disc list-inside text-muted-foreground space-y-1"> <li>Node.js 18+</li> <li>PostgreSQL database</li> <li>npm or yarn</li> </ul> </div> {/* Installation */} <div className="space-y-4"> <h3 className="text-lg font-semibold">Quick Start</h3> <div className="bg-muted rounded-lg p-4 font-mono text-sm space-y-1 overflow-x-auto"> <p className="text-muted-foreground"># Clone the repository</p> <p>git clone https://github.com/f/awesome-chatgpt-prompts.git</p> <p>cd awesome-chatgpt-prompts</p> <p className="text-muted-foreground mt-3"># Install dependencies</p> <p>npm install</p> <p className="text-muted-foreground mt-3"># Configure environment</p> <p>cp .env.example .env</p> <p className="text-muted-foreground mt-3"># Run migrations & seed</p> <p>npm run db:migrate</p> <p>npm run db:seed</p> <p className="text-muted-foreground mt-3"># Start development server</p> <p>npm run dev</p> </div> </div> {/* Environment Variables */} <div className="space-y-6"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Key className="h-5 w-5" /> Environment Variables </h3> <p className="text-muted-foreground"> Create a <code className="bg-muted px-1.5 py-0.5 rounded text-sm">.env</code> file based on <code className="bg-muted px-1.5 py-0.5 rounded text-sm">.env.example</code>: </p> {/* Core Variables */} <div className="space-y-3"> <h3 className="font-medium">Core (Required)</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[240px]">Variable</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">DATABASE_URL</TableCell> <TableCell className="text-muted-foreground text-sm">PostgreSQL connection string. Add <code className="text-xs">?connection_limit=5&pool_timeout=10</code> for serverless.</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">NEXTAUTH_URL</TableCell> <TableCell className="text-muted-foreground text-sm">Your app URL (e.g., <code className="text-xs">http://localhost:3000</code>)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">NEXTAUTH_SECRET</TableCell> <TableCell className="text-muted-foreground text-sm">Random secret for NextAuth session encryption</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* OAuth Variables */} <div className="space-y-3"> <h3 className="font-medium">OAuth Providers (Optional)</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[240px]">Variable</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">GITHUB_CLIENT_ID</TableCell> <TableCell className="text-muted-foreground text-sm">GitHub OAuth App client ID</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">GITHUB_CLIENT_SECRET</TableCell> <TableCell className="text-muted-foreground text-sm">GitHub OAuth App client secret</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">GOOGLE_CLIENT_ID</TableCell> <TableCell className="text-muted-foreground text-sm">Google OAuth client ID</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">GOOGLE_CLIENT_SECRET</TableCell> <TableCell className="text-muted-foreground text-sm">Google OAuth client secret</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">AZURE_AD_CLIENT_ID</TableCell> <TableCell className="text-muted-foreground text-sm">Azure AD application client ID</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">AZURE_AD_CLIENT_SECRET</TableCell> <TableCell className="text-muted-foreground text-sm">Azure AD application client secret</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">AZURE_AD_TENANT_ID</TableCell> <TableCell className="text-muted-foreground text-sm">Azure AD tenant ID</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* Storage Variables */} <div className="space-y-3"> <h3 className="font-medium">Storage Providers (Optional)</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[240px]">Variable</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">ENABLED_STORAGE</TableCell> <TableCell className="text-muted-foreground text-sm"><code className="text-xs">url</code> | <code className="text-xs">s3</code> | <code className="text-xs">do-spaces</code></TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">S3_BUCKET</TableCell> <TableCell className="text-muted-foreground text-sm">S3 bucket name</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">S3_REGION</TableCell> <TableCell className="text-muted-foreground text-sm">S3 region (e.g., us-east-1)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">S3_ACCESS_KEY_ID</TableCell> <TableCell className="text-muted-foreground text-sm">S3 access key</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">S3_SECRET_ACCESS_KEY</TableCell> <TableCell className="text-muted-foreground text-sm">S3 secret key</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">S3_ENDPOINT</TableCell> <TableCell className="text-muted-foreground text-sm">Custom endpoint for S3-compatible services (MinIO, etc.)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">DO_SPACES_*</TableCell> <TableCell className="text-muted-foreground text-sm">DigitalOcean Spaces: BUCKET, REGION, ACCESS_KEY_ID, SECRET_ACCESS_KEY, CDN_ENDPOINT</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* AI Variables */} <div className="space-y-3"> <h3 className="font-medium">AI Features (Optional)</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[240px]">Variable</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">OPENAI_API_KEY</TableCell> <TableCell className="text-muted-foreground text-sm">OpenAI API key for AI search and generation</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">OPENAI_BASE_URL</TableCell> <TableCell className="text-muted-foreground text-sm">Custom base URL for OpenAI-compatible APIs</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">OPENAI_EMBEDDING_MODEL</TableCell> <TableCell className="text-muted-foreground text-sm">Embedding model (default: <code className="text-xs">text-embedding-3-small</code>)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">OPENAI_GENERATIVE_MODEL</TableCell> <TableCell className="text-muted-foreground text-sm">Generative model (default: <code className="text-xs">gpt-4o-mini</code>)</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* Analytics */} <div className="space-y-3"> <h3 className="font-medium">Analytics (Optional)</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[240px]">Variable</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">GOOGLE_ANALYTICS_ID</TableCell> <TableCell className="text-muted-foreground text-sm">Google Analytics measurement ID (e.g., <code className="text-xs">G-XXXXXXXXX</code>)</TableCell> </TableRow> </TableBody> </Table> </div> </div> </div> {/* Configuration */} <div className="space-y-6"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Palette className="h-5 w-5" /> Configuration (prompts.config.ts) </h3> <p className="text-muted-foreground"> Customize your instance by editing <code className="bg-muted px-1.5 py-0.5 rounded text-sm">prompts.config.ts</code>: </p> {/* Branding */} <div className="space-y-3"> <h3 className="font-medium">Branding</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[160px]">Option</TableHead> <TableHead className="w-[120px]">Type</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">name</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">Your app name displayed in header and footer</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">logo</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">Path to logo for light mode</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">logoDark</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">Path to logo for dark mode</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">favicon</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">Path to favicon</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">description</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">App description for SEO and homepage</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* Theme */} <div className="space-y-3"> <h3 className="font-medium">Theme</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[160px]">Option</TableHead> <TableHead className="w-[200px]">Values</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">radius</TableCell> <TableCell className="text-muted-foreground text-xs"><code>none</code> | <code>sm</code> | <code>md</code> | <code>lg</code></TableCell> <TableCell className="text-muted-foreground text-sm">Border radius for UI components</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">variant</TableCell> <TableCell className="text-muted-foreground text-xs"><code>flat</code> | <code>default</code> | <code>brutal</code></TableCell> <TableCell className="text-muted-foreground text-sm">UI style variant</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">density</TableCell> <TableCell className="text-muted-foreground text-xs"><code>compact</code> | <code>default</code> | <code>comfortable</code></TableCell> <TableCell className="text-muted-foreground text-sm">Spacing density</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">colors.primary</TableCell> <TableCell className="text-muted-foreground text-xs">hex or oklch</TableCell> <TableCell className="text-muted-foreground text-sm">Primary brand color (e.g., <code>#6366f1</code>)</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* Auth */} <div className="space-y-3"> <h3 className="font-medium">Authentication</h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[160px]">Option</TableHead> <TableHead className="w-[200px]">Values</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">providers</TableCell> <TableCell className="text-muted-foreground text-xs">array</TableCell> <TableCell className="text-muted-foreground text-sm"><code>credentials</code>, <code>github</code>, <code>google</code>, <code>azure</code></TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">allowRegistration</TableCell> <TableCell className="text-muted-foreground text-xs">boolean</TableCell> <TableCell className="text-muted-foreground text-sm">Allow public sign-up (credentials provider only)</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* i18n */} <div className="space-y-3"> <h3 className="font-medium flex items-center gap-2"> <Globe className="h-4 w-4" /> Internationalization </h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[160px]">Option</TableHead> <TableHead className="w-[200px]">Type</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">locales</TableCell> <TableCell className="text-muted-foreground text-xs">string[]</TableCell> <TableCell className="text-muted-foreground text-sm">Supported locales: en, tr, es, zh, ja, ar, pt, fr, it, de, ko</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">defaultLocale</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-muted-foreground text-sm">Default language</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* Features */} <div className="space-y-3"> <h3 className="font-medium flex items-center gap-2"> <Cpu className="h-4 w-4" /> Features </h3> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[160px]">Option</TableHead> <TableHead className="w-[100px]">Default</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">privatePrompts</TableCell> <TableCell className="text-muted-foreground text-xs">true</TableCell> <TableCell className="text-muted-foreground text-sm">Allow users to create private prompts</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">changeRequests</TableCell> <TableCell className="text-muted-foreground text-xs">true</TableCell> <TableCell className="text-muted-foreground text-sm">Enable version control with change requests</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">categories</TableCell> <TableCell className="text-muted-foreground text-xs">true</TableCell> <TableCell className="text-muted-foreground text-sm">Enable prompt categories</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">tags</TableCell> <TableCell className="text-muted-foreground text-xs">true</TableCell> <TableCell className="text-muted-foreground text-sm">Enable prompt tags</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">aiSearch</TableCell> <TableCell className="text-muted-foreground text-xs">false</TableCell> <TableCell className="text-muted-foreground text-sm">AI-powered semantic search (requires OPENAI_API_KEY)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">aiGeneration</TableCell> <TableCell className="text-muted-foreground text-xs">false</TableCell> <TableCell className="text-muted-foreground text-sm">AI-powered generation features (requires OPENAI_API_KEY)</TableCell> </TableRow> </TableBody> </Table> </div> </div> </div> {/* White-label */} <div className="space-y-4"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Settings className="h-5 w-5" /> White-Label Mode </h3> <p className="text-muted-foreground"> Set <code className="bg-muted px-1.5 py-0.5 rounded text-sm">useCloneBranding = true</code> at the top of the config to: </p> <ul className="list-disc list-inside text-muted-foreground space-y-1"> <li>Display your branding name and description on the homepage</li> <li>Use your logo as the hero background watermark</li> <li>Hide prompts.chat achievements (GitHub stars, Forbes, etc.)</li> <li>Hide sponsor section and &quot;Become a Sponsor&quot; CTA</li> <li>Hide &quot;Clone on GitHub&quot; button</li> </ul> <div className="bg-muted rounded-lg p-4 font-mono text-sm"> <p className="text-muted-foreground">{"// prompts.config.ts"}</p> <p>const useCloneBranding = true;</p> </div> </div> {/* Production */} <div className="space-y-4"> <h3 className="text-lg font-semibold flex items-center gap-2"> <Globe className="h-5 w-5" /> Production Deployment </h3> <div className="bg-muted rounded-lg p-4 font-mono text-sm space-y-1"> <p>npm run build</p> <p>npm run start</p> </div> <p className="text-muted-foreground"> Deploy to Vercel, Railway, Render, or any Node.js hosting platform. Make sure to set all environment variables in your hosting provider&apos;s dashboard. </p> </div> {/* Support */} <div className="space-y-4"> <h3 className="text-lg font-semibold">Support</h3> <p className="text-muted-foreground"> For issues and questions, please open a{" "} <Link href="https://github.com/f/awesome-chatgpt-prompts/issues" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > GitHub Issue </Link> . For the complete documentation, see the{" "} <Link href="https://github.com/f/awesome-chatgpt-prompts/blob/main/SELF-HOSTING.md" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > SELF-HOSTING.md </Link> {" "}file in the repository. </p> </div> </section> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/docs/api/page.tsx
src/app/docs/api/page.tsx
import Link from "next/link"; import { headers } from "next/headers"; import { Code, Zap, Terminal, Search, Box, Key, Save, Sparkles } from "lucide-react"; import { ImprovePromptDemo } from "@/components/api/improve-prompt-demo"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { McpConfigTabs } from "@/components/mcp/mcp-config-tabs"; import config from "@/../prompts.config"; export const metadata = { title: "API Documentation - prompts.chat", description: "API for searching and discovering AI prompts programmatically", }; export default async function ApiDocsPage() { const headersList = await headers(); const host = headersList.get("host") || "prompts.chat"; const protocol = host.includes("localhost") ? "http" : "https"; const baseUrl = `${protocol}://${host}`; return ( <div className="container max-w-4xl py-10"> <h1 className="text-2xl font-bold mb-2">API Documentation</h1> <p className="text-muted-foreground mb-8"> {config.features.mcp !== false ? "prompts.chat provides an MCP-first API for searching and discovering AI prompts programmatically. Use the MCP endpoint directly with any MCP-compatible client, or make standard HTTP requests." : "prompts.chat provides an API for searching and discovering AI prompts programmatically." } </p> <div className="prose prose-neutral dark:prose-invert max-w-none space-y-10"> {config.features.mcp !== false && ( <> {/* MCP Overview */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Zap className="h-5 w-5" /> MCP-First API </h2> <p className="text-muted-foreground"> Our API is built on the{" "} <Link href="https://modelcontextprotocol.io" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > Model Context Protocol (MCP) </Link> , enabling seamless integration with AI assistants, IDEs, and automation tools. The same endpoint works for both MCP clients and traditional REST-style requests. </p> <div className="bg-muted rounded-lg p-4 font-mono text-sm"> <p className="text-muted-foreground"># MCP Endpoint</p> <p>POST {baseUrl}/api/mcp</p> </div> </section> {/* Using with MCP Clients */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Terminal className="h-5 w-5" /> Using with MCP Clients </h2> <p className="text-muted-foreground"> Add prompts.chat to your MCP client configuration. Choose your client and connection type below: </p> <McpConfigTabs baseUrl={baseUrl} className="[&_button]:text-sm [&_button]:px-3 [&_button]:py-1.5 [&_pre]:text-sm [&_pre]:p-4" /> <p className="text-muted-foreground text-sm"> <strong>Remote</strong> connects directly to prompts.chat API. <strong>Local</strong> runs the MCP server locally via npx. </p> </section> {/* Authentication */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Key className="h-5 w-5" /> Authentication </h2> <p className="text-muted-foreground"> Most API features work without authentication. However, to save prompts via MCP or access your private prompts, you need to authenticate using an API key. </p> <div className="bg-muted/50 rounded-lg p-4 text-sm space-y-3"> <div> <p className="font-medium">Generate an API Key</p> <p className="text-muted-foreground"> Go to{" "} <Link href="/settings" className="underline hover:text-foreground"> Settings </Link> {" "}to generate your API key. Keys start with <code className="bg-muted px-1.5 py-0.5 rounded">pchat_</code>. </p> </div> <div> <p className="font-medium">Using the API Key</p> <p className="text-muted-foreground"> Pass your API key via the <code className="bg-muted px-1.5 py-0.5 rounded">PROMPTS_API_KEY</code> header. </p> </div> </div> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Remote: HTTP transport with headers "prompts-chat": { "url": "${baseUrl}/api/mcp", "headers": { "PROMPTS_API_KEY": "pchat_your_api_key_here" } } # Local: stdio transport with environment variable "prompts-chat": { "command": "npx", "args": ["-y", "@fkadev/prompts.chat-mcp"], "env": { "PROMPTS_API_KEY": "pchat_your_api_key_here" } } # Or via curl (remote) curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "PROMPTS_API_KEY: pchat_your_api_key_here" \\ -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'`}</pre> </div> <p className="text-muted-foreground text-sm"> <strong>Remote (HTTP)</strong> sends requests to prompts.chat with the API key in headers. <strong> Local (stdio)</strong> runs the MCP server locally via npx with the API key as an environment variable. With authentication, you can use the <code className="bg-muted px-1.5 py-0.5 rounded">save_prompt</code> tool and search results will include your private prompts. </p> </section> {/* MCP Prompts */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Terminal className="h-5 w-5" /> MCP Prompts </h2> <p className="text-muted-foreground"> All public prompts are exposed as native MCP prompts. This allows MCP clients to list and use prompts directly via slash commands or prompt pickers. You can filter prompts by category or tag using URL query parameters. </p> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Filter by users (one or more usernames) "prompts-chat": { "url": "${baseUrl}/api/mcp?users=f,torvalds" } # Filter by categories "prompts-chat": { "url": "${baseUrl}/api/mcp?categories=coding,marketing" } # Filter by tags "prompts-chat": { "url": "${baseUrl}/api/mcp?tags=chatgpt,writing" } # Combine filters "prompts-chat": { "url": "${baseUrl}/api/mcp?users=f&categories=coding&tags=js" }`}</pre> </div> <div className="bg-muted/50 rounded-lg p-4 text-sm space-y-3"> <div> <p className="font-medium">prompts/list</p> <p className="text-muted-foreground">Browse all available prompts with pagination support.</p> </div> <div> <p className="font-medium">prompts/get</p> <p className="text-muted-foreground"> Retrieve a prompt by ID. Variables ({"${name}"} or {"${name:default}"}) are automatically substituted with provided arguments. </p> </div> </div> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# List prompts curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "Accept: application/json, text/event-stream" \\ -d '{"jsonrpc": "2.0", "id": 1, "method": "prompts/list"}' # Get a specific prompt with arguments curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "Accept: application/json, text/event-stream" \\ -d '{ "jsonrpc": "2.0", "id": 2, "method": "prompts/get", "params": { "name": "code-review-assistant", "arguments": { "topic": "AI safety" } } }'`}</pre> </div> </section> {/* Available Tools */} <section className="space-y-6"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Box className="h-5 w-5" /> Available Tools </h2> {/* search_prompts Tool */} <div className="space-y-4"> <h3 className="font-medium flex items-center gap-2"> <Search className="h-4 w-4" /> search_prompts </h3> <p className="text-muted-foreground"> Search for AI prompts by keyword. Returns matching prompts with title, description, content, author, category, and tags. </p> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[120px]">Parameter</TableHead> <TableHead className="w-[100px]">Type</TableHead> <TableHead className="w-[80px]">Required</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">query</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">Yes</TableCell> <TableCell className="text-muted-foreground text-sm">Search query to find relevant prompts</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">limit</TableCell> <TableCell className="text-muted-foreground text-xs">number</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Maximum results (default: 10, max: 50)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">type</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm"> Filter by type: <code className="text-xs">TEXT</code>, <code className="text-xs">STRUCTURED</code>, <code className="text-xs">IMAGE</code>, <code className="text-xs">VIDEO</code>, <code className="text-xs">AUDIO</code> </TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">category</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Filter by category slug</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">tag</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Filter by tag slug</TableCell> </TableRow> </TableBody> </Table> </div> </div> {/* get_prompt Tool */} <div className="space-y-4"> <h3 className="font-medium flex items-center gap-2"> <Box className="h-4 w-4" /> get_prompt </h3> <p className="text-muted-foreground"> Get a prompt by ID. If the prompt contains template variables (like {"${variable}"} or {"${variable:default}"}), the MCP client will be asked to provide values through elicitation. </p> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[120px]">Parameter</TableHead> <TableHead className="w-[100px]">Type</TableHead> <TableHead className="w-[80px]">Required</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">id</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">Yes</TableCell> <TableCell className="text-muted-foreground text-sm">The ID of the prompt to retrieve</TableCell> </TableRow> </TableBody> </Table> </div> <div className="bg-muted/50 rounded-lg p-4 text-sm"> <p className="font-medium mb-2">Variable Elicitation</p> <p className="text-muted-foreground"> When a prompt contains variables like {"${name}"} or {"${topic:default value}"}, MCP clients that support elicitation will prompt the user to fill in these values. Variables with default values (after the colon) are optional. The prompt content will be returned with variables replaced. </p> </div> </div> {/* save_prompt Tool */} <div className="space-y-4"> <h3 className="font-medium flex items-center gap-2"> <Save className="h-4 w-4" /> save_prompt <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Requires Auth</span> </h3> <p className="text-muted-foreground"> Save a new prompt to your account. Requires API key authentication. Prompts are private by default unless you&apos;ve changed the default in your settings. </p> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[140px]">Parameter</TableHead> <TableHead className="w-[100px]">Type</TableHead> <TableHead className="w-[80px]">Required</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">title</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">Yes</TableCell> <TableCell className="text-muted-foreground text-sm">Title of the prompt (max 200 chars)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">content</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">Yes</TableCell> <TableCell className="text-muted-foreground text-sm">The prompt content. Can include variables like {"${var}"}</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">description</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Optional description (max 500 chars)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">tags</TableCell> <TableCell className="text-muted-foreground text-xs">string[]</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Array of tag names (max 10)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">category</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Category slug</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">isPrivate</TableCell> <TableCell className="text-muted-foreground text-xs">boolean</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm">Override default privacy setting</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">type</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm"> <code className="text-xs">TEXT</code> (default), <code className="text-xs">STRUCTURED</code>, <code className="text-xs">IMAGE</code>, <code className="text-xs">VIDEO</code>, <code className="text-xs">AUDIO</code> </TableCell> </TableRow> </TableBody> </Table> </div> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Save a prompt via MCP curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "PROMPTS_API_KEY: pchat_your_api_key_here" \\ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "save_prompt", "arguments": { "title": "My Code Review Prompt", "content": "Review this code for \${language} best practices:\\n\\n\${code}", "description": "A helpful code review assistant", "tags": ["coding", "review"], "isPrivate": false } } }'`}</pre> </div> </div> {/* improve_prompt Tool */} <div className="space-y-4"> <h3 className="font-medium flex items-center gap-2"> <Sparkles className="h-4 w-4" /> improve_prompt <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Requires Auth</span> </h3> <p className="text-muted-foreground"> Transform a basic prompt into a well-structured, comprehensive prompt using AI. Searches for similar prompts for inspiration and generates improved versions. </p> <div className="border rounded-lg overflow-hidden"> <Table> <TableHeader> <TableRow> <TableHead className="w-[140px]">Parameter</TableHead> <TableHead className="w-[100px]">Type</TableHead> <TableHead className="w-[80px]">Required</TableHead> <TableHead>Description</TableHead> </TableRow> </TableHeader> <TableBody> <TableRow> <TableCell className="font-mono text-xs">prompt</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">Yes</TableCell> <TableCell className="text-muted-foreground text-sm">The prompt to improve (max 10,000 chars)</TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">outputType</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm"> Content type: <code className="text-xs">text</code> (default), <code className="text-xs">image</code>, <code className="text-xs">video</code>, <code className="text-xs">sound</code> </TableCell> </TableRow> <TableRow> <TableCell className="font-mono text-xs">outputFormat</TableCell> <TableCell className="text-muted-foreground text-xs">string</TableCell> <TableCell className="text-xs">No</TableCell> <TableCell className="text-muted-foreground text-sm"> Response format: <code className="text-xs">text</code> (default), <code className="text-xs">structured_json</code>, <code className="text-xs">structured_yaml</code> </TableCell> </TableRow> </TableBody> </Table> </div> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Improve a prompt via MCP curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "PROMPTS_API_KEY: pchat_your_api_key_here" \\ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "improve_prompt", "arguments": { "prompt": "write a blog post about AI", "outputType": "text", "outputFormat": "text" } } }'`}</pre> </div> </div> </section> {/* MCP Protocol Example */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Code className="h-5 w-5" /> MCP Protocol Examples </h2> <div className="space-y-3"> <h3 className="font-medium">Initialize Connection</h3> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "Accept: application/json, text/event-stream" \\ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "my-app", "version": "1.0.0" } } }'`}</pre> </div> </div> <div className="space-y-3"> <h3 className="font-medium">List Available Tools</h3> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "Accept: application/json, text/event-stream" \\ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }'`}</pre> </div> </div> <div className="space-y-3"> <h3 className="font-medium">Search Prompts</h3> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`curl -X POST ${baseUrl}/api/mcp \\ -H "Content-Type: application/json" \\ -H "Accept: application/json, text/event-stream" \\ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "search_prompts", "arguments": { "query": "code review", "limit": 5 } } }'`}</pre> </div> </div> </section> {/* Response Format */} <section className="space-y-4"> <h2 className="text-lg font-semibold">Response Format</h2> <p className="text-muted-foreground"> The <code className="bg-muted px-1.5 py-0.5 rounded text-sm">search_prompts</code> tool returns results in the following format: </p> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`{ "query": "code review", "count": 2, "prompts": [ { "id": "abc123", "title": "Code Review Assistant", "description": "A prompt for conducting thorough code reviews", "content": "You are an expert code reviewer...", "type": "TEXT", "author": "username", "category": "Development", "tags": ["coding", "review", "development"], "votes": 42, "createdAt": "2024-01-15T10:30:00.000Z" } ] }`}</pre> </div> </section> </> )} {/* Improve Prompt API */} <section className="space-y-4"> <h2 className="text-lg font-semibold flex items-center gap-2"> <Sparkles className="h-5 w-5" /> Improve Prompt API <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Requires Auth</span> </h2> <p className="text-muted-foreground"> Transform basic prompts into well-structured, comprehensive prompts using AI. The API uses embeddings to find similar prompts for inspiration and generates improved versions while preserving the original intent. Requires API key authentication. </p> <div className="border rounded-lg overflow-hidden"> <table className="w-full"> <thead className="bg-muted/50"> <tr> <th className="text-left p-3 text-sm font-medium w-[120px]">Parameter</th> <th className="text-left p-3 text-sm font-medium w-[100px]">Type</th> <th className="text-left p-3 text-sm font-medium w-[80px]">Required</th> <th className="text-left p-3 text-sm font-medium">Description</th> </tr> </thead> <tbody> <tr className="border-t"> <td className="p-3 font-mono text-xs">prompt</td> <td className="p-3 text-muted-foreground text-xs">string</td> <td className="p-3 text-xs">Yes</td> <td className="p-3 text-muted-foreground text-sm">The prompt to improve (max 10,000 chars)</td> </tr> <tr className="border-t"> <td className="p-3 font-mono text-xs">outputType</td> <td className="p-3 text-muted-foreground text-xs">string</td> <td className="p-3 text-xs">No</td> <td className="p-3 text-muted-foreground text-sm"> Content type: <code className="text-xs">text</code> (default), <code className="text-xs">image</code>, <code className="text-xs">video</code>, <code className="text-xs">sound</code> </td> </tr> <tr className="border-t"> <td className="p-3 font-mono text-xs">outputFormat</td> <td className="p-3 text-muted-foreground text-xs">string</td> <td className="p-3 text-xs">No</td> <td className="p-3 text-muted-foreground text-sm"> Response format: <code className="text-xs">text</code> (default), <code className="text-xs">structured_json</code>, <code className="text-xs">structured_yaml</code> </td> </tr> </tbody> </table> </div> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Improve a prompt curl -X POST ${baseUrl}/api/improve-prompt \\ -H "Content-Type: application/json" \\ -H "X-API-Key: pchat_your_api_key_here" \\ -d '{ "prompt": "write a blog post about AI", "outputType": "text", "outputFormat": "text" }'`}</pre> </div> <div className="bg-muted/50 rounded-lg p-4 text-sm space-y-3"> <div> <p className="font-medium">Response Format</p> <pre className="mt-2 text-xs text-muted-foreground">{`{ "original": "write a blog post about AI", "improved": "You are an expert technology writer...\n\n## Task\nWrite an engaging blog post...", "outputType": "text", "outputFormat": "text", "inspirations": [ { "title": "Blog Writer", "similarity": 85 }, { "title": "Content Creator", "similarity": 72 } ], "model": "gpt-4o" }`}</pre> </div> </div> <div className="pt-4"> <h3 className="font-medium mb-4">Try It Out</h3> <ImprovePromptDemo /> </div> </section> {/* REST API Alternative */} <section className="space-y-4"> <h2 className="text-lg font-semibold">REST API</h2> <p className="text-muted-foreground"> Use the standard REST endpoint to search and retrieve prompts: </p> <div className="bg-muted rounded-lg p-4 font-mono text-sm overflow-x-auto"> <pre>{`# Search prompts via REST curl "${baseUrl}/api/prompts?q=code+review&perPage=10" # Get prompt by ID curl "${baseUrl}/api/prompts/{id}"`}</pre> </div> </section> {/* Rate Limits */} <section className="space-y-4"> <h2 className="text-lg font-semibold">Rate Limits</h2> <p className="text-muted-foreground"> The API is public and free to use. Please be respectful with request frequency. For high-volume usage, consider{" "} <Link href="/docs/self-hosting" className="underline hover:text-foreground" > self-hosting your own instance </Link> . </p> </section> {/* Support */} <section className="space-y-4"> <h2 className="text-lg font-semibold">Support</h2> <p className="text-muted-foreground"> For issues and feature requests, please open a{" "} <Link href="https://github.com/f/awesome-chatgpt-prompts/issues" target="_blank" rel="noopener noreferrer" className="underline hover:text-foreground" > GitHub Issue </Link> . </p> </section> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/embed/page.tsx
src/app/embed/page.tsx
"use client"; import { useSearchParams } from "next/navigation"; import { Suspense, useEffect, useState, useMemo } from "react"; import { cn } from "@/lib/utils"; import { RunPromptButton } from "@/components/prompts/run-prompt-button"; interface TreeNode { name: string; path: string; isFolder: boolean; children: TreeNode[]; } function buildFileTree(paths: string[]): TreeNode[] { const root: TreeNode[] = []; for (const path of paths) { const parts = path.split("/").filter(Boolean); let currentLevel = root; let currentPath = ""; for (let i = 0; i < parts.length; i++) { const part = parts[i]; currentPath = currentPath ? `${currentPath}/${part}` : part; const isLastPart = i === parts.length - 1; const isFolder = path.endsWith("/") ? true : !isLastPart; let existing = currentLevel.find(n => n.name === part); if (!existing) { existing = { name: part, path: isFolder ? `${currentPath}/` : currentPath, isFolder, children: [], }; currentLevel.push(existing); } if (isFolder) { currentLevel = existing.children; } } } // Sort: folders first, then alphabetically const sortNodes = (nodes: TreeNode[]): TreeNode[] => { return nodes .sort((a, b) => { if (a.isFolder && !b.isFolder) return -1; if (!a.isFolder && b.isFolder) return 1; return a.name.localeCompare(b.name); }) .map(n => ({ ...n, children: sortNodes(n.children) })); }; return sortNodes(root); } interface EmbedConfig { prompt: string; context: string[]; model: string; mode: string; thinking: boolean; reasoning: boolean; planning: boolean; fast: boolean; max: boolean; lightColor: string; darkColor: string; themeMode: "auto" | "light" | "dark"; filetree: string[]; showDiff: boolean; diffFilename: string; diffOldText: string; diffNewText: string; flashButton: string; mcpTools: string[]; } function EmbedContent() { const searchParams = useSearchParams(); const [isDark, setIsDark] = useState(false); const [diffCollapsed, setDiffCollapsed] = useState(false); const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set()); const config: EmbedConfig = { prompt: searchParams?.get("prompt") || "", context: searchParams?.get("context")?.split(",").map(c => c.trim()).filter(Boolean) || [], model: searchParams?.get("model") || "GPT 4o", mode: searchParams?.get("mode") || "chat", thinking: searchParams?.get("thinking") === "true", reasoning: searchParams?.get("reasoning") === "true", planning: searchParams?.get("planning") === "true", fast: searchParams?.get("fast") === "true", max: searchParams?.get("max") === "true", lightColor: searchParams?.get("lightColor") || "#3b82f6", darkColor: searchParams?.get("darkColor") || "#60a5fa", themeMode: (searchParams?.get("themeMode") as EmbedConfig["themeMode"]) || "auto", filetree: searchParams?.get("filetree")?.split("\n").filter(Boolean) || [], showDiff: searchParams?.get("showDiff") === "true", diffFilename: searchParams?.get("diffFilename") || "", diffOldText: searchParams?.get("diffOldText") || "", diffNewText: searchParams?.get("diffNewText") || "", flashButton: searchParams?.get("flashButton") || "none", mcpTools: searchParams?.get("mcpTools")?.split("\n").filter(Boolean) || [], }; useEffect(() => { let dark = false; if (config.themeMode === "dark") { dark = true; } else if (config.themeMode === "light") { dark = false; } else { dark = window.matchMedia("(prefers-color-scheme: dark)").matches; } setIsDark(dark); // Set dark class on html element for portals (dropdowns, modals) if (dark) { document.documentElement.classList.add("dark"); } else { document.documentElement.classList.remove("dark"); } }, [config.themeMode]); const primaryColor = isDark ? config.darkColor : config.lightColor; const hexToRgb = (hex: string) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? `${parseInt(result[1], 16)} ${parseInt(result[2], 16)} ${parseInt(result[3], 16)}` : "59 130 246"; }; const hexToRgba = (hex: string, alpha: number) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (result) { const r = parseInt(result[1], 16); const g = parseInt(result[2], 16); const b = parseInt(result[3], 16); return `rgba(${r}, ${g}, ${b}, ${alpha})`; } return `rgba(59, 130, 246, ${alpha})`; }; const highlightMentions = (text: string) => { return text.replace(/@(\w+)/g, '<span class="mention">@$1</span>'); }; const renderContextPill = (context: string) => { let icon = null; let usesPrimary = false; if (context.startsWith("@")) { usesPrimary = true; } else if (context.startsWith("http")) { usesPrimary = true; icon = ( <svg className="w-3 h-3" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM4.332 8.027a6.012 6.012 0 011.912-2.706C6.512 5.73 6.974 6 7.5 6A1.5 1.5 0 019 7.5V8a2 2 0 004 0 2 2 0 011.523-1.943A5.977 5.977 0 0116 10c0 .34-.028.675-.083 1H15a2 2 0 00-2 2v2.197A5.973 5.973 0 0110 16v-2a2 2 0 00-2-2 2 2 0 01-2-2 2 2 0 00-1.668-1.973z" clipRule="evenodd"/> </svg> ); } else if (context.startsWith("#")) { usesPrimary = true; icon = ( <svg className="w-3 h-3" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clipRule="evenodd"/> </svg> ); } else if (context.endsWith("/")) { icon = ( <svg className="w-3 h-3" viewBox="0 0 20 20" fill="currentColor"> <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"/> </svg> ); } else if (context.includes(".")) { icon = ( <svg className="w-3 h-3" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M4 2a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V7.414A2 2 0 0017.414 6L14 2.586A2 2 0 0012.586 2H4zm2 4a1 1 0 011-1h4a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7zm-1 5a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1z" clipRule="evenodd"/> </svg> ); } const pillStyle = usesPrimary ? { backgroundColor: hexToRgba(primaryColor, 0.1), color: primaryColor, border: `1px solid ${hexToRgba(primaryColor, 0.2)}`, } : { backgroundColor: isDark ? "rgba(38,38,38,0.5)" : "rgba(248,250,252,1)", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }; return ( <span key={context} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={pillStyle} > {icon} <span>{context.startsWith("#") ? context.substring(1) : context}</span> </span> ); }; const toggleFileSelection = (file: string) => { setSelectedFiles(prev => { const next = new Set(prev); if (next.has(file)) { next.delete(file); } else { next.add(file); } return next; }); }; const allContextPills = [...config.context, ...Array.from(selectedFiles)]; const fileTree = useMemo(() => buildFileTree(config.filetree), [config.filetree]); const renderTreeNode = (node: TreeNode, depth: number = 0): React.ReactNode => { const isSelected = selectedFiles.has(node.path); return ( <div key={node.path}> <button onClick={() => !node.isFolder && toggleFileSelection(node.path)} className="w-full flex items-center gap-1.5 py-0.5 text-[10px] rounded transition-colors text-left" style={{ paddingLeft: `${depth * 12 + 8}px`, paddingRight: "8px", backgroundColor: isSelected ? hexToRgba(primaryColor, 0.1) : "transparent", color: isSelected ? primaryColor : (isDark ? "#e5e5e5" : "#374151"), }} > {node.isFolder ? ( <svg className="w-3 h-3 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor"> <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"/> </svg> ) : ( <svg className="w-3 h-3 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M4 2a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V7.414A2 2 0 0017.414 6L14 2.586A2 2 0 0012.586 2H4z" clipRule="evenodd"/> </svg> )} <span className="truncate">{node.name}</span> </button> {node.children.length > 0 && ( <div> {node.children.map(child => renderTreeNode(child, depth + 1))} </div> )} </div> ); }; return ( <div className={cn("h-screen flex", isDark ? "dark" : "")} style={{ ["--primary" as string]: hexToRgb(primaryColor), ["--background" as string]: isDark ? "26 26 26" : "255 255 255", ["--foreground" as string]: isDark ? "250 250 250" : "15 23 42", ["--muted" as string]: isDark ? "38 38 38" : "248 250 252", ["--muted-foreground" as string]: isDark ? "163 163 163" : "100 116 139", ["--border" as string]: isDark ? "64 64 64" : "226 232 240", } as React.CSSProperties} > <style jsx global>{` .mention { background-color: rgb(var(--primary) / 0.1); color: rgb(var(--primary)); padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-weight: 500; } .bg-primary\\/10 { background-color: rgb(var(--primary) / 0.1); } .text-primary { color: rgb(var(--primary)); } .border-primary\\/20 { border-color: rgb(var(--primary) / 0.2); } .bg-muted { background-color: rgb(var(--muted)); } .text-foreground { color: rgb(var(--foreground)); } .border-border { border-color: rgb(var(--border)); } .text-muted-foreground { color: rgb(var(--muted-foreground)); } .bg-background { background-color: rgb(var(--background)); } `}</style> {/* File Sidebar */} {fileTree.length > 0 && ( <div className="w-40 sm:w-44 border-r flex-shrink-0 overflow-y-auto" style={{ backgroundColor: isDark ? "rgba(38,38,38,0.5)" : "#ffffff", borderColor: isDark ? "#404040" : "#e2e8f0", }} > <div className="p-2 border-b" style={{ borderColor: isDark ? "#404040" : "#e2e8f0" }} > <h3 className="text-[10px] font-semibold uppercase tracking-wider" style={{ color: isDark ? "#a3a3a3" : "#64748b" }} > Files </h3> </div> <div className="py-1"> {fileTree.map(node => renderTreeNode(node))} </div> </div> )} {/* Main Content */} <div className="flex-1 flex flex-col p-2 sm:p-4 h-full overflow-hidden relative" style={{ backgroundColor: isDark ? "#1a1a1a" : "#ffffff" }} > {/* Large Images (##image or ##image:Label) */} {allContextPills.filter(ctx => ctx.startsWith("##image")).length > 0 && ( <div className="flex flex-wrap gap-2 mb-2 flex-shrink-0"> {allContextPills.filter(ctx => ctx.startsWith("##image")).map((ctx, index) => { const label = ctx.includes(":") ? ctx.split(":")[1] : `Image ${index + 1}`; return ( <div key={`${ctx}-${index}`} className="relative w-24 h-24 rounded-lg overflow-hidden flex-shrink-0" style={{ border: `2px solid ${hexToRgba(primaryColor, 0.3)}` }} > <img src={`https://picsum.photos/200?sig=${index}`} alt={label} className="w-full h-full object-cover" /> <div className="absolute bottom-0 left-0 right-0 px-1.5 py-0.5 text-[8px] font-medium text-center" style={{ backgroundColor: hexToRgba(primaryColor, 0.9), color: "#fff", }} > {label} </div> </div> ); })} </div> )} {/* Context Pills (excluding ##image) */} {allContextPills.filter(ctx => !ctx.startsWith("##image")).length > 0 && ( <div className="flex flex-wrap gap-1.5 mb-2 flex-shrink-0"> {allContextPills.filter(ctx => !ctx.startsWith("##image")).map((ctx) => renderContextPill(ctx))} </div> )} {/* MCP Tools */} {config.mcpTools.length > 0 && ( <div className="flex flex-wrap gap-1.5 mb-2 flex-shrink-0"> {config.mcpTools.map((tool) => { const [server, toolName] = tool.includes(":") ? tool.split(":") : ["mcp", tool]; return ( <span key={tool} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "rgba(139,92,246,0.15)" : "rgba(139,92,246,0.1)", color: isDark ? "#a78bfa" : "#7c3aed", border: isDark ? "1px solid rgba(139,92,246,0.3)" : "1px solid rgba(139,92,246,0.2)", }} > <svg className="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/> </svg> <span className="opacity-60">{server}:</span> <span>{toolName}</span> </span> ); })} </div> )} {/* Diff View */} {config.showDiff && config.diffFilename && ( <div className={cn( "mb-2 flex-shrink-0 bg-muted border border-border rounded-lg p-2 transition-all", diffCollapsed && "py-1" )}> <div className="flex items-center justify-between"> <div className="flex items-center gap-1.5"> <svg className="w-3 h-3 text-primary flex-shrink-0" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M4 2a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V7.414A2 2 0 0017.414 6L14 2.586A2 2 0 0012.586 2H4zm2 4a1 1 0 011-1h4a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7zm-1 5a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1z" clipRule="evenodd"/> </svg> <span className="text-xs font-medium text-foreground truncate">{config.diffFilename}</span> </div> <div className="flex gap-1 items-center"> <div className="flex rounded-md overflow-hidden"> <button className={cn( "px-2 py-0.5 bg-green-500 hover:bg-green-600 text-white text-[10px] font-medium transition-colors flex items-center gap-0.5", config.flashButton === "accept" && "animate-pulse" )}> <svg className="w-2.5 h-2.5" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd"/> </svg> <span className="hidden sm:inline">Accept</span> </button> <button className={cn( "px-2 py-0.5 bg-red-500 hover:bg-red-600 text-white text-[10px] font-medium transition-colors flex items-center gap-0.5", config.flashButton === "reject" && "animate-pulse" )}> <svg className="w-2.5 h-2.5" viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd"/> </svg> <span className="hidden sm:inline">Reject</span> </button> </div> <button onClick={() => setDiffCollapsed(!diffCollapsed)} className="p-0.5 text-muted-foreground hover:text-foreground transition-colors" > <svg className={cn("w-3 h-3 transition-transform", diffCollapsed && "rotate-180")} viewBox="0 0 20 20" fill="currentColor"> <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd"/> </svg> </button> </div> </div> {!diffCollapsed && ( <div className="space-y-1 mt-1.5"> {config.diffOldText && ( <div className="p-2 rounded text-[10px] font-mono whitespace-pre-wrap max-h-20 overflow-y-auto" style={{ backgroundColor: isDark ? "rgba(127, 29, 29, 0.15)" : "rgba(254, 226, 226, 0.6)", color: isDark ? "#fca5a5" : "#b91c1c", border: isDark ? "1px solid rgba(127, 29, 29, 0.3)" : "1px solid rgba(252, 165, 165, 0.5)", }} > {config.diffOldText} </div> )} {config.diffNewText && ( <div className="p-2 rounded text-[10px] font-mono whitespace-pre-wrap max-h-20 overflow-y-auto" style={{ backgroundColor: isDark ? "rgba(20, 83, 45, 0.15)" : "rgba(220, 252, 231, 0.6)", color: isDark ? "#86efac" : "#15803d", border: isDark ? "1px solid rgba(20, 83, 45, 0.3)" : "1px solid rgba(134, 239, 172, 0.5)", }} > {config.diffNewText} </div> )} </div> )} </div> )} {/* Prompt Container */} <div className="flex-1 min-h-0 overflow-hidden"> <div className="h-full rounded-lg p-3 sm:p-4 overflow-y-auto" style={{ backgroundColor: isDark ? "rgba(38,38,38,0.5)" : "rgba(241,245,249,0.5)", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > {config.prompt ? ( <p className="text-sm whitespace-pre-wrap" style={{ color: isDark ? "#fafafa" : "#0f172a" }} dangerouslySetInnerHTML={{ __html: highlightMentions(config.prompt) }} /> ) : ( <p className="text-sm italic" style={{ color: isDark ? "#a3a3a3" : "#64748b" }} > Enter your prompt in the designer... </p> )} </div> </div> {/* Settings Pills + Run Button */} <div className="flex items-center justify-between mt-2 flex-shrink-0"> <div className="flex flex-wrap gap-1.5 items-center"> <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: hexToRgba(primaryColor, 0.1), color: primaryColor, border: `1px solid ${hexToRgba(primaryColor, 0.2)}`, }} > {config.mode.charAt(0).toUpperCase() + config.mode.slice(1)} </span> <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: hexToRgba(primaryColor, 0.1), color: primaryColor, border: `1px solid ${hexToRgba(primaryColor, 0.2)}`, }} > {config.model} </span> {(config.thinking || config.reasoning || config.planning || config.fast || config.max) && ( <span style={{ color: isDark ? "#a3a3a3" : "#64748b" }} className="text-[10px]">•</span> )} {config.thinking && ( <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "#262626" : "#f8fafc", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > Thinking </span> )} {config.reasoning && ( <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "#262626" : "#f8fafc", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > Reasoning </span> )} {config.planning && ( <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "#262626" : "#f8fafc", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > Planning </span> )} {config.fast && ( <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "#262626" : "#f8fafc", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > Fast </span> )} {config.max && ( <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ backgroundColor: isDark ? "#262626" : "#f8fafc", color: isDark ? "#fafafa" : "#0f172a", border: isDark ? "1px solid #404040" : "1px solid #e2e8f0", }} > Max </span> )} </div> <div className="flex items-center gap-2"> <a href="https://prompts.chat" target="_blank" rel="noopener noreferrer" className="flex items-center gap-1.5 text-[10px] font-medium transition-opacity hover:opacity-80" style={{ color: isDark ? "#a3a3a3" : "#64748b" }} > <img src={isDark ? "/logo-dark.svg" : "/logo.svg"} alt="prompts.chat" className="w-3.5 h-3.5" /> <span>prompts.chat</span> </a> {config.prompt && ( <div className={isDark ? "dark" : ""}> <RunPromptButton content={config.prompt} variant="outline" size="icon" className={`!h-6 !w-6 !p-0 [&_svg]:!h-3 [&_svg]:!w-3 ${isDark ? "!border-zinc-600 !bg-zinc-800 !text-zinc-200" : "!border-zinc-300 !bg-white !text-zinc-700"}`} /> </div> )} </div> </div> </div> </div> ); } export default function EmbedPage() { return ( <Suspense fallback={<div className="h-screen flex items-center justify-center">Loading...</div>}> <EmbedContent /> </Suspense> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/promptmasters/page.tsx
src/app/promptmasters/page.tsx
"use client"; import { useState, useEffect } from "react"; import Link from "next/link"; import { useTranslations } from "next-intl"; import { Trophy, Medal, Award } from "lucide-react"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Skeleton } from "@/components/ui/skeleton"; interface LeaderboardUser { id: string; name: string | null; username: string; avatar: string | null; totalUpvotes: number; promptCount: number; } interface LeaderboardData { period: string; leaderboard: LeaderboardUser[]; } function LeaderboardSkeleton() { return ( <div className="space-y-3"> {Array.from({ length: 10 }).map((_, i) => ( <div key={i} className="flex items-center gap-4 p-3"> <Skeleton className="h-8 w-8 rounded-full" /> <Skeleton className="h-10 w-10 rounded-full" /> <div className="flex-1"> <Skeleton className="h-4 w-32 mb-1" /> <Skeleton className="h-3 w-20" /> </div> <Skeleton className="h-6 w-16" /> </div> ))} </div> ); } function RankBadge({ rank }: { rank: number }) { if (rank === 1) { return <Trophy className="h-6 w-6 text-yellow-500" />; } else if (rank === 2) { return <Medal className="h-6 w-6 text-gray-400" />; } else if (rank === 3) { return <Award className="h-6 w-6 text-amber-600" />; } return ( <span className="w-6 h-6 flex items-center justify-center text-sm font-medium text-muted-foreground"> {rank} </span> ); } function LeaderboardList({ users }: { users: LeaderboardUser[] }) { const t = useTranslations("promptmasters"); if (users.length === 0) { return ( <div className="text-center py-12 text-muted-foreground"> {t("noData")} </div> ); } return ( <div className="divide-y"> {users.map((user, index) => ( <Link key={user.id} href={`/@${user.username}`} prefetch={false} className="flex items-center gap-4 p-3 hover:bg-muted/50 transition-colors" > <div className="w-8 flex justify-center"> <RankBadge rank={index + 1} /> </div> <Avatar className="h-10 w-10"> <AvatarImage src={user.avatar || undefined} alt={user.name || user.username} /> <AvatarFallback> {(user.name || user.username).slice(0, 2).toUpperCase()} </AvatarFallback> </Avatar> <div className="flex-1 min-w-0"> <p className="font-medium truncate">{user.name || user.username}</p> <p className="text-sm text-muted-foreground">@{user.username}</p> </div> <div className="flex items-center gap-4 text-sm"> <div className="text-center"> <p className="font-semibold">{user.promptCount}</p> <p className="text-xs text-muted-foreground">{t("prompts")}</p> </div> <div className="text-center"> <p className="font-semibold text-primary">{user.totalUpvotes}</p> <p className="text-xs text-muted-foreground">{t("upvotes")}</p> </div> </div> </Link> ))} </div> ); } export default function PromptmastersPage() { const t = useTranslations("promptmasters"); const [allTime, setAllTime] = useState<LeaderboardData | null>(null); const [monthly, setMonthly] = useState<LeaderboardData | null>(null); const [weekly, setWeekly] = useState<LeaderboardData | null>(null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchLeaderboards() { try { const [allRes, monthRes, weekRes] = await Promise.all([ fetch("/api/leaderboard?period=all"), fetch("/api/leaderboard?period=month"), fetch("/api/leaderboard?period=week"), ]); if (allRes.ok) setAllTime(await allRes.json()); if (monthRes.ok) setMonthly(await monthRes.json()); if (weekRes.ok) setWeekly(await weekRes.json()); } catch (error) { console.error("Failed to fetch leaderboards:", error); } finally { setLoading(false); } } fetchLeaderboards(); }, []); return ( <div className="container py-8"> <div className="max-w-3xl mx-auto"> <div className="text-center mb-8"> <div className="flex items-center justify-center gap-2 mb-2"> <Trophy className="h-8 w-8 text-yellow-500" /> <h1 className="text-3xl font-bold">{t("title")}</h1> </div> <p className="text-muted-foreground">{t("description")}</p> </div> <Tabs defaultValue="all" className="w-full"> <TabsList className="grid w-full grid-cols-3 mb-6"> <TabsTrigger value="all">{t("allTime")}</TabsTrigger> <TabsTrigger value="month">{t("thisMonth")}</TabsTrigger> <TabsTrigger value="week">{t("thisWeek")}</TabsTrigger> </TabsList> <TabsContent value="all" className="mt-0"> {loading ? ( <LeaderboardSkeleton /> ) : ( <LeaderboardList users={allTime?.leaderboard || []} /> )} </TabsContent> <TabsContent value="month" className="mt-0"> {loading ? ( <LeaderboardSkeleton /> ) : ( <LeaderboardList users={monthly?.leaderboard || []} /> )} </TabsContent> <TabsContent value="week" className="mt-0"> {loading ? ( <LeaderboardSkeleton /> ) : ( <LeaderboardList users={weekly?.leaderboard || []} /> )} </TabsContent> </Tabs> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/promptmasters/loading.tsx
src/app/promptmasters/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function PromptmastersLoading() { return ( <div className="container py-8"> <div className="max-w-3xl mx-auto"> {/* Header - centered */} <div className="text-center mb-8"> <div className="flex items-center justify-center gap-2 mb-2"> <Skeleton className="h-8 w-8 rounded" /> <Skeleton className="h-9 w-48" /> </div> <Skeleton className="h-4 w-64 mx-auto" /> </div> {/* Tabs */} <Skeleton className="h-10 w-full mb-6 rounded-lg" /> {/* Leaderboard */} <div className="divide-y"> {Array.from({ length: 10 }).map((_, i) => ( <div key={i} className="flex items-center gap-4 p-3"> <Skeleton className="h-6 w-8" /> <Skeleton className="h-10 w-10 rounded-full" /> <div className="flex-1"> <Skeleton className="h-5 w-32 mb-1" /> <Skeleton className="h-4 w-20" /> </div> <div className="flex gap-4"> <Skeleton className="h-10 w-12" /> <Skeleton className="h-10 w-12" /> </div> </div> ))} </div> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/discover/page.tsx
src/app/discover/page.tsx
import { DiscoveryPrompts } from "@/components/prompts/discovery-prompts"; import { StructuredData } from "@/components/seo/structured-data"; import { db } from "@/lib/db"; export default async function DiscoverPage() { // Fetch top prompts for structured data const topPrompts = await db.prompt.findMany({ where: { isPrivate: false, isUnlisted: false, deletedAt: null, }, orderBy: { votes: { _count: "desc" }, }, take: 10, select: { id: true, title: true, description: true, slug: true, }, }); const itemListData = topPrompts.map((prompt) => ({ name: prompt.title, url: `/prompts/${prompt.id}${prompt.slug ? `_${prompt.slug}` : ""}`, description: prompt.description || undefined, })); return ( <> <StructuredData type="itemList" data={{ items: itemListData }} /> <StructuredData type="breadcrumb" data={{ breadcrumbs: [ { name: "Home", url: "/" }, { name: "Discover", url: "/discover" }, ], }} /> <div className="flex flex-col"> <DiscoveryPrompts /> </div> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/app/discover/loading.tsx
src/app/discover/loading.tsx
import { Skeleton } from "@/components/ui/skeleton"; export default function DiscoverLoading() { return ( <div className="container py-6"> {/* Header */} <div className="mb-6"> <Skeleton className="h-6 w-32 mb-2" /> <Skeleton className="h-4 w-48" /> </div> {/* User Grid */} <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3"> {Array.from({ length: 9 }).map((_, i) => ( <div key={i} className="border rounded-lg p-4"> <div className="flex items-center gap-3"> <Skeleton className="h-12 w-12 rounded-full" /> <div className="flex-1"> <Skeleton className="h-5 w-28 mb-1" /> <Skeleton className="h-4 w-20" /> </div> </div> </div> ))} </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/hooks/use-mobile.ts
src/hooks/use-mobile.ts
"use client"; import { useState, useEffect } from "react"; export function useIsMobile(breakpoint: number = 768) { const [isMobile, setIsMobile] = useState(false); useEffect(() => { const checkMobile = () => { setIsMobile(window.innerWidth < breakpoint); }; checkMobile(); window.addEventListener("resize", checkMobile); return () => window.removeEventListener("resize", checkMobile); }, [breakpoint]); return isMobile; }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/pages/api/mcp.ts
src/pages/api/mcp.ts
import type { NextApiRequest, NextApiResponse } from "next"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { ElicitResultSchema, ListPromptsRequestSchema, GetPromptRequestSchema, type PrimitiveSchemaDefinition, } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; import { db } from "@/lib/db"; import { isValidApiKeyFormat } from "@/lib/api-key"; import { improvePrompt } from "@/lib/ai/improve-prompt"; interface AuthenticatedUser { id: string; username: string; mcpPromptsPublicByDefault: boolean; } async function authenticateApiKey(apiKey: string | null): Promise<AuthenticatedUser | null> { if (!apiKey || !isValidApiKeyFormat(apiKey)) { return null; } const user = await db.user.findUnique({ where: { apiKey }, select: { id: true, username: true, mcpPromptsPublicByDefault: true, }, }); return user; } interface ExtractedVariable { name: string; defaultValue?: string; } function slugify(text: string): string { return text .toLowerCase() .trim() .replace(/[^\w\s-]/g, "") .replace(/[\s_-]+/g, "-") .replace(/^-+|-+$/g, ""); } /** * Get the prompt name/slug for MCP. * Priority: slug > slugify(title) > id */ function getPromptName(prompt: { id: string; slug?: string | null; title: string }): string { if (prompt.slug) return prompt.slug; const titleSlug = slugify(prompt.title); if (titleSlug) return titleSlug; return prompt.id; } function extractVariables(content: string): ExtractedVariable[] { // Format: ${variableName} or ${variableName:default} const regex = /\$\{([a-zA-Z_][a-zA-Z0-9_\s]*?)(?::([^}]*))?\}/g; const variables: ExtractedVariable[] = []; const seen = new Set<string>(); let match; while ((match = regex.exec(content)) !== null) { const name = match[1].trim(); if (!seen.has(name)) { seen.add(name); variables.push({ name, defaultValue: match[2]?.trim(), }); } } return variables; } export const config = { api: { bodyParser: false, }, }; interface ServerOptions { categories?: string[]; tags?: string[]; users?: string[]; authenticatedUser?: AuthenticatedUser | null; } function createServer(options: ServerOptions = {}) { const server = new McpServer( { name: "prompts-chat", version: "1.0.0", }, { capabilities: { prompts: { listChanged: false }, tools: {}, }, } ); const { authenticatedUser } = options; // Build category/tag filter for prompts // If authenticated user is present and no specific users filter, include their private prompts const buildPromptFilter = (includeOwnPrivate: boolean = true): Record<string, unknown> => { const baseFilter: Record<string, unknown> = { isUnlisted: false, deletedAt: null, }; // Handle visibility: public prompts OR authenticated user's own prompts if (authenticatedUser && includeOwnPrivate) { // If users filter includes the authenticated user (or no users filter), include their private prompts const usersFilter = options.users && options.users.length > 0 ? options.users : null; const includeAuthUserPrivate = !usersFilter || usersFilter.includes(authenticatedUser.username); if (includeAuthUserPrivate) { baseFilter.OR = [ { isPrivate: false }, { isPrivate: true, authorId: authenticatedUser.id }, ]; } else { baseFilter.isPrivate = false; } } else { baseFilter.isPrivate = false; } if (options.categories && options.categories.length > 0) { baseFilter.category = { slug: { in: options.categories }, }; } if (options.tags && options.tags.length > 0) { baseFilter.tags = { some: { tag: { slug: { in: options.tags } }, }, }; } if (options.users && options.users.length > 0) { baseFilter.author = { username: { in: options.users }, }; } return baseFilter; }; const promptFilter = buildPromptFilter(); // Dynamic MCP Prompts - expose database prompts as MCP prompts server.server.setRequestHandler(ListPromptsRequestSchema, async (request) => { const cursor = request.params?.cursor; const page = cursor ? parseInt(cursor, 10) : 1; const perPage = 20; const prompts = await db.prompt.findMany({ where: promptFilter, skip: (page - 1) * perPage, take: perPage + 1, // fetch one extra to check if there's more orderBy: { createdAt: "desc" }, select: { id: true, slug: true, title: true, description: true, content: true, }, }); const hasMore = prompts.length > perPage; const results = hasMore ? prompts.slice(0, perPage) : prompts; return { prompts: results.map((p) => { const variables = extractVariables(p.content); return { name: getPromptName(p), title: p.title, description: p.description || undefined, arguments: variables.map((v) => ({ name: v.name, description: v.defaultValue ? `Default: ${v.defaultValue}` : undefined, required: !v.defaultValue, })), }; }), nextCursor: hasMore ? String(page + 1) : undefined, }; }); server.server.setRequestHandler(GetPromptRequestSchema, async (request) => { const promptSlug = request.params.name; const args = request.params.arguments || {}; // Fetch all matching prompts and find by slug const prompts = await db.prompt.findMany({ where: promptFilter, select: { id: true, slug: true, title: true, description: true, content: true, }, }); // Find by slug field first, then by slugified title, then by id const prompt = prompts.find((p) => p.slug === promptSlug || slugify(p.title) === promptSlug || p.id === promptSlug ); if (!prompt) { throw new Error(`Prompt not found: ${promptSlug}`); } // Replace variables in content let filledContent = prompt.content; const variables = extractVariables(prompt.content); for (const variable of variables) { const value = args[variable.name] ?? variable.defaultValue ?? `\${${variable.name}}`; filledContent = filledContent.replace( new RegExp(`\\$\\{${variable.name}(?::[^}]*)?\\}`, "g"), String(value) ); } return { description: prompt.description || prompt.title, messages: [ { role: "user" as const, content: { type: "text" as const, text: filledContent, }, }, ], }; }); server.registerTool( "search_prompts", { title: "Search Prompts", description: "Search for AI prompts by keyword. Returns matching prompts with title, description, content, author, category, and tags. Use this to discover prompts for various AI tasks like coding, writing, analysis, and more.", inputSchema: { query: z.string().describe("Search query to find relevant prompts"), limit: z .number() .min(1) .max(50) .default(10) .describe("Maximum number of prompts to return (default 10, max 50)"), type: z .enum(["TEXT", "STRUCTURED", "IMAGE", "VIDEO", "AUDIO"]) .optional() .describe("Filter by prompt type"), category: z.string().optional().describe("Filter by category slug"), tag: z.string().optional().describe("Filter by tag slug"), }, }, async ({ query, limit = 10, type, category, tag }) => { try { const where: Record<string, unknown> = { isUnlisted: false, deletedAt: null, AND: [ // Search filter { OR: [ { title: { contains: query, mode: "insensitive" } }, { description: { contains: query, mode: "insensitive" } }, { content: { contains: query, mode: "insensitive" } }, ], }, // Visibility filter: public OR user's own private prompts authenticatedUser ? { OR: [ { isPrivate: false }, { isPrivate: true, authorId: authenticatedUser.id }, ], } : { isPrivate: false }, ], }; if (type) where.type = type; if (category) where.category = { slug: category }; if (tag) where.tags = { some: { tag: { slug: tag } } }; const prompts = await db.prompt.findMany({ where, take: Math.min(limit, 50), orderBy: { createdAt: "desc" }, select: { id: true, slug: true, title: true, description: true, content: true, type: true, structuredFormat: true, createdAt: true, author: { select: { username: true, name: true } }, category: { select: { name: true, slug: true } }, tags: { select: { tag: { select: { name: true, slug: true } } } }, _count: { select: { votes: true } }, }, }); const results = prompts.map((p) => ({ id: p.id, slug: getPromptName(p), title: p.title, description: p.description, content: p.content, type: p.type, structuredFormat: p.structuredFormat, author: p.author.name || p.author.username, category: p.category?.name || null, tags: p.tags.map((t) => t.tag.name), votes: p._count.votes, createdAt: p.createdAt.toISOString(), })); return { content: [ { type: "text" as const, text: JSON.stringify({ query, count: results.length, prompts: results }, null, 2), }, ], }; } catch (error) { console.error("MCP search_prompts error:", error); return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to search prompts" }) }], isError: true, }; } } ); server.registerTool( "get_prompt", { title: "Get Prompt", description: "Get a prompt by ID and optionally fill in its variables. If the prompt contains template variables (like {{variable}}), you will be asked to provide values for them.", inputSchema: { id: z.string().describe("The ID of the prompt to retrieve"), }, }, async ({ id }, extra) => { try { const prompt = await db.prompt.findFirst({ where: { id, isPrivate: false, isUnlisted: false, deletedAt: null, }, select: { id: true, slug: true, title: true, description: true, content: true, type: true, structuredFormat: true, author: { select: { username: true, name: true } }, category: { select: { name: true, slug: true } }, tags: { select: { tag: { select: { name: true, slug: true } } } }, }, }); if (!prompt) { return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Prompt not found" }) }], isError: true, }; } const variables = extractVariables(prompt.content); if (variables.length > 0) { const properties: Record<string, PrimitiveSchemaDefinition> = {}; const requiredFields: string[] = []; for (const variable of variables) { properties[variable.name] = { type: "string", title: variable.name, description: `Value for \${${variable.name}}${variable.defaultValue ? ` (default: ${variable.defaultValue})` : ""}`, default: variable.defaultValue, }; // Only require fields without defaults if (!variable.defaultValue) { requiredFields.push(variable.name); } } try { // Add timeout to prevent hanging if client doesn't support elicitation const timeoutMs = 10000; // 10 seconds const elicitationPromise = extra.sendRequest( { method: "elicitation/create", params: { mode: "form", message: `This prompt requires ${variables.length} variable(s). Please provide values:`, requestedSchema: { type: "object", properties, required: requiredFields.length > 0 ? requiredFields : undefined, }, }, }, ElicitResultSchema ); const timeoutPromise = new Promise<never>((_, reject) => setTimeout(() => reject(new Error("Elicitation timeout")), timeoutMs) ); const result = await Promise.race([elicitationPromise, timeoutPromise]); if (result.action === "accept" && result.content) { let filledContent = prompt.content; for (const [key, value] of Object.entries(result.content)) { // Replace ${key} or ${key:default} patterns filledContent = filledContent.replace( new RegExp(`\\$\\{${key}(?::[^}]*)?\\}`, "g"), String(value) ); } return { content: [ { type: "text" as const, text: JSON.stringify( { ...prompt, content: filledContent, originalContent: prompt.content, variables: result.content, author: prompt.author.name || prompt.author.username, category: prompt.category?.name || null, tags: prompt.tags.map((t) => t.tag.name), link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`, }, null, 2 ), }, ], }; } else { return { content: [ { type: "text" as const, text: JSON.stringify( { ...prompt, variablesRequired: variables, message: "User declined to provide variable values. Returning original prompt.", author: prompt.author.name || prompt.author.username, category: prompt.category?.name || null, tags: prompt.tags.map((t) => t.tag.name), link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`, }, null, 2 ), }, ], }; } } catch { return { content: [ { type: "text" as const, text: JSON.stringify( { ...prompt, variablesRequired: variables, message: "Elicitation not supported. Variables need to be filled manually.", author: prompt.author.name || prompt.author.username, category: prompt.category?.name || null, tags: prompt.tags.map((t) => t.tag.name), link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`, }, null, 2 ), }, ], }; } } return { content: [ { type: "text" as const, text: JSON.stringify( { ...prompt, author: prompt.author.name || prompt.author.username, category: prompt.category?.name || null, tags: prompt.tags.map((t) => t.tag.name), link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`, }, null, 2 ), }, ], }; } catch (error) { console.error("MCP get_prompt error:", error); return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to get prompt" }) }], isError: true, }; } } ); // Save prompt tool - requires authentication server.registerTool( "save_prompt", { title: "Save Prompt", description: "Save a new prompt to your prompts.chat account. Requires API key authentication. Prompts are private by default unless configured otherwise in settings.", inputSchema: { title: z.string().min(1).max(200).describe("Title of the prompt"), content: z.string().min(1).describe("The prompt content. Can include variables like ${variable} or ${variable:default}"), description: z.string().max(500).optional().describe("Optional description of the prompt"), tags: z.array(z.string()).max(10).optional().describe("Optional array of tag names (will be created if they don't exist)"), category: z.string().optional().describe("Optional category slug"), isPrivate: z.boolean().optional().describe("Whether the prompt is private (default: uses your account setting)"), type: z.enum(["TEXT", "STRUCTURED", "IMAGE", "VIDEO", "AUDIO"]).optional().describe("Prompt type (default: TEXT)"), structuredFormat: z.enum(["JSON", "YAML"]).optional().describe("Format for structured prompts"), }, }, async ({ title, content, description, tags, category, isPrivate, type, structuredFormat }) => { if (!authenticatedUser) { return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }], isError: true, }; } try { // Determine privacy setting const shouldBePrivate = isPrivate !== undefined ? isPrivate : !authenticatedUser.mcpPromptsPublicByDefault; // Find or create tags const tagConnections: { tag: { connect: { id: string } } }[] = []; if (tags && tags.length > 0) { for (const tagName of tags) { const tagSlug = slugify(tagName); if (!tagSlug) continue; let tag = await db.tag.findUnique({ where: { slug: tagSlug } }); if (!tag) { tag = await db.tag.create({ data: { name: tagName, slug: tagSlug, }, }); } tagConnections.push({ tag: { connect: { id: tag.id } } }); } } // Find category if provided let categoryId: string | undefined; if (category) { const cat = await db.category.findUnique({ where: { slug: category } }); if (cat) categoryId = cat.id; } // Create the prompt const prompt = await db.prompt.create({ data: { title, slug: slugify(title), content, description: description || null, isPrivate: shouldBePrivate, type: type || "TEXT", structuredFormat: type === "STRUCTURED" ? (structuredFormat || "JSON") : null, authorId: authenticatedUser.id, categoryId: categoryId || null, tags: { create: tagConnections, }, }, select: { id: true, slug: true, title: true, description: true, content: true, isPrivate: true, type: true, createdAt: true, tags: { select: { tag: { select: { name: true, slug: true } } } }, category: { select: { name: true, slug: true } }, }, }); return { content: [ { type: "text" as const, text: JSON.stringify( { success: true, prompt: { ...prompt, tags: prompt.tags.map((t) => t.tag.name), category: prompt.category?.name || null, link: prompt.isPrivate ? null : `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`, }, }, null, 2 ), }, ], }; } catch (error) { console.error("MCP save_prompt error:", error); return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to save prompt" }) }], isError: true, }; } } ); // Improve prompt tool - uses AI to enhance prompts server.registerTool( "improve_prompt", { title: "Improve Prompt", description: "Transform a basic prompt into a well-structured, comprehensive prompt using AI. Optionally searches for similar prompts for inspiration. Supports different output types (text, image, video, sound) and formats (text, JSON, YAML).", inputSchema: { prompt: z.string().min(1).max(10000).describe("The prompt to improve"), outputType: z .enum(["text", "image", "video", "sound"]) .default("text") .describe("Content type: text, image, video, or sound"), outputFormat: z .enum(["text", "structured_json", "structured_yaml"]) .default("text") .describe("Response format: text, structured_json, or structured_yaml"), }, }, async ({ prompt, outputType = "text", outputFormat = "text" }) => { if (!authenticatedUser) { return { content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }], isError: true, }; } try { const result = await improvePrompt({ prompt, outputType, outputFormat }); return { content: [ { type: "text" as const, text: JSON.stringify(result, null, 2), }, ], }; } catch (error) { console.error("MCP improve_prompt error:", error); const message = error instanceof Error ? error.message : "Failed to improve prompt"; return { content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }], isError: true, }; } } ); return server; } async function parseBody(req: NextApiRequest): Promise<unknown> { return new Promise((resolve, reject) => { let body = ""; req.on("data", (chunk) => (body += chunk)); req.on("end", () => { try { resolve(JSON.parse(body)); } catch { resolve(body); } }); req.on("error", reject); }); } export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === "GET") { return res.status(200).json({ name: "prompts-chat", version: "1.0.0", description: "MCP server for prompts.chat - Search and discover AI prompts", protocol: "Model Context Protocol (MCP)", capabilities: { tools: true, prompts: true, }, tools: [ { name: "search_prompts", description: "Search for AI prompts by keyword.", }, { name: "get_prompt", description: "Get a prompt by ID with variable elicitation support.", }, { name: "save_prompt", description: "Save a new prompt (requires API key authentication).", }, { name: "improve_prompt", description: "Transform a basic prompt into a well-structured, comprehensive prompt using AI.", }, ], prompts: { description: "All public prompts are available as MCP prompts. Use prompts/list to browse and prompts/get to retrieve with variable substitution.", usage: "Access via slash commands in MCP clients (e.g., /prompt-id)", }, endpoint: "/api/mcp", }); } if (req.method === "DELETE") { return res.status(204).end(); } if (req.method !== "POST") { return res.status(405).json({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed" }, id: null, }); } // Parse query parameters for filtering const url = new URL(req.url || "", `http://${req.headers.host}`); const categoriesParam = url.searchParams.get("categories"); const tagsParam = url.searchParams.get("tags"); const usersParam = url.searchParams.get("users"); // Extract API key from PROMPTS_API_KEY header or query parameter const apiKeyHeader = req.headers["prompts_api_key"] || req.headers["prompts-api-key"]; const apiKeyParam = url.searchParams.get("api_key"); const apiKey = (Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader) || apiKeyParam; // Authenticate user if API key is provided const authenticatedUser = await authenticateApiKey(apiKey); const serverOptions: ServerOptions = { authenticatedUser }; if (categoriesParam) { serverOptions.categories = categoriesParam.split(",").map((c) => c.trim()); } if (tagsParam) { serverOptions.tags = tagsParam.split(",").map((t) => t.trim()); } if (usersParam) { serverOptions.users = usersParam.split(",").map((u) => u.trim()); } const server = createServer(serverOptions); try { const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); await server.connect(transport); const body = await parseBody(req); await transport.handleRequest(req, res, body); res.on("close", () => { transport.close(); server.close(); }); } catch (error) { console.error("MCP error:", error); if (!res.headersSent) { res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null, }); } } }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/auth/auth-content.tsx
src/components/auth/auth-content.tsx
"use client"; import { useTranslations } from "next-intl"; import { LoginForm } from "./login-form"; import { RegisterForm } from "./register-form"; import { OAuthButton } from "./oauth-button"; interface AuthContentProps { providers: string[]; mode: "login" | "register"; useCloneBranding?: boolean; } const providerNames: Record<string, string> = { github: "GitHub", google: "Google", azure: "Microsoft", apple: "Apple", credentials: "Email", }; export function AuthContent({ providers, mode, useCloneBranding = false }: AuthContentProps) { const t = useTranslations("auth"); const hasCredentials = providers.includes("credentials"); const oauthProviders = providers.filter((p) => p !== "credentials"); const hasGitHub = oauthProviders.includes("github"); return ( <div className="space-y-3"> {/* OAuth providers */} {oauthProviders.length > 0 && ( <div className="space-y-2"> {oauthProviders.map((provider) => ( <OAuthButton key={provider} provider={provider} providerName={providerNames[provider] || provider} /> ))} {hasGitHub && !useCloneBranding && ( <p className="text-xs text-muted-foreground text-center mt-2"> {t("githubAttributionHint")} </p> )} </div> )} {/* Separator when both OAuth and credentials are enabled */} {oauthProviders.length > 0 && hasCredentials && ( <div className="relative"> <div className="absolute inset-0 flex items-center"> <span className="w-full border-t" /> </div> <div className="relative flex justify-center text-xs uppercase"> <span className="bg-background px-2 text-muted-foreground">or</span> </div> </div> )} {/* Credentials form */} {hasCredentials && (mode === "login" ? <LoginForm /> : <RegisterForm />)} </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/auth/oauth-button.tsx
src/components/auth/oauth-button.tsx
"use client"; import { useState } from "react"; import { signIn } from "next-auth/react"; import { useTranslations } from "next-intl"; import { Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { analyticsAuth } from "@/lib/analytics"; interface OAuthButtonProps { provider: string; providerName: string; } const providerIcons: Record<string, React.ReactNode> = { github: ( <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor"> <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/> </svg> ), google: ( <svg className="h-4 w-4" viewBox="0 0 24 24"> <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/> <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/> <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/> <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/> </svg> ), azure: ( <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor"> <path d="M5.483 21.3H24L14.025 4.013l-3.038 8.347 5.836 6.938L5.483 21.3zM13.23 2.7L6.105 8.677 0 19.253h5.505l7.725-16.553z"/> </svg> ), apple: ( <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor"> <path d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/> </svg> ), }; export function OAuthButton({ provider, providerName }: OAuthButtonProps) { const t = useTranslations("auth"); const [isLoading, setIsLoading] = useState(false); const handleSignIn = async () => { setIsLoading(true); analyticsAuth.oauthStart(provider); try { await signIn(provider, { callbackUrl: "/" }); } catch (error) { console.error("Sign in error:", error); setIsLoading(false); } }; return ( <Button type="button" variant="outline" className="w-full h-10" onClick={handleSignIn} disabled={isLoading} > {isLoading ? ( <Loader2 className="mr-2 h-4 w-4 animate-spin" /> ) : ( <span className="mr-2">{providerIcons[provider]}</span> )} {t("signInWith", { provider: providerName })} </Button> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/auth/login-form.tsx
src/components/auth/login-form.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { signIn } from "next-auth/react"; import { useTranslations } from "next-intl"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { toast } from "sonner"; import { analyticsAuth } from "@/lib/analytics"; const loginSchema = z.object({ email: z.string().email("Invalid email address"), password: z.string().min(6, "Password must be at least 6 characters"), }); type LoginFormValues = z.infer<typeof loginSchema>; export function LoginForm() { const router = useRouter(); const t = useTranslations("auth"); const [isLoading, setIsLoading] = useState(false); const form = useForm<LoginFormValues>({ resolver: zodResolver(loginSchema), defaultValues: { email: "", password: "", }, }); async function onSubmit(data: LoginFormValues) { setIsLoading(true); try { const result = await signIn("credentials", { email: data.email, password: data.password, redirect: false, }); if (result?.error) { analyticsAuth.loginFailed("credentials"); toast.error(t("invalidCredentials")); return; } analyticsAuth.login("credentials"); toast.success(t("loginSuccess")); router.push("/"); router.refresh(); } catch { toast.error(t("invalidCredentials")); } finally { setIsLoading(false); } } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3"> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("email")}</FormLabel> <FormControl> <Input type="email" placeholder="name@example.com" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("password")}</FormLabel> <FormControl> <Input type="password" placeholder="••••••••" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> <Button type="submit" className="w-full h-8 text-sm" disabled={isLoading}> {isLoading && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />} {t("login")} </Button> </form> </Form> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/auth/register-form.tsx
src/components/auth/register-form.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { toast } from "sonner"; import { analyticsAuth } from "@/lib/analytics"; const registerSchema = z.object({ name: z.string().min(2, "Name must be at least 2 characters"), username: z.string().min(1, "Username is required").regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"), email: z.string().email("Invalid email address"), password: z.string().min(6, "Password must be at least 6 characters"), confirmPassword: z.string(), }).refine((data) => data.password === data.confirmPassword, { message: "Passwords do not match", path: ["confirmPassword"], }); type RegisterFormValues = z.infer<typeof registerSchema>; export function RegisterForm() { const router = useRouter(); const t = useTranslations("auth"); const tCommon = useTranslations("common"); const [isLoading, setIsLoading] = useState(false); const form = useForm<RegisterFormValues>({ resolver: zodResolver(registerSchema), defaultValues: { name: "", username: "", email: "", password: "", confirmPassword: "", }, }); async function onSubmit(data: RegisterFormValues) { setIsLoading(true); try { const response = await fetch("/api/auth/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: data.name, username: data.username, email: data.email, password: data.password, }), }); const result = await response.json(); if (!response.ok) { if (result.error === "email_taken") { analyticsAuth.registerFailed("email_taken"); toast.error(t("emailTaken")); } else if (result.error === "username_taken") { analyticsAuth.registerFailed("username_taken"); toast.error(t("usernameTaken")); } else { analyticsAuth.registerFailed(result.error); toast.error(result.message || t("registrationFailed")); } return; } analyticsAuth.register(); toast.success(t("registerSuccess")); router.push("/login"); } catch { toast.error(tCommon("somethingWentWrong")); } finally { setIsLoading(false); } } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3"> <div className="grid grid-cols-2 gap-3"> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("name")}</FormLabel> <FormControl> <Input placeholder="John Doe" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("username")}</FormLabel> <FormControl> <Input placeholder="johndoe" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> </div> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("email")}</FormLabel> <FormControl> <Input type="email" placeholder="name@example.com" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> <div className="grid grid-cols-2 gap-3"> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("password")}</FormLabel> <FormControl> <Input type="password" placeholder="••••••••" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> <FormField control={form.control} name="confirmPassword" render={({ field }) => ( <FormItem className="space-y-1"> <FormLabel className="text-xs">{t("confirmPassword")}</FormLabel> <FormControl> <Input type="password" placeholder="••••••••" className="h-8 text-sm" disabled={isLoading} {...field} /> </FormControl> <FormMessage className="text-xs" /> </FormItem> )} /> </div> <Button type="submit" className="w-full h-8 text-sm" disabled={isLoading}> {isLoading && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />} {t("register")} </Button> </form> </Form> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/user/activity-chart.tsx
src/components/user/activity-chart.tsx
"use client"; import { useMemo, useState, useEffect } from "react"; import { useTranslations } from "next-intl"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; interface ActivityData { date: string; count: number; } interface ActivityChartProps { data: ActivityData[]; locale?: string; selectedDate?: string; onDateClick?: (date: string | null) => void; } export function ActivityChart({ data, locale = "en", selectedDate, onDateClick }: ActivityChartProps) { const t = useTranslations("user"); const [isMobile, setIsMobile] = useState(false); // Detect screen size for responsive behavior useEffect(() => { const checkMobile = () => setIsMobile(window.innerWidth < 768); checkMobile(); window.addEventListener("resize", checkMobile); return () => window.removeEventListener("resize", checkMobile); }, []); // Generate weeks based on screen size (6 months for mobile, 12 for desktop) const { weeks, months } = useMemo(() => { const today = new Date(); const weeks: { date: Date; count: number }[][] = []; const dataMap = new Map(data.map((d) => [d.date, d.count])); // 26 weeks (~6 months) for mobile, 52 weeks (~12 months) for desktop const daysBack = isMobile ? 182 : 364; const startDate = new Date(today); startDate.setDate(startDate.getDate() - daysBack); // Align to Sunday startDate.setDate(startDate.getDate() - startDate.getDay()); let currentWeek: { date: Date; count: number }[] = []; const currentDate = new Date(startDate); while (currentDate <= today) { const dateStr = currentDate.toISOString().split("T")[0]; currentWeek.push({ date: new Date(currentDate), count: dataMap.get(dateStr) || 0, }); if (currentDate.getDay() === 6 || currentDate.getTime() === today.getTime()) { weeks.push(currentWeek); currentWeek = []; } currentDate.setDate(currentDate.getDate() + 1); } if (currentWeek.length > 0) { weeks.push(currentWeek); } // Calculate month labels const months: { label: string; colStart: number }[] = []; let lastMonth = -1; weeks.forEach((week, weekIndex) => { const firstDay = week[0]; if (firstDay) { const month = firstDay.date.getMonth(); if (month !== lastMonth) { months.push({ label: firstDay.date.toLocaleDateString(locale, { month: "short" }), colStart: weekIndex, }); lastMonth = month; } } }); return { weeks, months }; }, [data, locale, isMobile]); // Calculate max count for intensity scaling const maxCount = useMemo(() => { return Math.max(1, ...data.map((d) => d.count)); }, [data]); // Get intensity level (0-4) based on count const getIntensity = (count: number): number => { if (count === 0) return 0; if (count === 1) return 1; const ratio = count / maxCount; if (ratio <= 0.25) return 1; if (ratio <= 0.5) return 2; if (ratio <= 0.75) return 3; return 4; }; // Total contributions in visible range const totalContributions = useMemo(() => { const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - (isMobile ? 182 : 364)); return data .filter((d) => new Date(d.date) >= cutoffDate) .reduce((sum, d) => sum + d.count, 0); }, [data, isMobile]); const dayLabels = ["", "M", "", "W", "", "F", ""]; return ( <div className="w-full flex flex-col items-center md:items-start"> <div className="text-sm text-muted-foreground mb-3"> {totalContributions} {totalContributions === 1 ? t("contribution") : t("contributionsPlural")} {isMobile ? t("inLast6Months") : t("inLastYear")} </div> <div className="inline-block"> {/* Month labels */} <div className="relative flex text-xs text-muted-foreground mb-1 ml-5 h-4"> {months.map((month, i) => ( <div key={i} className="absolute" style={{ left: `${month.colStart * 12}px` }} > {month.label} </div> ))} </div> <div className="flex gap-0.5"> {/* Day labels */} <div className="flex flex-col gap-0.5 text-xs text-muted-foreground mr-1"> {dayLabels.map((label, i) => ( <div key={i} className="h-[10px] leading-[10px] text-[9px]"> {label} </div> ))} </div> {/* Activity grid */} <TooltipProvider delayDuration={100}> <div className="flex gap-0.5"> {weeks.map((week, weekIndex) => ( <div key={weekIndex} className="flex flex-col gap-0.5"> {Array.from({ length: 7 }).map((_, dayIndex) => { const day = week.find((d) => d.date.getDay() === dayIndex); const intensity = day ? getIntensity(day.count) : 0; const isToday = day?.date.toDateString() === new Date().toDateString(); const isFuture = day && day.date > new Date(); if (!day || isFuture) { return <div key={dayIndex} className="w-[10px] h-[10px]" />; } const dateStr = day.date.toISOString().split("T")[0]; const isSelected = selectedDate === dateStr; const handleClick = () => { if (onDateClick) { // Toggle selection - if already selected, clear it onDateClick(isSelected ? null : dateStr); } }; return ( <Tooltip key={dayIndex}> <TooltipTrigger asChild> <div onClick={handleClick} className={` w-[10px] h-[10px] rounded-full transition-all cursor-pointer ${isToday ? "ring-1 ring-primary ring-offset-1 ring-offset-background" : ""} ${isSelected ? "ring-2 ring-foreground ring-offset-1 ring-offset-background scale-125" : ""} ${ intensity === 0 ? "bg-muted" : intensity === 1 ? "bg-primary/20" : intensity === 2 ? "bg-primary/40" : intensity === 3 ? "bg-primary/70" : "bg-primary" } `} /> </TooltipTrigger> <TooltipContent side="top" className="text-xs"> <p className="font-medium"> {day.count} {day.count === 1 ? t("contribution") : t("contributionsPlural")} </p> <p className="text-muted-foreground"> {day.date.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric", year: "numeric", })} </p> </TooltipContent> </Tooltip> ); })} </div> ))} </div> </TooltipProvider> </div> {/* Legend */} <div className="flex items-center gap-1 mt-3 text-xs text-muted-foreground justify-end"> <span>{t("less")}</span> <div className="w-[10px] h-[10px] rounded-full bg-muted" /> <div className="w-[10px] h-[10px] rounded-full bg-primary/20" /> <div className="w-[10px] h-[10px] rounded-full bg-primary/40" /> <div className="w-[10px] h-[10px] rounded-full bg-primary/70" /> <div className="w-[10px] h-[10px] rounded-full bg-primary" /> <span>{t("more")}</span> </div> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/user/activity-chart-wrapper.tsx
src/components/user/activity-chart-wrapper.tsx
"use client"; import { useRouter, useSearchParams } from "next/navigation"; import { useCallback } from "react"; import { ActivityChart } from "./activity-chart"; interface ActivityChartWrapperProps { data: { date: string; count: number }[]; locale?: string; } export function ActivityChartWrapper({ data, locale }: ActivityChartWrapperProps) { const router = useRouter(); const searchParams = useSearchParams(); const selectedDate = searchParams?.get("date") || undefined; const handleDateClick = useCallback((date: string | null) => { const params = new URLSearchParams(searchParams?.toString() || ""); if (date) { params.set("date", date); params.delete("page"); // Reset to page 1 when filtering } else { params.delete("date"); } // Always switch to prompts tab when filtering by date if (date) { params.set("tab", "prompts"); } const newUrl = `?${params.toString()}`; router.push(newUrl, { scroll: false }); }, [router, searchParams]); return ( <ActivityChart data={data} locale={locale} selectedDate={selectedDate} onDateClick={handleDateClick} /> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/settings/api-key-settings.tsx
src/components/settings/api-key-settings.tsx
"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { Copy, Eye, EyeOff, RefreshCw, Trash2, Key, Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Switch } from "@/components/ui/switch"; import { Label } from "@/components/ui/label"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; interface ApiKeySettingsProps { initialApiKey: string | null; initialPublicByDefault: boolean; } export function ApiKeySettings({ initialApiKey, initialPublicByDefault, }: ApiKeySettingsProps) { const t = useTranslations("apiKey"); const tCommon = useTranslations("common"); const [apiKey, setApiKey] = useState<string | null>(initialApiKey); const [showKey, setShowKey] = useState(false); const [isLoading, setIsLoading] = useState(false); const [publicByDefault, setPublicByDefault] = useState(initialPublicByDefault); const generateKey = async () => { setIsLoading(true); try { const response = await fetch("/api/user/api-key", { method: "POST", }); if (!response.ok) throw new Error("Failed to generate API key"); const data = await response.json(); setApiKey(data.apiKey); setShowKey(true); toast.success(t("keyGenerated")); } catch { toast.error(tCommon("error")); } finally { setIsLoading(false); } }; const regenerateKey = async () => { setIsLoading(true); try { const response = await fetch("/api/user/api-key", { method: "POST", }); if (!response.ok) throw new Error("Failed to regenerate API key"); const data = await response.json(); setApiKey(data.apiKey); setShowKey(true); toast.success(t("keyRegenerated")); } catch { toast.error(tCommon("error")); } finally { setIsLoading(false); } }; const revokeKey = async () => { setIsLoading(true); try { const response = await fetch("/api/user/api-key", { method: "DELETE", }); if (!response.ok) throw new Error("Failed to revoke API key"); setApiKey(null); setShowKey(false); toast.success(t("keyRevoked")); } catch { toast.error(tCommon("error")); } finally { setIsLoading(false); } }; const updatePublicDefault = async (value: boolean) => { try { const response = await fetch("/api/user/api-key", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mcpPromptsPublicByDefault: value }), }); if (!response.ok) throw new Error("Failed to update setting"); setPublicByDefault(value); toast.success(t("settingUpdated")); } catch { toast.error(tCommon("error")); } }; const copyToClipboard = () => { if (apiKey) { navigator.clipboard.writeText(apiKey); toast.success(tCommon("copied")); } }; const maskedKey = apiKey ? `${apiKey.slice(0, 10)}${"•".repeat(32)}${apiKey.slice(-8)}` : ""; return ( <Card> <CardHeader> <CardTitle className="text-base flex items-center gap-2"> <Key className="h-4 w-4" /> {t("title")} </CardTitle> <CardDescription>{t("description")}</CardDescription> </CardHeader> <CardContent className="space-y-4"> {apiKey ? ( <> <div className="space-y-2"> <Label>{t("yourApiKey")}</Label> <div className="flex items-center gap-2"> <code className="flex-1 bg-muted px-3 py-2 rounded-md text-sm font-mono overflow-hidden text-ellipsis"> {showKey ? apiKey : maskedKey} </code> <Button variant="outline" size="icon" onClick={() => setShowKey(!showKey)} > {showKey ? ( <EyeOff className="h-4 w-4" /> ) : ( <Eye className="h-4 w-4" /> )} </Button> <Button variant="outline" size="icon" onClick={copyToClipboard}> <Copy className="h-4 w-4" /> </Button> </div> <p className="text-xs text-muted-foreground">{t("keyWarning")}</p> </div> <div className="flex items-center justify-between rounded-lg border p-3"> <div className="space-y-0.5"> <Label htmlFor="public-default">{t("publicByDefault")}</Label> <p className="text-xs text-muted-foreground"> {t("publicByDefaultDescription")} </p> </div> <Switch id="public-default" checked={publicByDefault} onCheckedChange={updatePublicDefault} /> </div> <div className="flex gap-2"> <AlertDialog> <AlertDialogTrigger asChild> <Button variant="outline" disabled={isLoading}> <RefreshCw className="h-4 w-4 mr-2" /> {t("regenerate")} </Button> </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("regenerateTitle")}</AlertDialogTitle> <AlertDialogDescription> {t("regenerateDescription")} </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={regenerateKey}> {t("regenerate")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> <AlertDialog> <AlertDialogTrigger asChild> <Button variant="destructive" disabled={isLoading} className="text-white"> <Trash2 className="h-4 w-4 mr-2" /> {t("revoke")} </Button> </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("revokeTitle")}</AlertDialogTitle> <AlertDialogDescription> {t("revokeDescription")} </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={revokeKey} className="bg-destructive text-white hover:bg-destructive/90" > {t("revoke")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </div> </> ) : ( <div className="text-center py-4"> <p className="text-sm text-muted-foreground mb-4"> {t("noApiKey")} </p> <Button onClick={generateKey} disabled={isLoading}> {isLoading ? ( <Loader2 className="h-4 w-4 mr-2 animate-spin" /> ) : ( <Key className="h-4 w-4 mr-2" /> )} {t("generate")} </Button> </div> )} </CardContent> </Card> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/settings/profile-form.tsx
src/components/settings/profile-form.tsx
"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { useSession } from "next-auth/react"; import { useTranslations } from "next-intl"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Loader2, BadgeCheck, ExternalLink, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { toast } from "sonner"; import { analyticsProfile } from "@/lib/analytics"; const profileSchema = z.object({ name: z.string().min(1, "Name is required").max(100), username: z .string() .min(1, "Username is required") .max(30) .regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"), avatar: z.string().url().optional().or(z.literal("")), }); type ProfileFormValues = z.infer<typeof profileSchema>; interface ProfileFormProps { user: { id: string; name: string | null; username: string; email: string; avatar: string | null; verified: boolean; }; showVerifiedSection?: boolean; } export function ProfileForm({ user, showVerifiedSection = false }: ProfileFormProps) { const router = useRouter(); const { update } = useSession(); const t = useTranslations("profile"); const tCommon = useTranslations("common"); const tSettings = useTranslations("settings"); const [isLoading, setIsLoading] = useState(false); const [isVerifiedSectionDismissed, setIsVerifiedSectionDismissed] = useState(true); const [hasMounted, setHasMounted] = useState(false); useEffect(() => { const stored = localStorage.getItem("verifiedSectionDismissed"); setIsVerifiedSectionDismissed(stored === "true"); setHasMounted(true); }, []); const handleDismissVerifiedSection = (dismissed: boolean) => { setIsVerifiedSectionDismissed(dismissed); localStorage.setItem("verifiedSectionDismissed", String(dismissed)); }; const form = useForm<ProfileFormValues>({ resolver: zodResolver(profileSchema), defaultValues: { name: user.name || "", username: user.username, avatar: user.avatar || "", }, }); const watchedAvatar = form.watch("avatar"); const watchedName = form.watch("name"); async function onSubmit(data: ProfileFormValues) { setIsLoading(true); try { const response = await fetch("/api/user/profile", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || "Failed to update profile"); } // Trigger NextAuth session refresh - JWT callback will fetch updated data from DB await update({}); analyticsProfile.updateProfile(); if (data.avatar !== user.avatar) { analyticsProfile.updateAvatar(); } toast.success(t("profileUpdated")); router.refresh(); // If username changed, redirect to new profile if (data.username !== user.username) { router.push(`/@${data.username}`); } } catch (error) { toast.error(error instanceof Error ? error.message : tCommon("error")); } finally { setIsLoading(false); } } return ( <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> <Card> <CardHeader> <CardTitle className="text-base">{t("title")}</CardTitle> <CardDescription> {t("updateInfo")} </CardDescription> </CardHeader> <CardContent className="space-y-4"> {/* Avatar Preview */} <div className="flex items-center gap-4"> <Avatar className="h-16 w-16"> <AvatarImage src={watchedAvatar || undefined} /> <AvatarFallback className="text-lg"> {watchedName?.charAt(0)?.toUpperCase() || user.username.charAt(0).toUpperCase()} </AvatarFallback> </Avatar> <div className="flex-1"> <Label htmlFor="avatar">{t("avatarUrl")}</Label> <Input id="avatar" placeholder="https://example.com/avatar.jpg" {...form.register("avatar")} className="mt-1" /> {form.formState.errors.avatar && ( <p className="text-xs text-destructive mt-1"> {form.formState.errors.avatar.message} </p> )} </div> </div> {/* Name */} <div className="space-y-2"> <Label htmlFor="name">{t("displayName")}</Label> <Input id="name" placeholder={t("namePlaceholder")} {...form.register("name")} /> {form.formState.errors.name && ( <p className="text-xs text-destructive"> {form.formState.errors.name.message} </p> )} </div> {/* Username */} <div className="space-y-2"> <Label htmlFor="username">{t("username")}</Label> <div className="flex items-center"> <span className="text-muted-foreground text-sm mr-1">@</span> <Input id="username" placeholder={t("usernamePlaceholder")} {...form.register("username")} /> </div> {form.formState.errors.username && ( <p className="text-xs text-destructive"> {form.formState.errors.username.message} </p> )} <div className="flex items-center justify-between"> <p className="text-xs text-muted-foreground"> {t("profileUrl")}: /{form.watch("username") || user.username} </p> {showVerifiedSection && !user.verified && hasMounted && isVerifiedSectionDismissed && ( <button type="button" onClick={() => handleDismissVerifiedSection(false)} className="inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 hover:underline" > <BadgeCheck className="h-3 w-3" /> {tSettings("getVerifiedTitle")} </button> )} </div> </div> {/* Verified Status */} {showVerifiedSection && ( user.verified ? ( <div className="flex items-center gap-2 p-3 rounded-lg border border-blue-500/30 bg-blue-500/5"> <BadgeCheck className="h-5 w-5 text-blue-500 shrink-0" /> <div> <p className="text-sm font-medium">{tSettings("verifiedTitle")}</p> <p className="text-xs text-muted-foreground">{tSettings("verifiedThankYou")}</p> </div> </div> ) : hasMounted && !isVerifiedSectionDismissed && ( <div className="relative p-4 rounded-lg border-2 border-amber-500/50 bg-gradient-to-r from-amber-500/10 to-yellow-500/10"> <button type="button" onClick={() => handleDismissVerifiedSection(true)} className="absolute top-2 right-2 p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors" > <X className="h-4 w-4" /> </button> <div className="flex items-center gap-2 mb-1"> <BadgeCheck className="h-5 w-5 text-blue-500" /> <p className="text-sm font-semibold">{tSettings("getVerifiedTitle")}</p> </div> <p className="text-sm text-muted-foreground mb-3 pr-6">{tSettings("getVerifiedDescription")}</p> <a href="https://donate.stripe.com/aFa9AS5RJeAR23nej0dMI03" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md bg-blue-500 text-white hover:bg-blue-600 transition-colors" > <BadgeCheck className="h-4 w-4" /> {tSettings("getVerifiedButton")} <span className="text-blue-100">({tSettings("verifiedBadgePrice")})</span> <ExternalLink className="h-3 w-3" /> </a> </div> ) )} {/* Email (read-only) */} <div className="space-y-2"> <Label htmlFor="email">{t("email")}</Label> <Input id="email" value={user.email} disabled className="bg-muted" /> <p className="text-xs text-muted-foreground"> {t("emailCannotChange")} </p> </div> </CardContent> </Card> <div className="flex justify-end"> <Button type="submit" disabled={isLoading}> {isLoading && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} {t("saveChanges")} </Button> </div> </form> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/prompts-management.tsx
src/components/admin/prompts-management.tsx
"use client"; import { useState, useEffect, useCallback } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import Link from "next/link"; import { Upload, Trash2, Loader2, CheckCircle, AlertCircle, Sparkles, Download, RefreshCw, Link2, Search, ExternalLink, Eye, EyeOff, Star, Flag, ChevronLeft, ChevronRight, Filter } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Progress } from "@/components/ui/progress"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; import { useBranding } from "@/components/providers/branding-provider"; interface ImportResult { success: boolean; imported: number; skipped: number; total: number; errors: string[]; } interface ProgressState { current: number; total: number; success: number; failed: number; } interface PromptAuthor { id: string; username: string; name: string | null; avatar: string | null; } interface PromptCategory { id: string; name: string; slug: string; } interface AdminPrompt { id: string; title: string; slug: string | null; type: string; isPrivate: boolean; isUnlisted: boolean; isFeatured: boolean; viewCount: number; createdAt: string; updatedAt: string; deletedAt: string | null; author: PromptAuthor; category: PromptCategory | null; _count: { votes: number; reports: number; }; } interface Pagination { page: number; limit: number; total: number; totalPages: number; } interface PromptsManagementProps { aiSearchEnabled: boolean; promptsWithoutEmbeddings: number; totalPublicPrompts: number; promptsWithoutSlugs: number; totalPrompts: number; } export function PromptsManagement({ aiSearchEnabled, promptsWithoutEmbeddings, totalPublicPrompts, promptsWithoutSlugs, totalPrompts }: PromptsManagementProps) { const router = useRouter(); const t = useTranslations("admin"); const tCommon = useTranslations("common"); const branding = useBranding(); // Disable import/delete community prompts on main site (not clones) const canModifyCommunityPrompts = branding.useCloneBranding; const [loading, setLoading] = useState(false); const [deleting, setDeleting] = useState(false); const [generating, setGenerating] = useState(false); const [generatingSlugs, setGeneratingSlugs] = useState(false); const [showConfirm, setShowConfirm] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [importResult, setImportResult] = useState<ImportResult | null>(null); const [embeddingResult, setEmbeddingResult] = useState<{ success: number; failed: number } | null>(null); const [embeddingProgress, setEmbeddingProgress] = useState<ProgressState | null>(null); const [slugResult, setSlugResult] = useState<{ success: number; failed: number } | null>(null); const [slugProgress, setSlugProgress] = useState<ProgressState | null>(null); const [generatingRelated, setGeneratingRelated] = useState(false); const [relatedResult, setRelatedResult] = useState<{ success: number; failed: number } | null>(null); const [relatedProgress, setRelatedProgress] = useState<ProgressState | null>(null); // Prompts list state const [prompts, setPrompts] = useState<AdminPrompt[]>([]); const [pagination, setPagination] = useState<Pagination | null>(null); const [searchQuery, setSearchQuery] = useState(""); const [currentPage, setCurrentPage] = useState(1); const [loadingPrompts, setLoadingPrompts] = useState(false); const [promptToDelete, setPromptToDelete] = useState<AdminPrompt | null>(null); const [deletingPrompt, setDeletingPrompt] = useState(false); const [promptFilter, setPromptFilter] = useState("all"); const fetchPrompts = useCallback(async (page: number, search: string, filter: string) => { setLoadingPrompts(true); try { const params = new URLSearchParams({ page: page.toString(), limit: "10", ...(search && { search }), ...(filter !== "all" && { filter }), }); const res = await fetch(`/api/admin/prompts?${params}`); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Failed to fetch prompts"); } setPrompts(data.prompts); setPagination(data.pagination); } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to fetch prompts"); } finally { setLoadingPrompts(false); } }, []); useEffect(() => { fetchPrompts(currentPage, searchQuery, promptFilter); // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentPage, promptFilter, fetchPrompts]); const handleSearch = () => { setCurrentPage(1); fetchPrompts(1, searchQuery, promptFilter); }; const handleFilterChange = (value: string) => { setPromptFilter(value); setCurrentPage(1); }; const handleDeletePrompt = async () => { if (!promptToDelete) return; setDeletingPrompt(true); try { const res = await fetch(`/api/admin/prompts/${promptToDelete.id}`, { method: "DELETE", }); const data = await res.json(); if (!res.ok) { throw new Error(data.message || "Failed to delete prompt"); } toast.success(t("promptsList.deleted")); setPromptToDelete(null); fetchPrompts(currentPage, searchQuery, promptFilter); router.refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to delete prompt"); } finally { setDeletingPrompt(false); } }; const handleImport = async () => { setLoading(true); setShowConfirm(false); setImportResult(null); try { const res = await fetch("/api/admin/import-prompts", { method: "POST" }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Import failed"); } setImportResult(data); if (data.imported > 0) { toast.success(t("prompts.importSuccess", { count: data.imported })); router.refresh(); } else if (data.skipped === data.total) { toast.info(t("prompts.allSkipped")); } } catch (error) { toast.error(error instanceof Error ? error.message : "Import failed"); } finally { setLoading(false); } }; const handleDelete = async () => { setDeleting(true); setShowDeleteConfirm(false); setImportResult(null); try { const res = await fetch("/api/admin/import-prompts", { method: "DELETE" }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Delete failed"); } toast.success(t("prompts.deleteSuccess", { count: data.deleted })); router.refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : "Delete failed"); } finally { setDeleting(false); } }; const handleGenerateEmbeddings = async (regenerate: boolean = false) => { setGenerating(true); setEmbeddingResult(null); setEmbeddingProgress(null); try { const url = regenerate ? "/api/admin/embeddings?regenerate=true" : "/api/admin/embeddings"; const res = await fetch(url, { method: "POST" }); if (!res.ok) { const data = await res.json(); throw new Error(data.error || "Failed to generate embeddings"); } // Read the stream const reader = res.body?.getReader(); if (!reader) throw new Error("No response body"); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split("\n\n").filter(line => line.startsWith("data: ")); for (const line of lines) { const jsonStr = line.replace("data: ", ""); try { const data = JSON.parse(jsonStr); if (data.done) { setEmbeddingResult({ success: data.success, failed: data.failed }); toast.success(t("prompts.embeddingsSuccess", { count: data.success })); router.refresh(); } else { setEmbeddingProgress({ current: data.current, total: data.total, success: data.success, failed: data.failed, }); } } catch { // Ignore parse errors } } } } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to generate embeddings"); } finally { setGenerating(false); setEmbeddingProgress(null); } }; const handleExport = () => { // Direct link to public prompts.csv endpoint window.open("/prompts.csv", "_blank"); toast.success(t("prompts.exportSuccess")); }; const handleGenerateRelatedPrompts = async () => { setGeneratingRelated(true); setRelatedResult(null); setRelatedProgress(null); try { const res = await fetch("/api/admin/related-prompts", { method: "POST" }); if (!res.ok) { const data = await res.json(); throw new Error(data.error || "Failed to generate related prompts"); } // Read the stream const reader = res.body?.getReader(); if (!reader) throw new Error("No response body"); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split("\n\n").filter(line => line.startsWith("data: ")); for (const line of lines) { const jsonStr = line.replace("data: ", ""); try { const data = JSON.parse(jsonStr); if (data.done) { setRelatedResult({ success: data.success, failed: data.failed }); toast.success(t("prompts.relatedSuccess", { count: data.success })); router.refresh(); } else { setRelatedProgress({ current: data.current, total: data.total, success: data.success, failed: data.failed, }); } } catch { // Ignore parse errors } } } } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to generate related prompts"); } finally { setGeneratingRelated(false); setRelatedProgress(null); } }; const handleGenerateSlugs = async (regenerate: boolean = false) => { setGeneratingSlugs(true); setSlugResult(null); setSlugProgress(null); try { const url = regenerate ? "/api/admin/slugs?regenerate=true" : "/api/admin/slugs"; const res = await fetch(url, { method: "POST" }); if (!res.ok) { const data = await res.json(); throw new Error(data.error || "Failed to generate slugs"); } // Read the stream const reader = res.body?.getReader(); if (!reader) throw new Error("No response body"); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split("\n\n").filter(line => line.startsWith("data: ")); for (const line of lines) { const jsonStr = line.replace("data: ", ""); try { const data = JSON.parse(jsonStr); if (data.done) { setSlugResult({ success: data.success, failed: data.failed }); toast.success(t("prompts.slugsSuccess", { count: data.success })); router.refresh(); } else { setSlugProgress({ current: data.current, total: data.total, success: data.success, failed: data.failed, }); } } catch { // Ignore parse errors } } } } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to generate slugs"); } finally { setGeneratingSlugs(false); setSlugProgress(null); } }; return ( <> <div className="flex items-center justify-between mb-4"> <div> <h3 className="text-lg font-semibold">{t("prompts.title")}</h3> <p className="text-sm text-muted-foreground">{t("prompts.description")}</p> </div> </div> <div className="rounded-md border p-3 sm:p-4 space-y-3"> {/* Import Row */} {canModifyCommunityPrompts && ( <div className="flex flex-col sm:flex-row sm:items-center gap-2"> <span className="text-sm text-muted-foreground flex-1">{t("import.fileInfo")}</span> <div className="flex gap-2"> <Button size="sm" variant="outline" onClick={() => setShowConfirm(true)} disabled={loading || deleting || generating} className="flex-1 sm:flex-none" > {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <><Upload className="h-4 w-4 mr-2" />{t("prompts.import")}</>} </Button> <Button size="sm" variant="ghost" onClick={() => setShowDeleteConfirm(true)} disabled={loading || deleting || generating} className="text-destructive hover:text-destructive" > {deleting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />} </Button> </div> </div> )} {/* Export Row */} <div className={`flex flex-col sm:flex-row sm:items-center gap-2 ${canModifyCommunityPrompts ? "pt-3 border-t" : ""}`}> <span className="text-sm text-muted-foreground flex-1">{t("prompts.exportInfo")}</span> <Button size="sm" variant="outline" onClick={handleExport} disabled={loading || deleting || generating} className="w-full sm:w-auto" > <Download className="h-4 w-4 mr-2" />{t("prompts.export")} </Button> </div> {importResult && ( <div className="flex items-center gap-2 text-sm text-muted-foreground"> {importResult.imported > 0 ? <CheckCircle className="h-4 w-4 text-green-500" /> : <AlertCircle className="h-4 w-4 text-amber-500" />} <span>{t("prompts.importResult", { imported: importResult.imported, skipped: importResult.skipped })}</span> </div> )} {/* AI Embeddings Row */} {aiSearchEnabled && ( <> <div className="flex flex-col sm:flex-row sm:items-center gap-2 pt-3 border-t"> <span className="text-sm text-muted-foreground flex-1"> {t("aiSearch.title")} <span className="tabular-nums">({promptsWithoutEmbeddings} {t("prompts.pending")})</span> </span> <div className="flex gap-2"> <Button size="sm" variant="outline" onClick={() => handleGenerateEmbeddings(false)} disabled={loading || deleting || generating || promptsWithoutEmbeddings === 0} className="flex-1 sm:flex-none" > {generating && !embeddingProgress ? ( <Loader2 className="h-4 w-4 animate-spin" /> ) : generating && embeddingProgress ? ( <><Loader2 className="h-4 w-4 animate-spin mr-2" />{embeddingProgress.current}/{embeddingProgress.total}</> ) : ( <><Sparkles className="h-4 w-4 mr-2" /><span className="hidden xs:inline">{t("prompts.generateEmbeddings")}</span><span className="xs:hidden">Generate</span></> )} </Button> <Button size="sm" variant="ghost" onClick={() => handleGenerateEmbeddings(true)} disabled={loading || deleting || generating || totalPublicPrompts === 0} title={t("prompts.regenerateEmbeddings")} > <RefreshCw className="h-4 w-4" /> </Button> </div> </div> {/* Progress bar */} {embeddingProgress && ( <div className="space-y-2"> <Progress value={Math.round((embeddingProgress.current / embeddingProgress.total) * 100)} className="h-2" /> <div className="flex justify-between text-xs text-muted-foreground"> <span>{embeddingProgress.current} / {embeddingProgress.total}</span> <span>{Math.round((embeddingProgress.current / embeddingProgress.total) * 100)}%</span> </div> <div className="flex gap-4 text-xs"> <span className="text-green-600">✓ {embeddingProgress.success}</span> {embeddingProgress.failed > 0 && <span className="text-red-600">✗ {embeddingProgress.failed}</span>} </div> </div> )} {embeddingResult && !embeddingProgress && ( <div className="flex items-center gap-2 text-sm text-muted-foreground"> {embeddingResult.failed === 0 ? <CheckCircle className="h-4 w-4 text-green-500" /> : <AlertCircle className="h-4 w-4 text-amber-500" />} <span>{t("prompts.embeddingsResult", { success: embeddingResult.success, failed: embeddingResult.failed })}</span> </div> )} </> )} {/* URL Slugs Row */} <div className="flex flex-col sm:flex-row sm:items-center gap-2 pt-3 border-t"> <span className="text-sm text-muted-foreground flex-1"> {t("prompts.slugsTitle")} <span className="tabular-nums">({promptsWithoutSlugs} {t("prompts.pending")})</span> </span> <div className="flex gap-2"> <Button size="sm" variant="outline" onClick={() => handleGenerateSlugs(false)} disabled={loading || deleting || generating || generatingSlugs || promptsWithoutSlugs === 0} className="flex-1 sm:flex-none" > {generatingSlugs && !slugProgress ? ( <Loader2 className="h-4 w-4 animate-spin" /> ) : generatingSlugs && slugProgress ? ( <><Loader2 className="h-4 w-4 animate-spin mr-2" />{slugProgress.current}/{slugProgress.total}</> ) : ( <><Link2 className="h-4 w-4 mr-2" />{t("prompts.generateSlugs")}</> )} </Button> <Button size="sm" variant="ghost" onClick={() => handleGenerateSlugs(true)} disabled={loading || deleting || generating || generatingSlugs || totalPrompts === 0} title={t("prompts.regenerateSlugs")} > <RefreshCw className="h-4 w-4" /> </Button> </div> </div> {/* Slug Progress bar */} {slugProgress && ( <div className="space-y-2"> <Progress value={Math.round((slugProgress.current / slugProgress.total) * 100)} className="h-2" /> <div className="flex justify-between text-xs text-muted-foreground"> <span>{slugProgress.current} / {slugProgress.total}</span> <span>{Math.round((slugProgress.current / slugProgress.total) * 100)}%</span> </div> <div className="flex gap-4 text-xs"> <span className="text-green-600">✓ {slugProgress.success}</span> {slugProgress.failed > 0 && <span className="text-red-600">✗ {slugProgress.failed}</span>} </div> </div> )} {slugResult && !slugProgress && ( <div className="flex items-center gap-2 text-sm text-muted-foreground"> {slugResult.failed === 0 ? <CheckCircle className="h-4 w-4 text-green-500" /> : <AlertCircle className="h-4 w-4 text-amber-500" />} <span>{t("prompts.slugsResult", { success: slugResult.success, failed: slugResult.failed })}</span> </div> )} {/* Related Prompts Row */} {aiSearchEnabled && ( <> <div className="flex flex-col sm:flex-row sm:items-center gap-2 pt-3 border-t"> <span className="text-sm text-muted-foreground flex-1"> {t("prompts.relatedTitle")} </span> <Button size="sm" variant="outline" onClick={handleGenerateRelatedPrompts} disabled={loading || deleting || generating || generatingSlugs || generatingRelated} className="w-full sm:w-auto" > {generatingRelated && !relatedProgress ? ( <Loader2 className="h-4 w-4 animate-spin" /> ) : generatingRelated && relatedProgress ? ( <><Loader2 className="h-4 w-4 animate-spin mr-2" />{relatedProgress.current}/{relatedProgress.total}</> ) : ( <><Sparkles className="h-4 w-4 mr-2" />{t("prompts.regenerateRelated")}</> )} </Button> </div> {/* Related Progress bar */} {relatedProgress && ( <div className="space-y-2"> <Progress value={Math.round((relatedProgress.current / relatedProgress.total) * 100)} className="h-2" /> <div className="flex justify-between text-xs text-muted-foreground"> <span>{relatedProgress.current} / {relatedProgress.total}</span> <span>{Math.round((relatedProgress.current / relatedProgress.total) * 100)}%</span> </div> <div className="flex gap-4 text-xs"> <span className="text-green-600">✓ {relatedProgress.success}</span> {relatedProgress.failed > 0 && <span className="text-red-600">✗ {relatedProgress.failed}</span>} </div> </div> )} {relatedResult && !relatedProgress && ( <div className="flex items-center gap-2 text-sm text-muted-foreground"> {relatedResult.failed === 0 ? <CheckCircle className="h-4 w-4 text-green-500" /> : <AlertCircle className="h-4 w-4 text-amber-500" />} <span>{t("prompts.relatedResult", { success: relatedResult.success, failed: relatedResult.failed })}</span> </div> )} </> )} </div> <AlertDialog open={showConfirm} onOpenChange={setShowConfirm}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("prompts.importConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription>{t("prompts.importConfirmDescription")}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("prompts.cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleImport}>{t("prompts.confirm")}</AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("prompts.deleteConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription>{t("prompts.deleteConfirmDescription")}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("prompts.cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90 text-white"> {t("prompts.delete")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> {/* Prompts List Section */} <div className="mt-8"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4"> <div> <h3 className="text-lg font-semibold">{t("promptsList.title")}</h3> <p className="text-sm text-muted-foreground">{t("promptsList.description")}</p> </div> <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto"> <Select value={promptFilter} onValueChange={handleFilterChange}> <SelectTrigger className="w-full sm:w-[140px]"> <Filter className="h-4 w-4 mr-2" /> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="all">{t("promptsList.filters.all")}</SelectItem> <SelectItem value="public">{t("promptsList.filters.public")}</SelectItem> <SelectItem value="private">{t("promptsList.filters.private")}</SelectItem> <SelectItem value="unlisted">{t("promptsList.filters.unlisted")}</SelectItem> <SelectItem value="featured">{t("promptsList.filters.featured")}</SelectItem> <SelectItem value="reported">{t("promptsList.filters.reported")}</SelectItem> <SelectItem value="deleted">{t("promptsList.filters.deleted")}</SelectItem> </SelectContent> </Select> <div className="flex gap-2"> <div className="relative flex-1 sm:flex-none"> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <Input placeholder={tCommon("search")} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleSearch()} className="pl-9 w-full sm:w-[200px]" /> </div> <Button size="icon" variant="outline" onClick={handleSearch} disabled={loadingPrompts}> {loadingPrompts ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />} </Button> </div> </div> </div> {/* Mobile-friendly Prompts Cards */} <div className="space-y-3"> {loadingPrompts && prompts.length === 0 ? ( <div className="flex items-center justify-center py-12"> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /> </div> ) : prompts.length === 0 ? ( <div className="text-center py-12 text-muted-foreground"> {t("promptsList.noPrompts")} </div> ) : ( prompts.map((prompt) => ( <div key={prompt.id} className="rounded-lg border bg-card p-4 space-y-3" > {/* Header Row */} <div className="flex items-start justify-between gap-3"> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2 flex-wrap"> <h4 className="font-medium truncate">{prompt.title}</h4> {prompt.isFeatured && ( <Star className="h-4 w-4 text-yellow-500 fill-yellow-500 flex-shrink-0" /> )} {prompt.isPrivate && ( <Badge variant="secondary" className="text-xs"> <EyeOff className="h-3 w-3 mr-1" /> {t("promptsList.private")} </Badge> )} {prompt.isUnlisted && ( <Badge variant="outline" className="text-xs"> <Eye className="h-3 w-3 mr-1" /> {t("promptsList.unlisted")} </Badge> )} {prompt._count.reports > 0 && ( <Badge variant="destructive" className="text-xs"> <Flag className="h-3 w-3 mr-1" /> {prompt._count.reports} </Badge> )} </div> <p className="text-xs text-muted-foreground mt-1"> {prompt.type} • {prompt.viewCount} {t("promptsList.views")} • {prompt._count.votes} {t("promptsList.votes")} </p> </div> <div className="flex items-center gap-2 flex-shrink-0"> {prompt.id && ( <Link href={`/prompts/${prompt.id}`} target="_blank" prefetch={false}> <Button size="icon" variant="ghost" className="h-8 w-8"> <ExternalLink className="h-4 w-4" /> </Button> </Link> )} <Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10" onClick={() => setPromptToDelete(prompt)} > <Trash2 className="h-4 w-4" /> </Button> </div> </div> {/* Author & Category Row */} <div className="flex items-center justify-between gap-3 text-sm"> <div className="flex items-center gap-2 min-w-0"> <Avatar className="h-6 w-6"> <AvatarImage src={prompt.author.avatar || undefined} /> <AvatarFallback className="text-xs"> {prompt.author.name?.[0] || prompt.author.username[0]} </AvatarFallback> </Avatar> <span className="text-muted-foreground truncate"> @{prompt.author.username} </span> </div> {prompt.category && ( <Badge variant="secondary" className="text-xs truncate max-w-[150px]"> {prompt.category.name} </Badge> )} </div> {/* Date Row */} <div className="flex items-center justify-between text-xs text-muted-foreground"> <span>{t("promptsList.created")}: {new Date(prompt.createdAt).toLocaleDateString()}</span> <span className="font-mono text-[10px] opacity-50">{prompt.id.slice(0, 8)}</span> </div> </div> )) )} </div> {/* Pagination */} {pagination && pagination.totalPages > 1 && ( <div className="flex items-center justify-between mt-4 pt-4 border-t"> <p className="text-sm text-muted-foreground"> {t("promptsList.showing", { from: (pagination.page - 1) * pagination.limit + 1, to: Math.min(pagination.page * pagination.limit, pagination.total), total: pagination.total, })} </p> <div className="flex items-center gap-2"> <Button size="icon" variant="outline" className="h-8 w-8" disabled={currentPage === 1 || loadingPrompts} onClick={() => setCurrentPage((p) => p - 1)} > <ChevronLeft className="h-4 w-4" /> </Button> <span className="text-sm tabular-nums px-2"> {currentPage} / {pagination.totalPages} </span> <Button
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
true
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/tags-table.tsx
src/components/admin/tags-table.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { MoreHorizontal, Plus, Pencil, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; interface Tag { id: string; name: string; slug: string; color: string; _count: { prompts: number; }; } interface TagsTableProps { tags: Tag[]; } export function TagsTable({ tags }: TagsTableProps) { const router = useRouter(); const t = useTranslations("admin.tags"); const [editTag, setEditTag] = useState<Tag | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null); const [isCreating, setIsCreating] = useState(false); const [loading, setLoading] = useState(false); const [formData, setFormData] = useState({ name: "", slug: "", color: "#6366f1" }); const openCreateDialog = () => { setFormData({ name: "", slug: "", color: "#6366f1" }); setIsCreating(true); }; const openEditDialog = (tag: Tag) => { setFormData({ name: tag.name, slug: tag.slug, color: tag.color, }); setEditTag(tag); }; const handleSubmit = async () => { setLoading(true); try { const url = editTag ? `/api/admin/tags/${editTag.id}` : "/api/admin/tags"; const method = editTag ? "PATCH" : "POST"; const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData), }); if (!res.ok) throw new Error("Failed to save"); toast.success(editTag ? t("updated") : t("created")); router.refresh(); setEditTag(null); setIsCreating(false); } catch { toast.error(t("saveFailed")); } finally { setLoading(false); } }; const handleDelete = async () => { if (!deleteId) return; setLoading(true); try { const res = await fetch(`/api/admin/tags/${deleteId}`, { method: "DELETE", }); if (!res.ok) throw new Error("Failed to delete"); toast.success(t("deleted")); router.refresh(); } catch { toast.error(t("deleteFailed")); } finally { setLoading(false); setDeleteId(null); } }; return ( <> <div className="flex items-center justify-between mb-4"> <div> <h3 className="text-lg font-semibold">{t("title")}</h3> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> <Button size="sm" onClick={openCreateDialog}> <Plus className="h-4 w-4 mr-2" /> {t("add")} </Button> </div> <div className="rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>{t("name")}</TableHead> <TableHead>{t("slug")}</TableHead> <TableHead>{t("color")}</TableHead> <TableHead className="text-center">{t("prompts")}</TableHead> <TableHead className="w-[50px]"></TableHead> </TableRow> </TableHeader> <TableBody> {tags.length === 0 ? ( <TableRow> <TableCell colSpan={5} className="text-center text-muted-foreground py-8"> {t("noTags")} </TableCell> </TableRow> ) : ( tags.map((tag) => ( <TableRow key={tag.id}> <TableCell> <span className="inline-flex items-center px-2 py-0.5 rounded text-sm font-medium" style={{ backgroundColor: tag.color + "20", color: tag.color }} > {tag.name} </span> </TableCell> <TableCell className="text-sm text-muted-foreground">{tag.slug}</TableCell> <TableCell> <div className="flex items-center gap-2"> <div className="w-6 h-6 rounded border" style={{ backgroundColor: tag.color }} /> <span className="text-sm text-muted-foreground">{tag.color}</span> </div> </TableCell> <TableCell className="text-center">{tag._count.prompts}</TableCell> <TableCell> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="h-8 w-8"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => openEditDialog(tag)}> <Pencil className="h-4 w-4 mr-2" /> {t("edit")} </DropdownMenuItem> <DropdownMenuItem className="text-destructive" onClick={() => setDeleteId(tag.id)} > <Trash2 className="h-4 w-4 mr-2" /> {t("delete")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </TableCell> </TableRow> )) )} </TableBody> </Table> </div> {/* Create/Edit Dialog */} <Dialog open={isCreating || !!editTag} onOpenChange={() => { setIsCreating(false); setEditTag(null); }}> <DialogContent> <DialogHeader> <DialogTitle>{editTag ? t("editTitle") : t("createTitle")}</DialogTitle> <DialogDescription>{editTag ? t("editDescription") : t("createDescription")}</DialogDescription> </DialogHeader> <div className="grid gap-4 py-4"> <div className="grid gap-2"> <Label htmlFor="name">{t("name")}</Label> <Input id="name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} /> </div> <div className="grid gap-2"> <Label htmlFor="slug">{t("slug")}</Label> <Input id="slug" value={formData.slug} onChange={(e) => setFormData({ ...formData, slug: e.target.value })} /> </div> <div className="grid gap-2"> <Label htmlFor="color">{t("color")}</Label> <div className="flex gap-2"> <Input id="color" type="color" value={formData.color} onChange={(e) => setFormData({ ...formData, color: e.target.value })} className="w-12 h-10 p-1 cursor-pointer" /> <Input value={formData.color} onChange={(e) => setFormData({ ...formData, color: e.target.value })} placeholder="#6366f1" className="flex-1" /> </div> </div> </div> <DialogFooter> <Button variant="outline" onClick={() => { setIsCreating(false); setEditTag(null); }}> {t("cancel")} </Button> <Button onClick={handleSubmit} disabled={loading || !formData.name || !formData.slug}> {editTag ? t("save") : t("create")} </Button> </DialogFooter> </DialogContent> </Dialog> {/* Delete Confirmation */} <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} disabled={loading} className="bg-destructive text-white hover:bg-destructive/90" > {t("delete")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/ai-search-settings.tsx
src/components/admin/ai-search-settings.tsx
"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Progress } from "@/components/ui/progress"; import { Sparkles, Loader2, CheckCircle, AlertCircle, RefreshCw } from "lucide-react"; import { toast } from "sonner"; interface AISearchSettingsProps { enabled: boolean; promptsWithoutEmbeddings: number; totalPrompts: number; } interface ProgressState { current: number; total: number; success: number; failed: number; } export function AISearchSettings({ enabled, promptsWithoutEmbeddings, totalPrompts }: AISearchSettingsProps) { const t = useTranslations("admin"); const [isGenerating, setIsGenerating] = useState(false); const [progress, setProgress] = useState<ProgressState | null>(null); const [result, setResult] = useState<{ success: number; failed: number } | null>(null); const handleGenerateEmbeddings = async (regenerate: boolean = false) => { setIsGenerating(true); setResult(null); setProgress(null); try { const url = regenerate ? "/api/admin/embeddings?regenerate=true" : "/api/admin/embeddings"; const response = await fetch(url, { method: "POST", }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || "Failed to generate embeddings"); } // Read the stream const reader = response.body?.getReader(); if (!reader) throw new Error("No response body"); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split("\n\n").filter(line => line.startsWith("data: ")); for (const line of lines) { const jsonStr = line.replace("data: ", ""); try { const data = JSON.parse(jsonStr); if (data.done) { setResult({ success: data.success, failed: data.failed }); toast.success(t("aiSearch.generateSuccess", { count: data.success })); } else { setProgress({ current: data.current, total: data.total, success: data.success, failed: data.failed, }); } } catch { // Ignore parse errors } } } } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to generate embeddings"); } finally { setIsGenerating(false); setProgress(null); } }; if (!enabled) { return null; } const progressPercent = progress ? Math.round((progress.current / progress.total) * 100) : 0; return ( <Card> <CardHeader> <CardTitle className="flex items-center gap-2"> <Sparkles className="h-5 w-5" /> {t("aiSearch.title")} </CardTitle> <CardDescription>{t("aiSearch.description")}</CardDescription> </CardHeader> <CardContent className="space-y-4"> <div className="flex items-center justify-between"> <div className="text-sm"> <span className="text-muted-foreground">{t("aiSearch.promptsWithoutEmbeddings")}: </span> <span className="font-medium">{promptsWithoutEmbeddings}</span> </div> </div> {/* Progress bar */} {progress && ( <div className="space-y-2"> <Progress value={progressPercent} className="h-2" /> <div className="flex justify-between text-xs text-muted-foreground"> <span>{progress.current} / {progress.total}</span> <span>{progressPercent}%</span> </div> <div className="flex gap-4 text-xs"> <span className="text-green-600">✓ {progress.success}</span> {progress.failed > 0 && <span className="text-red-600">✗ {progress.failed}</span>} </div> </div> )} {result && !progress && ( <div className="flex items-center gap-2 text-sm"> {result.failed === 0 ? ( <CheckCircle className="h-4 w-4 text-green-500" /> ) : ( <AlertCircle className="h-4 w-4 text-amber-500" /> )} <span> {t("aiSearch.generateResult", { success: result.success, failed: result.failed })} </span> </div> )} <div className="flex gap-2"> <Button onClick={() => handleGenerateEmbeddings(false)} disabled={isGenerating || promptsWithoutEmbeddings === 0} className="flex-1" > {isGenerating && !progress ? ( <> <Loader2 className="h-4 w-4 mr-2 animate-spin" /> {t("aiSearch.generating")} </> ) : isGenerating && progress ? ( <> <Loader2 className="h-4 w-4 mr-2 animate-spin" /> {progress.current}/{progress.total} </> ) : ( <> <Sparkles className="h-4 w-4 mr-2" /> {t("aiSearch.generateButton")} </> )} </Button> <Button variant="outline" onClick={() => handleGenerateEmbeddings(true)} disabled={isGenerating || totalPrompts === 0} title={t("aiSearch.regenerateTooltip")} > <RefreshCw className="h-4 w-4" /> </Button> </div> </CardContent> </Card> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/webhooks-table.tsx
src/components/admin/webhooks-table.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Badge } from "@/components/ui/badge"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { Plus, MoreHorizontal, Pencil, Trash2, Slack, X, Play } from "lucide-react"; import { SLACK_PRESET_PAYLOAD, WEBHOOK_PLACEHOLDERS } from "@/lib/webhook"; import { CodeEditor } from "@/components/ui/code-editor"; import type { JsonValue } from "@prisma/client/runtime/library"; interface WebhookConfig { id: string; name: string; url: string; method: string; headers: JsonValue; payload: string; events: string[]; isEnabled: boolean; createdAt: Date; } interface WebhooksTableProps { webhooks: WebhookConfig[]; } interface HeaderEntry { key: string; value: string; } const EVENTS = [ { value: "PROMPT_CREATED", label: "Prompt Created" }, { value: "PROMPT_UPDATED", label: "Prompt Updated" }, { value: "PROMPT_DELETED", label: "Prompt Deleted" }, ]; const PLACEHOLDER_LIST = Object.values(WEBHOOK_PLACEHOLDERS); // Headers Editor Component function HeadersEditor({ headers, onChange, }: { headers: HeaderEntry[]; onChange: (headers: HeaderEntry[]) => void; }) { const addHeader = () => { onChange([...headers, { key: "", value: "" }]); }; const removeHeader = (index: number) => { onChange(headers.filter((_, i) => i !== index)); }; const updateHeader = (index: number, field: "key" | "value", value: string) => { const updated = [...headers]; updated[index][field] = value; onChange(updated); }; return ( <div className="space-y-2"> {headers.map((header, index) => ( <div key={index} className="flex gap-2"> <Input placeholder="Header name" value={header.key} onChange={(e) => updateHeader(index, "key", e.target.value)} className="flex-1 font-mono text-sm" /> <Input placeholder="Header value" value={header.value} onChange={(e) => updateHeader(index, "value", e.target.value)} className="flex-1 font-mono text-sm" /> <Button type="button" variant="ghost" size="icon" onClick={() => removeHeader(index)} className="shrink-0" > <X className="h-4 w-4" /> </Button> </div> ))} <Button type="button" variant="outline" size="sm" onClick={addHeader} className="w-full" > <Plus className="h-4 w-4 mr-2" /> Add Header </Button> </div> ); } export function WebhooksTable({ webhooks: initialWebhooks }: WebhooksTableProps) { const t = useTranslations("admin.webhooks"); const router = useRouter(); const [webhooks, setWebhooks] = useState(initialWebhooks); const [isCreateOpen, setIsCreateOpen] = useState(false); const [isEditOpen, setIsEditOpen] = useState(false); const [editingWebhook, setEditingWebhook] = useState<WebhookConfig | null>(null); const [isLoading, setIsLoading] = useState(false); const [formData, setFormData] = useState({ name: "", url: "", method: "POST", headers: [] as HeaderEntry[], payload: "", events: ["PROMPT_CREATED"] as string[], isEnabled: true, }); const resetForm = () => { setFormData({ name: "", url: "", method: "POST", headers: [], payload: "", events: ["PROMPT_CREATED"], isEnabled: true, }); }; const applySlackPreset = () => { setFormData((prev) => ({ ...prev, name: prev.name || "Slack Notifications", method: "POST", headers: [{ key: "Content-Type", value: "application/json" }], payload: SLACK_PRESET_PAYLOAD, })); }; const headersToObject = (headers: HeaderEntry[]): Record<string, string> | null => { const filtered = headers.filter((h) => h.key.trim() !== ""); if (filtered.length === 0) return null; return Object.fromEntries(filtered.map((h) => [h.key, h.value])); }; const objectToHeaders = (obj: JsonValue): HeaderEntry[] => { if (!obj || typeof obj !== "object" || Array.isArray(obj)) return []; return Object.entries(obj).map(([key, value]) => ({ key, value: String(value) })); }; const handleCreate = async () => { setIsLoading(true); try { const response = await fetch("/api/admin/webhooks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...formData, headers: headersToObject(formData.headers), }), }); if (response.ok) { const newWebhook = await response.json(); setWebhooks((prev) => [newWebhook, ...prev]); setIsCreateOpen(false); resetForm(); router.refresh(); } } catch (error) { console.error("Failed to create webhook:", error); } finally { setIsLoading(false); } }; const handleEdit = async () => { if (!editingWebhook) return; setIsLoading(true); try { const response = await fetch(`/api/admin/webhooks/${editingWebhook.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...formData, headers: headersToObject(formData.headers), }), }); if (response.ok) { const updatedWebhook = await response.json(); setWebhooks((prev) => prev.map((w) => (w.id === updatedWebhook.id ? updatedWebhook : w)) ); setIsEditOpen(false); setEditingWebhook(null); resetForm(); router.refresh(); } } catch (error) { console.error("Failed to update webhook:", error); } finally { setIsLoading(false); } }; const handleDelete = async (id: string) => { if (!confirm(t("deleteConfirm"))) return; try { const response = await fetch(`/api/admin/webhooks/${id}`, { method: "DELETE", }); if (response.ok) { setWebhooks((prev) => prev.filter((w) => w.id !== id)); router.refresh(); } } catch (error) { console.error("Failed to delete webhook:", error); } }; const handleToggleEnabled = async (webhook: WebhookConfig) => { try { const response = await fetch(`/api/admin/webhooks/${webhook.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isEnabled: !webhook.isEnabled }), }); if (response.ok) { setWebhooks((prev) => prev.map((w) => w.id === webhook.id ? { ...w, isEnabled: !w.isEnabled } : w ) ); } } catch (error) { console.error("Failed to toggle webhook:", error); } }; const handleTest = async (webhook: WebhookConfig) => { try { const response = await fetch(`/api/admin/webhooks/${webhook.id}/test`, { method: "POST", }); if (response.ok) { alert(t("testSuccess")); } else { const data = await response.json(); alert(t("testFailed") + ": " + (data.error || "Unknown error")); } } catch (error) { console.error("Failed to test webhook:", error); alert(t("testFailed")); } }; const openEditDialog = (webhook: WebhookConfig) => { setEditingWebhook(webhook); setFormData({ name: webhook.name, url: webhook.url, method: webhook.method, headers: objectToHeaders(webhook.headers), payload: webhook.payload, events: webhook.events, isEnabled: webhook.isEnabled, }); setIsEditOpen(true); }; const WebhookForm = () => ( <div className="space-y-6"> <div className="flex gap-2"> <Button type="button" variant="outline" size="sm" onClick={applySlackPreset} className="gap-2" > <Slack className="h-4 w-4" /> {t("useSlackPreset")} </Button> </div> <div className="grid grid-cols-2 gap-4"> <div className="grid gap-2"> <Label htmlFor="name">{t("name")}</Label> <Input id="name" value={formData.name} onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))} placeholder="Slack Notifications" /> </div> <div className="grid gap-2"> <Label htmlFor="method">{t("method")}</Label> <Select value={formData.method} onValueChange={(value) => setFormData((prev) => ({ ...prev, method: value }))} > <SelectTrigger> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="GET">GET</SelectItem> <SelectItem value="POST">POST</SelectItem> <SelectItem value="PUT">PUT</SelectItem> <SelectItem value="PATCH">PATCH</SelectItem> </SelectContent> </Select> </div> </div> <div className="grid gap-2"> <Label htmlFor="url">{t("url")}</Label> <Input id="url" type="url" value={formData.url} onChange={(e) => setFormData((prev) => ({ ...prev, url: e.target.value }))} placeholder="https://hooks.slack.com/services/..." /> </div> <div className="grid gap-2"> <Label>{t("events")}</Label> <div className="flex flex-wrap gap-3"> {EVENTS.map((event) => ( <label key={event.value} className="flex items-center gap-2 cursor-pointer" > <input type="checkbox" checked={formData.events.includes(event.value)} onChange={(e) => { if (e.target.checked) { setFormData((prev) => ({ ...prev, events: [...prev.events, event.value], })); } else { setFormData((prev) => ({ ...prev, events: prev.events.filter((ev) => ev !== event.value), })); } }} className="rounded" /> <span className="text-sm">{event.label}</span> </label> ))} </div> </div> <div className="grid gap-2"> <Label>{t("headers")}</Label> <HeadersEditor headers={formData.headers} onChange={(headers) => setFormData((prev) => ({ ...prev, headers }))} /> </div> <div className="grid gap-2"> <Label>{t("payload")}</Label> <CodeEditor value={formData.payload} onChange={(payload: string) => setFormData((prev) => ({ ...prev, payload }))} language="json" minHeight="280px" debounceMs={300} /> <div className="space-y-2"> <p className="text-xs text-muted-foreground">{t("placeholders")}:</p> <div className="flex flex-wrap gap-1"> {PLACEHOLDER_LIST.map((placeholder) => ( <Badge key={placeholder} variant="secondary" className="text-xs font-mono cursor-pointer hover:bg-accent" onClick={() => { const newPayload = formData.payload + placeholder; setFormData((prev) => ({ ...prev, payload: newPayload })); }} > {placeholder} </Badge> ))} </div> </div> </div> <div className="flex items-center gap-2"> <Switch id="isEnabled" checked={formData.isEnabled} onCheckedChange={(checked) => setFormData((prev) => ({ ...prev, isEnabled: checked })) } /> <Label htmlFor="isEnabled">{t("enabled")}</Label> </div> </div> ); return ( <> <div className="flex items-center justify-between mb-4"> <div> <h3 className="text-lg font-semibold">{t("title")}</h3> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}> <DialogTrigger asChild> <Button onClick={() => { resetForm(); setIsCreateOpen(true); }}> <Plus className="h-4 w-4 mr-2" /> {t("add")} </Button> </DialogTrigger> <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-y-auto"> <DialogHeader> <DialogTitle>{t("addTitle")}</DialogTitle> <DialogDescription>{t("addDescription")}</DialogDescription> </DialogHeader> <WebhookForm /> <DialogFooter> <Button variant="outline" onClick={() => setIsCreateOpen(false)}> {t("cancel")} </Button> <Button onClick={handleCreate} disabled={isLoading}> {t("create")} </Button> </DialogFooter> </DialogContent> </Dialog> </div> <div className="rounded-md border"> {webhooks.length === 0 ? ( <div className="text-center py-8 text-muted-foreground"> {t("empty")} </div> ) : ( <Table> <TableHeader> <TableRow> <TableHead>{t("name")}</TableHead> <TableHead>{t("url")}</TableHead> <TableHead>{t("events")}</TableHead> <TableHead>{t("status")}</TableHead> <TableHead className="w-[70px]"></TableHead> </TableRow> </TableHeader> <TableBody> {webhooks.map((webhook) => ( <TableRow key={webhook.id}> <TableCell className="font-medium">{webhook.name}</TableCell> <TableCell className="max-w-[200px] truncate text-xs font-mono"> {webhook.url} </TableCell> <TableCell> <div className="flex flex-wrap gap-1"> {webhook.events.map((event) => ( <Badge key={event} variant="secondary" className="text-xs"> {event.replace("PROMPT_", "")} </Badge> ))} </div> </TableCell> <TableCell> <Switch checked={webhook.isEnabled} onCheckedChange={() => handleToggleEnabled(webhook)} /> </TableCell> <TableCell> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => handleTest(webhook)}> <Play className="h-4 w-4 mr-2" /> {t("test")} </DropdownMenuItem> <DropdownMenuItem onClick={() => openEditDialog(webhook)}> <Pencil className="h-4 w-4 mr-2" /> {t("edit")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleDelete(webhook.id)} className="text-destructive" > <Trash2 className="h-4 w-4 mr-2" /> {t("delete")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </TableCell> </TableRow> ))} </TableBody> </Table> )} </div> {/* Edit Dialog */} <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}> <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-y-auto"> <DialogHeader> <DialogTitle>{t("editTitle")}</DialogTitle> <DialogDescription>{t("editDescription")}</DialogDescription> </DialogHeader> <WebhookForm /> <DialogFooter> <Button variant="outline" onClick={() => setIsEditOpen(false)}> {t("cancel")} </Button> <Button onClick={handleEdit} disabled={isLoading}> {t("save")} </Button> </DialogFooter> </DialogContent> </Dialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/reports-table.tsx
src/components/admin/reports-table.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations, useLocale } from "next-intl"; import Link from "next/link"; import { formatDistanceToNow } from "@/lib/date"; import { getPromptUrl } from "@/lib/urls"; import { MoreHorizontal, Check, X, Eye, ExternalLink, RotateCcw, ListPlus } from "lucide-react"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { toast } from "sonner"; interface Report { id: string; reason: "SPAM" | "INAPPROPRIATE" | "COPYRIGHT" | "MISLEADING" | "RELIST_REQUEST" | "OTHER"; details: string | null; status: "PENDING" | "REVIEWED" | "DISMISSED"; createdAt: Date; prompt: { id: string; slug?: string | null; title: string; isUnlisted?: boolean; deletedAt?: Date | null; }; reporter: { id: string; username: string; name: string | null; avatar: string | null; }; } interface ReportsTableProps { reports: Report[]; } export function ReportsTable({ reports }: ReportsTableProps) { const router = useRouter(); const t = useTranslations("admin.reports"); const tReport = useTranslations("report"); const locale = useLocale(); const [loading, setLoading] = useState<string | null>(null); const handleStatusChange = async (reportId: string, status: "REVIEWED" | "DISMISSED") => { setLoading(reportId); try { const res = await fetch(`/api/admin/reports/${reportId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status }), }); if (!res.ok) throw new Error("Failed to update status"); toast.success(status === "REVIEWED" ? t("markedReviewed") : t("dismissed")); router.refresh(); } catch { toast.error(t("updateFailed")); } finally { setLoading(null); } }; const handleRelistPrompt = async (promptId: string) => { setLoading(promptId); try { const res = await fetch(`/api/prompts/${promptId}/unlist`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ unlist: false }), }); if (!res.ok) throw new Error("Failed to relist prompt"); toast.success(t("promptRelisted")); router.refresh(); } catch { toast.error(t("relistFailed")); } finally { setLoading(null); } }; const handleRestorePrompt = async (promptId: string) => { setLoading(promptId); try { const res = await fetch(`/api/prompts/${promptId}/restore`, { method: "POST", }); if (!res.ok) throw new Error("Failed to restore prompt"); toast.success(t("promptRestored")); router.refresh(); } catch { toast.error(t("restoreFailed")); } finally { setLoading(null); } }; const statusColors = { PENDING: "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20", REVIEWED: "bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20", DISMISSED: "bg-muted text-muted-foreground", }; const reasonLabels: Record<string, string> = { SPAM: tReport("reasons.spam"), INAPPROPRIATE: tReport("reasons.inappropriate"), COPYRIGHT: tReport("reasons.copyright"), MISLEADING: tReport("reasons.misleading"), RELIST_REQUEST: tReport("reasons.relistRequest"), OTHER: tReport("reasons.other"), }; return ( <> <div className="flex items-center justify-between mb-4"> <div> <h3 className="text-lg font-semibold">{t("title")}</h3> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> </div> {reports.length === 0 ? ( <div className="text-center py-12 text-muted-foreground border rounded-md"> {t("noReports")} </div> ) : ( <div className="rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>{t("prompt")}</TableHead> <TableHead>{t("reason")}</TableHead> <TableHead>{t("reportedBy")}</TableHead> <TableHead>{t("status")}</TableHead> <TableHead>{t("date")}</TableHead> <TableHead className="w-[50px]"></TableHead> </TableRow> </TableHeader> <TableBody> {reports.map((report) => ( <TableRow key={report.id}> <TableCell> <Link href={getPromptUrl(report.prompt.id, report.prompt.slug)} prefetch={false} className="font-medium hover:underline flex items-center gap-1" > {report.prompt.title} <ExternalLink className="h-3 w-3" /> </Link> </TableCell> <TableCell> <div> <Badge variant="outline">{reasonLabels[report.reason]}</Badge> {report.details && ( <p className="text-xs text-muted-foreground mt-1 max-w-[200px] truncate"> {report.details} </p> )} </div> </TableCell> <TableCell> <div className="flex items-center gap-2"> <Avatar className="h-6 w-6"> <AvatarImage src={report.reporter.avatar || undefined} /> <AvatarFallback className="text-xs"> {report.reporter.name?.charAt(0) || report.reporter.username.charAt(0)} </AvatarFallback> </Avatar> <span className="text-sm">@{report.reporter.username}</span> </div> </TableCell> <TableCell> <Badge variant="outline" className={statusColors[report.status]}> {t(`statuses.${report.status.toLowerCase()}`)} </Badge> </TableCell> <TableCell className="text-sm text-muted-foreground"> {formatDistanceToNow(report.createdAt, locale)} </TableCell> <TableCell> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="h-8 w-8" disabled={loading === report.id} > <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem asChild> <Link href={getPromptUrl(report.prompt.id, report.prompt.slug)} prefetch={false}> <Eye className="h-4 w-4 mr-2" /> {t("viewPrompt")} </Link> </DropdownMenuItem> <DropdownMenuSeparator /> {report.status === "PENDING" && ( <> <DropdownMenuItem onClick={() => handleStatusChange(report.id, "REVIEWED")}> <Check className="h-4 w-4 mr-2" /> {t("markReviewed")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleStatusChange(report.id, "DISMISSED")}> <X className="h-4 w-4 mr-2" /> {t("dismiss")} </DropdownMenuItem> </> )} {report.status !== "PENDING" && ( <DropdownMenuItem onClick={() => handleStatusChange(report.id, "REVIEWED")} disabled={report.status === "REVIEWED"} > <Check className="h-4 w-4 mr-2" /> {t("markReviewed")} </DropdownMenuItem> )} {report.reason === "RELIST_REQUEST" && report.prompt.isUnlisted && ( <> <DropdownMenuSeparator /> <DropdownMenuItem onClick={() => handleRelistPrompt(report.prompt.id)}> <ListPlus className="h-4 w-4 mr-2" /> {t("relistPrompt")} </DropdownMenuItem> </> )} {report.prompt.deletedAt && ( <> <DropdownMenuSeparator /> <DropdownMenuItem onClick={() => handleRestorePrompt(report.prompt.id)}> <RotateCcw className="h-4 w-4 mr-2" /> {t("restorePrompt")} </DropdownMenuItem> </> )} </DropdownMenuContent> </DropdownMenu> </TableCell> </TableRow> ))} </TableBody> </Table> </div> )} </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/users-table.tsx
src/components/admin/users-table.tsx
"use client"; import { useState, useEffect, useCallback } from "react"; import { useRouter } from "next/navigation"; import { useTranslations, useLocale } from "next-intl"; import { formatDistanceToNow } from "@/lib/date"; import { MoreHorizontal, Shield, User, Trash2, BadgeCheck, Search, Loader2, ChevronLeft, ChevronRight, Filter, Flag, AlertTriangle, Sparkles } from "lucide-react"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; interface UserData { id: string; email: string; username: string; name: string | null; avatar: string | null; role: "ADMIN" | "USER"; verified: boolean; flagged: boolean; flaggedAt: string | null; flaggedReason: string | null; dailyGenerationLimit: number; generationCreditsRemaining: number; createdAt: string; _count: { prompts: number; }; } interface Pagination { page: number; limit: number; total: number; totalPages: number; } export function UsersTable() { const router = useRouter(); const t = useTranslations("admin.users"); const tCommon = useTranslations("common"); const locale = useLocale(); const [deleteUserId, setDeleteUserId] = useState<string | null>(null); const [editCreditsUser, setEditCreditsUser] = useState<UserData | null>(null); const [newCreditLimit, setNewCreditLimit] = useState(""); const [loading, setLoading] = useState(false); // Pagination and search state const [users, setUsers] = useState<UserData[]>([]); const [pagination, setPagination] = useState<Pagination | null>(null); const [searchQuery, setSearchQuery] = useState(""); const [currentPage, setCurrentPage] = useState(1); const [loadingUsers, setLoadingUsers] = useState(true); const [userFilter, setUserFilter] = useState("all"); const fetchUsers = useCallback(async (page: number, search: string, filter: string) => { setLoadingUsers(true); try { const params = new URLSearchParams({ page: page.toString(), limit: "15", ...(search && { search }), ...(filter !== "all" && { filter }), }); const res = await fetch(`/api/admin/users?${params}`); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Failed to fetch users"); } setUsers(data.users); setPagination(data.pagination); } catch (error) { toast.error(error instanceof Error ? error.message : "Failed to fetch users"); } finally { setLoadingUsers(false); } }, []); useEffect(() => { fetchUsers(currentPage, searchQuery, userFilter); // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentPage, userFilter, fetchUsers]); const handleSearch = () => { setCurrentPage(1); fetchUsers(1, searchQuery, userFilter); }; const handleFilterChange = (value: string) => { setUserFilter(value); setCurrentPage(1); }; const handleRoleChange = async (userId: string, newRole: "ADMIN" | "USER") => { try { const res = await fetch(`/api/admin/users/${userId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role: newRole }), }); if (!res.ok) throw new Error("Failed to update role"); toast.success(t("roleUpdated")); router.refresh(); } catch { toast.error(t("roleUpdateFailed")); } }; const handleVerifyToggle = async (userId: string, verified: boolean) => { try { const res = await fetch(`/api/admin/users/${userId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ verified }), }); if (!res.ok) throw new Error("Failed to update verification"); toast.success(verified ? t("verified") : t("unverified")); fetchUsers(currentPage, searchQuery, userFilter); router.refresh(); } catch { toast.error(t("verifyFailed")); } }; const handleFlagToggle = async (userId: string, flagged: boolean) => { try { const res = await fetch(`/api/admin/users/${userId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ flagged, flaggedReason: flagged ? "Unusual activity" : null }), }); if (!res.ok) throw new Error("Failed to update flag status"); toast.success(flagged ? t("flagged") : t("unflagged")); fetchUsers(currentPage, searchQuery, userFilter); router.refresh(); } catch { toast.error(t("flagFailed")); } }; const handleDelete = async () => { if (!deleteUserId) return; setLoading(true); try { const res = await fetch(`/api/admin/users/${deleteUserId}`, { method: "DELETE", }); if (!res.ok) throw new Error("Failed to delete user"); toast.success(t("deleted")); fetchUsers(currentPage, searchQuery, userFilter); router.refresh(); } catch { toast.error(t("deleteFailed")); } finally { setLoading(false); setDeleteUserId(null); } }; const handleEditCredits = (user: UserData) => { setEditCreditsUser(user); setNewCreditLimit(user.dailyGenerationLimit.toString()); }; const handleSaveCredits = async () => { if (!editCreditsUser) return; setLoading(true); try { const res = await fetch(`/api/admin/users/${editCreditsUser.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ dailyGenerationLimit: newCreditLimit }), }); if (!res.ok) throw new Error("Failed to update credits"); toast.success(t("creditsUpdated")); fetchUsers(currentPage, searchQuery, userFilter); router.refresh(); } catch { toast.error(t("creditsUpdateFailed")); } finally { setLoading(false); setEditCreditsUser(null); } }; return ( <> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4"> <div> <h3 className="text-lg font-semibold">{t("title")}</h3> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto"> <Select value={userFilter} onValueChange={handleFilterChange}> <SelectTrigger className="w-full sm:w-[140px]"> <Filter className="h-4 w-4 mr-2" /> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="all">{t("filters.all")}</SelectItem> <SelectItem value="admin">{t("filters.admin")}</SelectItem> <SelectItem value="user">{t("filters.user")}</SelectItem> <SelectItem value="verified">{t("filters.verified")}</SelectItem> <SelectItem value="unverified">{t("filters.unverified")}</SelectItem> <SelectItem value="flagged">{t("filters.flagged")}</SelectItem> </SelectContent> </Select> <div className="flex gap-2"> <div className="relative flex-1 sm:flex-none"> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <Input placeholder={t("searchPlaceholder")} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleSearch()} className="pl-9 w-full sm:w-[200px]" /> </div> <Button size="icon" variant="outline" onClick={handleSearch} disabled={loadingUsers}> {loadingUsers ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />} </Button> </div> </div> </div> {loadingUsers && users.length === 0 ? ( <div className="flex items-center justify-center py-12 border rounded-md"> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /> </div> ) : users.length === 0 ? ( <div className="text-center py-12 border rounded-md text-muted-foreground"> {t("noUsers")} </div> ) : ( <> {/* Mobile Card View */} <div className="block sm:hidden space-y-3"> {users.map((user) => ( <div key={user.id} className="rounded-lg border bg-card p-4 space-y-3"> <div className="flex items-start justify-between gap-3"> <div className="flex items-center gap-3 min-w-0"> <Avatar className="h-10 w-10"> <AvatarImage src={user.avatar || undefined} /> <AvatarFallback> {user.name?.charAt(0) || user.username.charAt(0)} </AvatarFallback> </Avatar> <div className="min-w-0"> <div className="font-medium flex items-center gap-1 truncate"> {user.name || user.username} {user.verified && <BadgeCheck className="h-4 w-4 text-blue-500 flex-shrink-0" />} {user.flagged && <AlertTriangle className="h-4 w-4 text-amber-500 flex-shrink-0" />} </div> <div className="text-xs text-muted-foreground">@{user.username}</div> </div> </div> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="h-8 w-8 flex-shrink-0"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {user.role === "USER" ? ( <DropdownMenuItem onClick={() => handleRoleChange(user.id, "ADMIN")}> <Shield className="h-4 w-4 mr-2" /> {t("makeAdmin")} </DropdownMenuItem> ) : ( <DropdownMenuItem onClick={() => handleRoleChange(user.id, "USER")}> <User className="h-4 w-4 mr-2" /> {t("removeAdmin")} </DropdownMenuItem> )} <DropdownMenuItem onClick={() => handleVerifyToggle(user.id, !user.verified)}> <BadgeCheck className="h-4 w-4 mr-2" /> {user.verified ? t("unverify") : t("verify")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleFlagToggle(user.id, !user.flagged)}> <Flag className="h-4 w-4 mr-2" /> {user.flagged ? t("unflag") : t("flag")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleEditCredits(user)}> <Sparkles className="h-4 w-4 mr-2" /> {t("editCredits")} </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem className="text-destructive" onClick={() => setDeleteUserId(user.id)} > <Trash2 className="h-4 w-4 mr-2" /> {t("delete")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </div> <div className="flex items-center justify-between text-sm"> <span className="text-muted-foreground truncate">{user.email}</span> <Badge variant={user.role === "ADMIN" ? "default" : "secondary"} className="flex-shrink-0"> {user.role === "ADMIN" ? <Shield className="h-3 w-3 mr-1" /> : <User className="h-3 w-3 mr-1" />} {user.role} </Badge> </div> <div className="flex items-center justify-between text-xs text-muted-foreground"> <span>{user._count.prompts} {t("prompts").toLowerCase()}</span> <span>{formatDistanceToNow(new Date(user.createdAt), locale)}</span> </div> </div> ))} </div> {/* Desktop Table View */} <div className="hidden sm:block rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>{t("user")}</TableHead> <TableHead>{t("email")}</TableHead> <TableHead>{t("role")}</TableHead> <TableHead className="text-center">{t("prompts")}</TableHead> <TableHead>{t("joined")}</TableHead> <TableHead className="w-[50px]"></TableHead> </TableRow> </TableHeader> <TableBody> {users.map((user) => ( <TableRow key={user.id}> <TableCell> <div className="flex items-center gap-2"> <Avatar className="h-8 w-8"> <AvatarImage src={user.avatar || undefined} /> <AvatarFallback> {user.name?.charAt(0) || user.username.charAt(0)} </AvatarFallback> </Avatar> <div> <div className="font-medium flex items-center gap-1"> {user.name || user.username} {user.verified && <BadgeCheck className="h-4 w-4 text-blue-500" />} {user.flagged && <AlertTriangle className="h-4 w-4 text-amber-500" />} </div> <div className="text-xs text-muted-foreground">@{user.username}</div> </div> </div> </TableCell> <TableCell className="text-sm">{user.email}</TableCell> <TableCell> <Badge variant={user.role === "ADMIN" ? "default" : "secondary"}> {user.role === "ADMIN" ? <Shield className="h-3 w-3 mr-1" /> : <User className="h-3 w-3 mr-1" />} {user.role} </Badge> </TableCell> <TableCell className="text-center">{user._count.prompts}</TableCell> <TableCell className="text-sm text-muted-foreground"> {formatDistanceToNow(new Date(user.createdAt), locale)} </TableCell> <TableCell> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="h-8 w-8"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> {user.role === "USER" ? ( <DropdownMenuItem onClick={() => handleRoleChange(user.id, "ADMIN")}> <Shield className="h-4 w-4 mr-2" /> {t("makeAdmin")} </DropdownMenuItem> ) : ( <DropdownMenuItem onClick={() => handleRoleChange(user.id, "USER")}> <User className="h-4 w-4 mr-2" /> {t("removeAdmin")} </DropdownMenuItem> )} <DropdownMenuItem onClick={() => handleVerifyToggle(user.id, !user.verified)}> <BadgeCheck className="h-4 w-4 mr-2" /> {user.verified ? t("unverify") : t("verify")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleFlagToggle(user.id, !user.flagged)}> <Flag className="h-4 w-4 mr-2" /> {user.flagged ? t("unflag") : t("flag")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleEditCredits(user)}> <Sparkles className="h-4 w-4 mr-2" /> {t("editCredits")} </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem className="text-destructive" onClick={() => setDeleteUserId(user.id)} > <Trash2 className="h-4 w-4 mr-2" /> {t("delete")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </TableCell> </TableRow> ))} </TableBody> </Table> </div> {/* Pagination */} {pagination && pagination.totalPages > 1 && ( <div className="flex flex-col sm:flex-row items-center justify-between gap-4 mt-4 pt-4 border-t"> <p className="text-sm text-muted-foreground"> {t("showing", { from: (pagination.page - 1) * pagination.limit + 1, to: Math.min(pagination.page * pagination.limit, pagination.total), total: pagination.total, })} </p> <div className="flex items-center gap-2"> <Button size="icon" variant="outline" className="h-8 w-8" disabled={currentPage === 1 || loadingUsers} onClick={() => setCurrentPage((p) => p - 1)} > <ChevronLeft className="h-4 w-4" /> </Button> <span className="text-sm tabular-nums px-2"> {currentPage} / {pagination.totalPages} </span> <Button size="icon" variant="outline" className="h-8 w-8" disabled={currentPage === pagination.totalPages || loadingUsers} onClick={() => setCurrentPage((p) => p + 1)} > <ChevronRight className="h-4 w-4" /> </Button> </div> </div> )} </> )} <AlertDialog open={!!deleteUserId} onOpenChange={() => setDeleteUserId(null)}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} disabled={loading} className="bg-destructive text-white hover:bg-destructive/90" > {t("delete")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> {/* Edit Credits Dialog */} <AlertDialog open={!!editCreditsUser} onOpenChange={() => setEditCreditsUser(null)}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("editCreditsTitle")}</AlertDialogTitle> <AlertDialogDescription> {t("editCreditsDescription", { username: editCreditsUser?.username || "" })} </AlertDialogDescription> </AlertDialogHeader> <div className="py-4"> <div className="space-y-2"> <label className="text-sm font-medium">{t("dailyLimit")}</label> <Input type="number" min="0" value={newCreditLimit} onChange={(e) => setNewCreditLimit(e.target.value)} placeholder="10" /> <p className="text-xs text-muted-foreground"> {t("currentCredits", { remaining: editCreditsUser?.generationCreditsRemaining ?? 0, limit: editCreditsUser?.dailyGenerationLimit ?? 0 })} </p> </div> </div> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleSaveCredits} disabled={loading}> {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} {t("save")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/import-prompts.tsx
src/components/admin/import-prompts.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { Upload, FileText, CheckCircle, AlertCircle, Loader2, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; interface ImportResult { success: boolean; imported: number; skipped: number; total: number; errors: string[]; } export function ImportPrompts() { const router = useRouter(); const t = useTranslations("admin.import"); const [loading, setLoading] = useState(false); const [deleting, setDeleting] = useState(false); const [showConfirm, setShowConfirm] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [result, setResult] = useState<ImportResult | null>(null); const handleImport = async () => { setLoading(true); setShowConfirm(false); setResult(null); try { const res = await fetch("/api/admin/import-prompts", { method: "POST", }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Import failed"); } setResult(data); if (data.imported > 0) { toast.success(t("success", { count: data.imported })); router.refresh(); } else if (data.skipped === data.total) { toast.info(t("allSkipped")); } } catch (error) { const message = error instanceof Error ? error.message : "Import failed"; toast.error(message); } finally { setLoading(false); } }; const handleDelete = async () => { setDeleting(true); setShowDeleteConfirm(false); setResult(null); try { const res = await fetch("/api/admin/import-prompts", { method: "DELETE", }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || "Delete failed"); } toast.success(t("deleteSuccess", { count: data.deleted })); router.refresh(); } catch (error) { const message = error instanceof Error ? error.message : "Delete failed"; toast.error(message); } finally { setDeleting(false); } }; return ( <> <Card> <CardHeader> <CardTitle className="flex items-center gap-2"> <FileText className="h-5 w-5" /> {t("title")} </CardTitle> <CardDescription>{t("description")}</CardDescription> </CardHeader> <CardContent className="space-y-4"> <div className="rounded-lg border border-dashed p-6 text-center"> <Upload className="mx-auto h-10 w-10 text-muted-foreground mb-3" /> <p className="text-sm text-muted-foreground mb-1"> {t("fileInfo")} </p> <p className="text-xs text-muted-foreground"> {t("csvFormat")} </p> </div> <div className="flex gap-2"> <Button onClick={() => setShowConfirm(true)} disabled={loading || deleting} className="flex-1" > {loading ? ( <> <Loader2 className="mr-2 h-4 w-4 animate-spin" /> {t("importing")} </> ) : ( <> <Upload className="mr-2 h-4 w-4" /> {t("importButton")} </> )} </Button> <Button onClick={() => setShowDeleteConfirm(true)} disabled={loading || deleting} variant="destructive" > {deleting ? ( <Loader2 className="h-4 w-4 animate-spin" /> ) : ( <Trash2 className="h-4 w-4" /> )} </Button> </div> {result && ( <div className="rounded-lg border p-4 space-y-2"> <div className="flex items-center gap-2"> {result.imported > 0 ? ( <CheckCircle className="h-5 w-5 text-green-500" /> ) : ( <AlertCircle className="h-5 w-5 text-yellow-500" /> )} <span className="font-medium">{t("resultTitle")}</span> </div> <div className="text-sm text-muted-foreground space-y-1"> <p>{t("imported", { count: result.imported })}</p> <p>{t("skipped", { count: result.skipped })}</p> <p>{t("total", { count: result.total })}</p> </div> {result.errors.length > 0 && ( <div className="mt-2 pt-2 border-t"> <p className="text-sm font-medium text-destructive mb-1"> {t("errors")} </p> <ul className="text-xs text-muted-foreground space-y-1"> {result.errors.map((error, i) => ( <li key={i}>{error}</li> ))} </ul> </div> )} </div> )} </CardContent> </Card> <AlertDialog open={showConfirm} onOpenChange={setShowConfirm}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("confirmTitle")}</AlertDialogTitle> <AlertDialogDescription> {t("confirmDescription")} </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleImport}> {t("confirm")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription> {t("deleteConfirmDescription")} </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90 text-white"> {t("deleteButton")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/admin/categories-table.tsx
src/components/admin/categories-table.tsx
"use client"; import { useState, useMemo } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { MoreHorizontal, Plus, Pencil, Trash2, ChevronRight, Pin, PinOff } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { toast } from "sonner"; interface Category { id: string; name: string; slug: string; description: string | null; icon: string | null; order: number; pinned: boolean; parentId: string | null; parent: { id: string; name: string } | null; children?: Category[]; _count: { prompts: number; children: number; }; } interface CategoriesTableProps { categories: Category[]; } export function CategoriesTable({ categories }: CategoriesTableProps) { const router = useRouter(); const t = useTranslations("admin.categories"); const [editCategory, setEditCategory] = useState<Category | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null); const [isCreating, setIsCreating] = useState(false); const [loading, setLoading] = useState(false); const [formData, setFormData] = useState({ name: "", slug: "", description: "", icon: "", parentId: "", pinned: false }); // Get only root categories (no parent) for parent selection const rootCategories = useMemo(() => categories.filter(c => !c.parentId), [categories] ); // Build hierarchical list for display (parents first, then children indented) const hierarchicalCategories = useMemo(() => { const result: (Category & { level: number })[] = []; // Add root categories and their children rootCategories.forEach(parent => { result.push({ ...parent, level: 0 }); const children = categories.filter(c => c.parentId === parent.id); children.forEach(child => { result.push({ ...child, level: 1 }); }); }); return result; }, [categories, rootCategories]); const openCreateDialog = () => { setFormData({ name: "", slug: "", description: "", icon: "", parentId: "", pinned: false }); setIsCreating(true); }; const openEditDialog = (category: Category) => { setFormData({ name: category.name, slug: category.slug, description: category.description || "", icon: category.icon || "", parentId: category.parentId || "", pinned: category.pinned, }); setEditCategory(category); }; const handleTogglePin = async (category: Category) => { setLoading(true); try { const res = await fetch(`/api/admin/categories/${category.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pinned: !category.pinned }), }); if (!res.ok) throw new Error("Failed to update"); toast.success(category.pinned ? t("unpinned") : t("pinned")); router.refresh(); } catch { toast.error(t("saveFailed")); } finally { setLoading(false); } }; // Filter out invalid parent options (can't be own parent or child of self) const getValidParentOptions = () => { if (!editCategory) return rootCategories; // When editing, exclude self and any category that has this as parent return rootCategories.filter(c => c.id !== editCategory.id && c.parentId !== editCategory.id ); }; const handleSubmit = async () => { setLoading(true); try { const url = editCategory ? `/api/admin/categories/${editCategory.id}` : "/api/admin/categories"; const method = editCategory ? "PATCH" : "POST"; const payload = { ...formData, parentId: formData.parentId || null, // Convert empty string to null }; const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (!res.ok) throw new Error("Failed to save"); toast.success(editCategory ? t("updated") : t("created")); router.refresh(); setEditCategory(null); setIsCreating(false); } catch { toast.error(t("saveFailed")); } finally { setLoading(false); } }; const handleDelete = async () => { if (!deleteId) return; setLoading(true); try { const res = await fetch(`/api/admin/categories/${deleteId}`, { method: "DELETE", }); if (!res.ok) throw new Error("Failed to delete"); toast.success(t("deleted")); router.refresh(); } catch { toast.error(t("deleteFailed")); } finally { setLoading(false); setDeleteId(null); } }; return ( <> <div className="flex items-center justify-between mb-4"> <div> <h3 className="text-lg font-semibold">{t("title")}</h3> <p className="text-sm text-muted-foreground">{t("description")}</p> </div> <Button size="sm" onClick={openCreateDialog}> <Plus className="h-4 w-4 mr-2" /> {t("add")} </Button> </div> <div className="rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>{t("name")}</TableHead> <TableHead>{t("slug")}</TableHead> <TableHead>{t("parent")}</TableHead> <TableHead className="text-center">{t("prompts")}</TableHead> <TableHead className="w-[50px]"></TableHead> </TableRow> </TableHeader> <TableBody> {hierarchicalCategories.length === 0 ? ( <TableRow> <TableCell colSpan={5} className="text-center text-muted-foreground py-8"> {t("noCategories")} </TableCell> </TableRow> ) : ( hierarchicalCategories.map((category) => ( <TableRow key={category.id} className={category.level > 0 ? "bg-muted/30" : ""}> <TableCell> <div className="flex items-center gap-2" style={{ paddingLeft: category.level * 24 }}> {category.level > 0 && ( <ChevronRight className="h-3 w-3 text-muted-foreground" /> )} {category.icon && <span>{category.icon}</span>} <span className={category.level === 0 ? "font-medium" : ""}>{category.name}</span> {category._count.children > 0 && ( <Badge variant="secondary" className="text-xs"> {category._count.children} {t("subcategories")} </Badge> )} {category.pinned && ( <Badge variant="default" className="text-xs"> <Pin className="h-3 w-3 mr-1" /> {t("pinnedBadge")} </Badge> )} </div> </TableCell> <TableCell className="text-sm text-muted-foreground">{category.slug}</TableCell> <TableCell> {category.parent ? ( <Badge variant="outline">{category.parent.name}</Badge> ) : ( <Badge variant="default" className="bg-primary/10 text-primary hover:bg-primary/20"> {t("rootCategory")} </Badge> )} </TableCell> <TableCell className="text-center">{category._count.prompts}</TableCell> <TableCell> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="h-8 w-8"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => openEditDialog(category)}> <Pencil className="h-4 w-4 mr-2" /> {t("edit")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleTogglePin(category)} disabled={loading}> {category.pinned ? ( <><PinOff className="h-4 w-4 mr-2" />{t("unpin")}</> ) : ( <><Pin className="h-4 w-4 mr-2" />{t("pin")}</> )} </DropdownMenuItem> <DropdownMenuItem className="text-destructive" onClick={() => setDeleteId(category.id)} > <Trash2 className="h-4 w-4 mr-2" /> {t("delete")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </TableCell> </TableRow> )) )} </TableBody> </Table> </div> {/* Create/Edit Dialog */} <Dialog open={isCreating || !!editCategory} onOpenChange={() => { setIsCreating(false); setEditCategory(null); }}> <DialogContent> <DialogHeader> <DialogTitle>{editCategory ? t("editTitle") : t("createTitle")}</DialogTitle> <DialogDescription>{editCategory ? t("editDescription") : t("createDescription")}</DialogDescription> </DialogHeader> <div className="grid gap-4 py-4"> <div className="grid gap-2"> <Label htmlFor="name">{t("name")}</Label> <Input id="name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} /> </div> <div className="grid gap-2"> <Label htmlFor="slug">{t("slug")}</Label> <Input id="slug" value={formData.slug} onChange={(e) => setFormData({ ...formData, slug: e.target.value })} /> </div> <div className="grid gap-2"> <Label htmlFor="parentId">{t("parentCategory")}</Label> <Select value={formData.parentId} onValueChange={(value) => setFormData({ ...formData, parentId: value === "none" ? "" : value })} > <SelectTrigger> <SelectValue placeholder={t("selectParent")} /> </SelectTrigger> <SelectContent> <SelectItem value="none">{t("noParent")}</SelectItem> {getValidParentOptions().map((cat) => ( <SelectItem key={cat.id} value={cat.id}> {cat.icon && <span className="mr-2">{cat.icon}</span>} {cat.name} </SelectItem> ))} </SelectContent> </Select> <p className="text-xs text-muted-foreground">{t("parentHelp")}</p> </div> <div className="grid gap-2"> <Label htmlFor="description">{t("descriptionLabel")}</Label> <Input id="description" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} /> </div> <div className="grid gap-2"> <Label htmlFor="icon">{t("icon")}</Label> <Input id="icon" value={formData.icon} onChange={(e) => setFormData({ ...formData, icon: e.target.value })} placeholder="📁" /> </div> <div className="flex items-center gap-2"> <input type="checkbox" id="pinned" checked={formData.pinned} onChange={(e) => setFormData({ ...formData, pinned: e.target.checked })} className="h-4 w-4 rounded border-gray-300" /> <Label htmlFor="pinned" className="text-sm font-normal cursor-pointer"> {t("pinnedLabel")} </Label> </div> </div> <DialogFooter> <Button variant="outline" onClick={() => { setIsCreating(false); setEditCategory(null); }}> {t("cancel")} </Button> <Button onClick={handleSubmit} disabled={loading || !formData.name || !formData.slug}> {editCategory ? t("save") : t("create")} </Button> </DialogFooter> </DialogContent> </Dialog> {/* Delete Confirmation */} <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle> <AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>{t("cancel")}</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} disabled={loading} className="bg-destructive text-white hover:bg-destructive/90" > {t("delete")} </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/developers/embed-examples.ts
src/components/developers/embed-examples.ts
export interface EmbedExampleConfig { prompt: string; context: string; model: string; mode: string; thinking: boolean; reasoning: boolean; planning: boolean; fast: boolean; filetree: string; showFiletree: boolean; showDiff: boolean; diffFilename?: string; diffOldText?: string; diffNewText?: string; flashButton?: string; lightColor: string; darkColor: string; themeMode?: "auto" | "light" | "dark"; mcpTools?: string; showMcpTools?: boolean; } export interface EmbedExample { value: string; label: string; category: string; config: Partial<EmbedExampleConfig>; } export const EMBED_EXAMPLES: EmbedExample[] = [ // Coding Examples { value: "vibe-coding", label: "Vibe Coding", category: "Coding", config: { prompt: `Create a React hook called useDebounce that:\n- Takes a value and delay as parameters\n- Returns the debounced value\n- Properly cleans up the timeout\n- Is fully typed with TypeScript`, context: "hooks/useDebounce.ts, @codebase", model: "Claude 4.5 Sonnet", mode: "code", thinking: true, filetree: "src/\nsrc/hooks/\nsrc/hooks/useDebounce.ts\nsrc/hooks/useLocalStorage.ts\nsrc/components/\nsrc/components/SearchInput.tsx", showFiletree: true, showDiff: false, lightColor: "#8b5cf6", darkColor: "#a78bfa", }, }, { value: "vibe-coding-diff", label: "Vibe Coding with Diff", category: "Coding", config: { prompt: `Refactor this component to use the new useDebounce hook for the search input.`, context: "SearchInput.tsx, hooks/useDebounce.ts", model: "Claude 4.5 Sonnet", mode: "code", thinking: true, filetree: "src/\nsrc/hooks/\nsrc/hooks/useDebounce.ts\nsrc/components/\nsrc/components/SearchInput.tsx", showFiletree: true, showDiff: true, diffFilename: "SearchInput.tsx", diffOldText: "const [query, setQuery] = useState('');\n\nuseEffect(() => {\n fetchResults(query);\n}, [query]);", diffNewText: "const [query, setQuery] = useState('');\nconst debouncedQuery = useDebounce(query, 300);\n\nuseEffect(() => {\n fetchResults(debouncedQuery);\n}, [debouncedQuery]);", flashButton: "accept", lightColor: "#8b5cf6", darkColor: "#a78bfa", }, }, { value: "api-integration", label: "API Integration", category: "Coding", config: { prompt: `Create a type-safe API client for a REST endpoint:\n- GET /users - list all users\n- POST /users - create user\n- GET /users/:id - get user by id\n- PUT /users/:id - update user\n- DELETE /users/:id - delete user\n\nUse fetch with proper error handling and TypeScript types.`, context: "api/client.ts, @types", model: "GPT-5", mode: "code", thinking: true, reasoning: true, filetree: "src/\nsrc/api/\nsrc/api/client.ts\nsrc/api/types.ts\nsrc/hooks/\nsrc/hooks/useUsers.ts", showFiletree: true, showDiff: false, lightColor: "#3b82f6", darkColor: "#60a5fa", }, }, { value: "debugging", label: "Debug Session", category: "Coding", config: { prompt: `This React component causes an infinite re-render loop. Find and fix the bug:\n\nconst UserProfile = ({ userId }) => {\n const [user, setUser] = useState(null);\n \n useEffect(() => {\n fetchUser(userId).then(setUser);\n });\n \n return <div>{user?.name}</div>;\n};`, context: "components/UserProfile.tsx", model: "Claude 4.5 Sonnet", mode: "code", thinking: true, showFiletree: false, showDiff: true, diffFilename: "UserProfile.tsx", diffOldText: "useEffect(() => {\n fetchUser(userId).then(setUser);\n});", diffNewText: "useEffect(() => {\n fetchUser(userId).then(setUser);\n}, [userId]);", flashButton: "accept", lightColor: "#ef4444", darkColor: "#f87171", }, }, // Chat Examples { value: "chatgpt", label: "ChatGPT Style", category: "Chat", config: { prompt: `Explain the concept of closures in JavaScript with practical examples. Include:\n- What closures are\n- How they work\n- Common use cases\n- Potential pitfalls`, context: "", model: "GPT-4o", mode: "chat", thinking: false, showFiletree: false, showDiff: false, lightColor: "#10b981", darkColor: "#34d399", themeMode: "light" as const, }, }, { value: "claude", label: "Claude Style", category: "Chat", config: { prompt: `Help me write a professional email to decline a job offer while keeping the door open for future opportunities.\n\nContext:\n- Received offer from TechCorp as Senior Engineer\n- Great team and compensation, but role doesn't align with my career goals\n- Want to maintain good relationship with the hiring manager Sarah\n- Interested in their upcoming ML team expansion next year\n\nKeep it warm but professional, around 150-200 words.`, context: "", model: "Claude 4.5 Sonnet", mode: "ask", reasoning: true, showFiletree: false, showDiff: false, lightColor: "#f97316", darkColor: "#fb923c", }, }, { value: "gemini", label: "Gemini Style", category: "Chat", config: { prompt: `Compare and contrast microservices vs monolithic architecture. Create a decision matrix for when to use each approach based on:\n- Team size\n- Project complexity\n- Scaling requirements\n- Development speed\n- Maintenance costs`, context: "", model: "Gemini 2.5 Pro", mode: "chat", thinking: true, reasoning: true, showFiletree: false, showDiff: false, lightColor: "#4285f4", darkColor: "#8ab4f8", }, }, // Planning Examples { value: "project-planning", label: "Project Planning", category: "Planning", config: { prompt: `I want to build a real-time collaborative whiteboard app like Miro. Help me plan the architecture and break it down into phases:\n\nRequirements:\n- Real-time collaboration (multiple users)\n- Drawing tools (pen, shapes, text)\n- Infinite canvas with zoom/pan\n- Export to PNG/PDF\n- User authentication\n\nTech preferences: React, Node.js, WebSockets`, context: "@web", model: "GPT-5", mode: "plan", thinking: true, planning: true, showFiletree: false, showDiff: false, lightColor: "#8b5cf6", darkColor: "#a78bfa", }, }, { value: "code-review", label: "Code Review", category: "Planning", config: { prompt: `Review this pull request for a payment processing module. Check for:\n- Security vulnerabilities\n- Error handling\n- Performance issues\n- Code style consistency\n- Test coverage gaps`, context: "@pr #142, @codebase", model: "Claude 4.5 Sonnet", mode: "ask", thinking: true, reasoning: true, showFiletree: true, filetree: "src/\nsrc/payments/\nsrc/payments/processor.ts\nsrc/payments/validation.ts\nsrc/payments/__tests__/", showDiff: false, lightColor: "#f59e0b", darkColor: "#fbbf24", }, }, // Research Examples { value: "research", label: "Research Assistant", category: "Research", config: { prompt: `I'm researching the latest advancements in transformer architectures for my ML thesis. Summarize the key innovations since the original "Attention is All You Need" paper, focusing on:\n- Efficiency improvements (sparse attention, linear attention)\n- Architectural variations (encoder-only, decoder-only)\n- Notable models and their contributions\n- Current state-of-the-art benchmarks`, context: "@web", model: "GPT-5", mode: "ask", thinking: true, reasoning: true, showFiletree: false, showDiff: false, lightColor: "#06b6d4", darkColor: "#22d3ee", }, }, { value: "learning", label: "Learning Mode", category: "Research", config: { prompt: `Teach me about database indexing as if I'm a junior developer. Cover:\n1. What indexes are and why they matter\n2. B-tree vs Hash indexes\n3. When to add indexes\n4. Common indexing mistakes\n\nUse simple analogies and include a practical PostgreSQL example.`, context: "", model: "Claude 4.5 Sonnet", mode: "chat", thinking: false, reasoning: true, showFiletree: false, showDiff: false, lightColor: "#ec4899", darkColor: "#f472b6", themeMode: "dark" as const, }, }, // Quick Actions { value: "quick-refactor", label: "Quick Refactor", category: "Quick Actions", config: { prompt: `Convert this callback-based function to use async/await with proper error handling.`, context: "utils/api.js", model: "GPT-4o", mode: "code", fast: true, showFiletree: false, showDiff: true, diffFilename: "api.js", diffOldText: "function fetchData(url, callback) {\n fetch(url)\n .then(res => res.json())\n .then(data => callback(null, data))\n .catch(err => callback(err));\n}", diffNewText: "async function fetchData(url) {\n try {\n const res = await fetch(url);\n return await res.json();\n } catch (err) {\n throw new Error(`Failed to fetch: ${err.message}`);\n }\n}", flashButton: "accept", lightColor: "#22c55e", darkColor: "#4ade80", }, }, { value: "quick-test", label: "Generate Tests", category: "Quick Actions", config: { prompt: `Generate unit tests for this utility function using Jest. Cover edge cases.`, context: "utils/formatDate.ts", model: "Claude 4.5 Sonnet", mode: "code", fast: true, filetree: "src/\nsrc/utils/\nsrc/utils/formatDate.ts\nsrc/utils/__tests__/\nsrc/utils/__tests__/formatDate.test.ts", showFiletree: true, showDiff: false, lightColor: "#14b8a6", darkColor: "#2dd4bf", }, }, // MCP Tools Examples { value: "mcp-github", label: "GitHub Integration", category: "MCP Tools", config: { prompt: `Create a new GitHub issue for the bug we discussed. Include:\n- Title: "Login redirect fails on mobile Safari"\n- Labels: bug, high-priority\n- Assignee: @frontend-team\n- Description with reproduction steps`, context: "@github", model: "Claude 4.5 Sonnet", mode: "code", thinking: true, showFiletree: false, showDiff: false, mcpTools: "github:create_issue\ngithub:add_labels\ngithub:assign_issue", showMcpTools: true, lightColor: "#8b5cf6", darkColor: "#a78bfa", }, }, { value: "mcp-filesystem", label: "File Operations", category: "MCP Tools", config: { prompt: `Read the configuration file, update the API endpoint to production, and save it back.`, context: "config/settings.json", model: "GPT-5", mode: "code", thinking: true, filetree: "config/\nconfig/settings.json\nconfig/settings.dev.json\nconfig/settings.prod.json", showFiletree: true, showDiff: false, mcpTools: "filesystem:read_file\nfilesystem:write_file\nfilesystem:list_directory", showMcpTools: true, lightColor: "#f59e0b", darkColor: "#fbbf24", }, }, { value: "mcp-database", label: "Database Query", category: "MCP Tools", config: { prompt: `Find all users who signed up in the last 30 days but haven't completed onboarding. Export their emails for a re-engagement campaign.`, context: "@database", model: "GPT-5", mode: "ask", thinking: true, reasoning: true, showFiletree: false, showDiff: false, mcpTools: "postgres:query\npostgres:list_tables\ncsv:export", showMcpTools: true, lightColor: "#06b6d4", darkColor: "#22d3ee", }, }, { value: "mcp-multi-tool", label: "Multi-Tool Workflow", category: "MCP Tools", config: { prompt: `Search our codebase for deprecated API calls, create a tracking issue on GitHub, and send a Slack notification to the team.`, context: "@codebase", model: "Claude 4.5 Sonnet", mode: "plan", thinking: true, planning: true, showFiletree: false, showDiff: false, mcpTools: "github:search_code\ngithub:create_issue\nslack:send_message\nfilesystem:read_file", showMcpTools: true, lightColor: "#ec4899", darkColor: "#f472b6", }, }, // Image Generation Examples { value: "nano-banana", label: "Nano Banana Pro", category: "Image & Video", config: { prompt: `Generate a hyper-realistic image of a tiny banana the size of a grain of rice, sitting on a human fingertip. The banana should have perfect miniature details - tiny brown spots, a small stem, and realistic texture. Soft studio lighting, macro photography style, shallow depth of field.`, context: "##image, #style:photorealistic", model: "🍌 Nano Banana Pro", mode: "chat", thinking: false, showFiletree: false, showDiff: false, lightColor: "#fbbf24", darkColor: "#fcd34d", }, }, { value: "veo-video", label: "Veo 3.1 Video", category: "Image & Video", config: { prompt: `Create a smooth 5-second video transition between these two frames. The camera should slowly pan from left to right while the lighting gradually shifts from warm sunset tones to cool twilight. Add subtle particle effects floating through the air.`, context: "##image:First Frame, ##image:Last Frame", model: "Veo 3.1", mode: "chat", thinking: false, showFiletree: false, showDiff: false, lightColor: "#ef4444", darkColor: "#f87171", }, }, ];
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/developers/prompt-tokenizer.tsx
src/components/developers/prompt-tokenizer.tsx
"use client"; import { useState, useEffect, useMemo, useCallback, useRef } from "react"; import { useTranslations } from "next-intl"; import { useTheme } from "next-themes"; import Editor, { type Monaco } from "@monaco-editor/react"; import type { editor } from "monaco-editor"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Progress } from "@/components/ui/progress"; import { Switch } from "@/components/ui/switch"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Copy, Check, Trash2, HardDrive, AlertTriangle, DollarSign, Hash, FileText, Type, Zap, Settings2, Highlighter } from "lucide-react"; import { toast } from "sonner"; import { cn } from "@/lib/utils"; // Default settings const DEFAULT_CONTEXT_WINDOW = 128000; const DEFAULT_INPUT_PRICE = 2.50; const DEFAULT_OUTPUT_PRICE = 10.00; const SETTINGS_STORAGE_KEY = "promptTokenizerSettings"; interface TokenStats { tokens: number; characters: number; words: number; lines: number; sentences: number; } interface TokenizerSettings { contextWindow: number; inputPrice: number; outputPrice: number; } interface SavedAnalysis { id: string; text: string; stats: TokenStats; createdAt: number; } const STORAGE_KEY = "promptTokenizerHistory"; const MAX_HISTORY = 30; // Model-agnostic token estimation (~4 chars per token average) function estimateTokens(text: string): number { if (!text) return 0; const charCount = text.length; const wordCount = text.split(/\s+/).filter(Boolean).length; // Average across common tokenizers: ~4 chars per token, with word boundary adjustments return Math.ceil(charCount / 4 + wordCount * 0.1); } function calculateStats(text: string): TokenStats { const characters = text.length; const words = text.split(/\s+/).filter(Boolean).length; const lines = text.split(/\n/).length; const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0).length; const tokens = estimateTokens(text); return { tokens, characters, words, lines, sentences }; } function loadSettings(): TokenizerSettings { if (typeof window === "undefined") return { contextWindow: DEFAULT_CONTEXT_WINDOW, inputPrice: DEFAULT_INPUT_PRICE, outputPrice: DEFAULT_OUTPUT_PRICE }; try { const saved = localStorage.getItem(SETTINGS_STORAGE_KEY); if (saved) { const parsed = JSON.parse(saved); return { contextWindow: parsed.contextWindow ?? DEFAULT_CONTEXT_WINDOW, inputPrice: parsed.inputPrice ?? DEFAULT_INPUT_PRICE, outputPrice: parsed.outputPrice ?? DEFAULT_OUTPUT_PRICE, }; } } catch {} return { contextWindow: DEFAULT_CONTEXT_WINDOW, inputPrice: DEFAULT_INPUT_PRICE, outputPrice: DEFAULT_OUTPUT_PRICE }; } function saveSettings(settings: TokenizerSettings) { if (typeof window === "undefined") return; localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(settings)); } function loadHistory(): SavedAnalysis[] { if (typeof window === "undefined") return []; try { const saved = localStorage.getItem(STORAGE_KEY); return saved ? JSON.parse(saved) : []; } catch { return []; } } function saveHistory(history: SavedAnalysis[]) { if (typeof window === "undefined") return; localStorage.setItem(STORAGE_KEY, JSON.stringify(history.slice(0, MAX_HISTORY))); } function formatNumber(num: number): string { if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`; if (num >= 1000) return `${(num / 1000).toFixed(1)}K`; return num.toLocaleString(); } function formatPrice(price: number): string { if (price < 0.01) return `$${price.toFixed(4)}`; if (price < 1) return `$${price.toFixed(3)}`; return `$${price.toFixed(2)}`; } // Approximate tokenization for visualization (simulates BPE-like splitting) function tokenizeForVisualization(text: string): { start: number; end: number }[] { if (!text) return []; const tokens: { start: number; end: number }[] = []; let pos = 0; while (pos < text.length) { // Skip whitespace as its own token if (/\s/.test(text[pos])) { const start = pos; while (pos < text.length && /\s/.test(text[pos])) { pos++; } tokens.push({ start, end: pos }); continue; } // Handle punctuation as single tokens if (/[^\w\s]/.test(text[pos])) { tokens.push({ start: pos, end: pos + 1 }); pos++; continue; } // Handle words - split into ~4 char chunks to simulate subword tokenization const wordStart = pos; while (pos < text.length && /\w/.test(text[pos])) { pos++; } const word = text.slice(wordStart, pos); // Split longer words into subword tokens (~4 chars each) if (word.length <= 4) { tokens.push({ start: wordStart, end: pos }); } else { let subPos = wordStart; while (subPos < pos) { const chunkSize = Math.min(4, pos - subPos); tokens.push({ start: subPos, end: subPos + chunkSize }); subPos += chunkSize; } } } return tokens; } export function PromptTokenizer() { const t = useTranslations("developers"); const { theme } = useTheme(); const [text, setText] = useState(""); const [history, setHistory] = useState<SavedAnalysis[]>([]); const [selectedId, setSelectedId] = useState<string | null>(null); const [copied, setCopied] = useState(false); const [highlightTokens, setHighlightTokens] = useState(false); // Monaco editor refs const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null); const monacoRef = useRef<Monaco | null>(null); const decorationsRef = useRef<editor.IEditorDecorationsCollection | null>(null); // User-configurable settings const [contextWindow, setContextWindow] = useState(DEFAULT_CONTEXT_WINDOW); const [inputPrice, setInputPrice] = useState(DEFAULT_INPUT_PRICE); const [outputPrice, setOutputPrice] = useState(DEFAULT_OUTPUT_PRICE); const stats = useMemo(() => calculateStats(text), [text]); const contextUsage = useMemo(() => contextWindow > 0 ? (stats.tokens / contextWindow) * 100 : 0, [stats.tokens, contextWindow] ); const estimatedInputCost = useMemo(() => (stats.tokens / 1000000) * inputPrice, [stats.tokens, inputPrice] ); const estimatedOutputCost = useMemo(() => (stats.tokens / 1000000) * outputPrice, [stats.tokens, outputPrice] ); // Load history and settings on mount useEffect(() => { setHistory(loadHistory()); const settings = loadSettings(); setContextWindow(settings.contextWindow); setInputPrice(settings.inputPrice); setOutputPrice(settings.outputPrice); }, []); // Save settings when they change useEffect(() => { saveSettings({ contextWindow, inputPrice, outputPrice }); }, [contextWindow, inputPrice, outputPrice]); // Apply token highlighting decorations useEffect(() => { if (!editorRef.current || !monacoRef.current) return; const editor = editorRef.current; const monaco = monacoRef.current; // Clear existing decorations if (decorationsRef.current) { decorationsRef.current.clear(); } if (!highlightTokens || !text) return; const tokens = tokenizeForVisualization(text); const model = editor.getModel(); if (!model) return; // Create decorations with alternating colors const decorations: editor.IModelDeltaDecoration[] = tokens .filter(token => !/^\s+$/.test(text.slice(token.start, token.end))) // Skip whitespace-only tokens .map((token, index) => { const startPos = model.getPositionAt(token.start); const endPos = model.getPositionAt(token.end); return { range: new monaco.Range( startPos.lineNumber, startPos.column, endPos.lineNumber, endPos.column ), options: { inlineClassName: index % 2 === 0 ? "token-highlight-even" : "token-highlight-odd", }, }; }); decorationsRef.current = editor.createDecorationsCollection(decorations); }, [text, highlightTokens]); const handleEditorMount = useCallback((editor: editor.IStandaloneCodeEditor, monaco: Monaco) => { editorRef.current = editor; monacoRef.current = monaco; // Add custom CSS for token highlighting const styleId = "token-highlight-styles"; if (!document.getElementById(styleId)) { const style = document.createElement("style"); style.id = styleId; style.textContent = ` .token-highlight-even { background-color: rgba(59, 130, 246, 0.25); border-radius: 2px; } .token-highlight-odd { background-color: rgba(168, 85, 247, 0.25); border-radius: 2px; } `; document.head.appendChild(style); } }, []); const addToHistory = useCallback(() => { if (!text.trim()) return; const newItem: SavedAnalysis = { id: Date.now().toString(), text: text.slice(0, 500), // Store truncated for history stats, createdAt: Date.now(), }; const newHistory = [newItem, ...history].slice(0, MAX_HISTORY); setHistory(newHistory); saveHistory(newHistory); setSelectedId(newItem.id); toast.success(t("tokenizer.saved")); }, [text, stats, history, t]); const deleteFromHistory = useCallback((id: string) => { const newHistory = history.filter((item) => item.id !== id); setHistory(newHistory); saveHistory(newHistory); if (selectedId === id) { setSelectedId(null); } }, [history, selectedId]); const loadFromHistory = useCallback((item: SavedAnalysis) => { setText(item.text); setSelectedId(item.id); }, []); const handleCopy = async () => { const report = `Token Analysis Report Tokens: ${stats.tokens.toLocaleString()} Characters: ${stats.characters.toLocaleString()} Words: ${stats.words.toLocaleString()} Lines: ${stats.lines.toLocaleString()} Context Usage: ${contextUsage.toFixed(2)}% of ${formatNumber(contextWindow)} Estimated Input Cost: ${formatPrice(estimatedInputCost)} Estimated Output Cost: ${formatPrice(estimatedOutputCost)}`; await navigator.clipboard.writeText(report); setCopied(true); toast.success(t("copied")); setTimeout(() => setCopied(false), 2000); }; const clearText = () => { setText(""); setSelectedId(null); }; return ( <div className="h-full flex overflow-hidden"> {/* History Sidebar */} <div className="w-56 h-full flex flex-col border-r bg-muted/20 shrink-0"> <div className="p-3 border-b"> <h3 className="text-sm font-medium">{t("history")}</h3> <p className="text-xs text-muted-foreground flex items-center gap-1 mt-1"> <HardDrive className="h-3 w-3" /> {t("storedOnDevice")} </p> </div> <ScrollArea className="flex-1"> <div className="p-2 space-y-1"> {history.length === 0 ? ( <p className="text-xs text-muted-foreground text-center py-4"> {t("noHistory")} </p> ) : ( history.map((item) => ( <div key={item.id} className={cn( "group relative p-2 rounded-md cursor-pointer text-xs hover:bg-muted transition-colors", selectedId === item.id && "bg-muted" )} onClick={() => loadFromHistory(item)} > <p className="font-medium truncate pr-6">{item.text.slice(0, 30)}...</p> <p className="text-muted-foreground mt-0.5"> {item.stats.tokens.toLocaleString()} tokens </p> <Button variant="ghost" size="icon" className="absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => { e.stopPropagation(); deleteFromHistory(item.id); }} > <Trash2 className="h-3 w-3" /> </Button> </div> )) )} </div> </ScrollArea> </div> {/* Main Editor Panel */} <div className="flex-1 h-full flex flex-col min-w-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("tokenizer.inputText")}</span> <div className="flex items-center gap-3"> <div className="flex items-center gap-2"> <Highlighter className="h-3.5 w-3.5 text-muted-foreground" /> <Label htmlFor="highlight-toggle" className="text-xs text-muted-foreground cursor-pointer"> {t("tokenizer.highlightTokens")} </Label> <Switch id="highlight-toggle" checked={highlightTokens} onCheckedChange={setHighlightTokens} className="scale-75" /> </div> <Button variant="ghost" size="icon" className="h-7 w-7" onClick={clearText}> <Trash2 className="h-3.5 w-3.5" /> </Button> </div> </div> <div className="flex-1 min-h-0 overflow-hidden"> <Editor height="100%" language="markdown" value={text} onChange={(value) => setText(value ?? "")} onMount={handleEditorMount} theme={theme === "dark" ? "vs-dark" : "light"} options={{ minimap: { enabled: false }, fontSize: 13, lineNumbers: "on", wordWrap: "on", scrollBeyondLastLine: false, automaticLayout: true, padding: { top: 8, bottom: 8 }, renderLineHighlight: "none", placeholder: t("tokenizer.placeholder"), }} /> </div> <div className="h-10 px-4 border-t bg-background flex items-center justify-between shrink-0"> <div className="text-xs text-muted-foreground"> {text.length.toLocaleString()} characters </div> <Button onClick={addToHistory} disabled={!text.trim()} size="sm" variant="outline" className="h-7 gap-1.5" > <HardDrive className="h-3.5 w-3.5" /> {t("tokenizer.saveToHistory")} </Button> </div> </div> {/* Stats Panel */} <div className="w-80 h-full flex flex-col border-l bg-muted/20 shrink-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("tokenizer.analysis")}</span> <Button variant="ghost" size="icon" onClick={handleCopy} className="h-6 w-6" > {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />} </Button> </div> <ScrollArea className="flex-1"> <div className="p-4 space-y-4"> {/* Token Count - Primary */} <div className="space-y-1"> <div className="flex items-center gap-2 text-xs text-muted-foreground mb-1"> <Hash className="h-3.5 w-3.5" /> {t("tokenizer.tokens")} </div> <div className="text-3xl font-bold tabular-nums"> {stats.tokens.toLocaleString()} </div> <div className="text-xs text-muted-foreground mt-1"> ≈ {(stats.characters / stats.tokens || 0).toFixed(1)} chars/token </div> </div> {/* Settings */} <div className="p-3 rounded-lg border bg-background space-y-3"> <div className="flex items-center gap-2 text-xs font-medium"> <Settings2 className="h-3.5 w-3.5" /> {t("tokenizer.settings")} </div> <div className="space-y-1.5"> <Label className="text-[10px] text-muted-foreground">{t("tokenizer.contextWindowSize")}</Label> <Input type="number" value={contextWindow} onChange={(e) => setContextWindow(Math.max(1, parseInt(e.target.value) || 0))} className="h-7 text-xs" min={1} /> </div> <div className="grid grid-cols-2 gap-2"> <div className="space-y-1.5"> <Label className="text-[10px] text-muted-foreground">{t("tokenizer.inputPricePerMillion")}</Label> <div className="relative"> <span className="absolute left-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">$</span> <Input type="number" value={inputPrice} onChange={(e) => setInputPrice(Math.max(0, parseFloat(e.target.value) || 0))} className="h-7 text-xs pl-5" min={0} step={0.01} /> </div> </div> <div className="space-y-1.5"> <Label className="text-[10px] text-muted-foreground">{t("tokenizer.outputPricePerMillion")}</Label> <div className="relative"> <span className="absolute left-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">$</span> <Input type="number" value={outputPrice} onChange={(e) => setOutputPrice(Math.max(0, parseFloat(e.target.value) || 0))} className="h-7 text-xs pl-5" min={0} step={0.01} /> </div> </div> </div> </div> {/* Context Window Usage */} <div className="space-y-2"> <div className="flex items-center justify-between text-xs"> <span className="text-muted-foreground">{t("tokenizer.contextUsage")}</span> <span className={cn( "font-medium", contextUsage > 90 && "text-red-500", contextUsage > 75 && contextUsage <= 90 && "text-yellow-500" )}> {contextUsage.toFixed(2)}% </span> </div> <Progress value={Math.min(contextUsage, 100)} className={cn( "h-2", contextUsage > 90 && "[&>div]:bg-red-500", contextUsage > 75 && contextUsage <= 90 && "[&>div]:bg-yellow-500" )} /> <div className="flex items-center justify-between text-[10px] text-muted-foreground"> <span>{formatNumber(stats.tokens)}</span> <span>{formatNumber(contextWindow)}</span> </div> {contextUsage > 90 && ( <div className="flex items-center gap-1.5 text-xs text-red-500 mt-1"> <AlertTriangle className="h-3 w-3" /> {t("tokenizer.nearLimit")} </div> )} </div> {/* Cost Estimation */} <div className="p-3 rounded-lg border bg-background"> <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2"> <DollarSign className="h-3.5 w-3.5" /> {t("tokenizer.estimatedCost")} </div> <div className="grid grid-cols-2 gap-2"> <div> <div className="text-lg font-semibold tabular-nums"> {formatPrice(estimatedInputCost)} </div> <div className="text-[10px] text-muted-foreground">Input</div> </div> <div> <div className="text-lg font-semibold tabular-nums"> {formatPrice(estimatedOutputCost)} </div> <div className="text-[10px] text-muted-foreground">Output (if same)</div> </div> </div> <div className="text-[10px] text-muted-foreground mt-2 pt-2 border-t"> ${inputPrice}/1M in • ${outputPrice}/1M out </div> </div> {/* Detailed Stats */} <div className="space-y-2"> <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wider"> {t("tokenizer.textStats")} </h4> <div className="grid grid-cols-2 gap-2"> <div className="p-2 rounded border bg-background"> <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground"> <Type className="h-3 w-3" /> Characters </div> <div className="text-sm font-medium tabular-nums"> {stats.characters.toLocaleString()} </div> </div> <div className="p-2 rounded border bg-background"> <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground"> <FileText className="h-3 w-3" /> Words </div> <div className="text-sm font-medium tabular-nums"> {stats.words.toLocaleString()} </div> </div> <div className="p-2 rounded border bg-background"> <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground"> <Zap className="h-3 w-3" /> Lines </div> <div className="text-sm font-medium tabular-nums"> {stats.lines.toLocaleString()} </div> </div> <div className="p-2 rounded border bg-background"> <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground"> <FileText className="h-3 w-3" /> Sentences </div> <div className="text-sm font-medium tabular-nums"> {stats.sentences.toLocaleString()} </div> </div> </div> </div> {/* Note */} <p className="text-[10px] text-muted-foreground leading-relaxed"> {t("tokenizer.estimationNote")} </p> </div> </ScrollArea> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/developers/embed-designer.tsx
src/components/developers/embed-designer.tsx
"use client"; import { useState, useEffect, useCallback } from "react"; import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Copy, Check, Code2, ExternalLink, RotateCcw } from "lucide-react"; import { toast } from "sonner"; import { EMBED_EXAMPLES } from "./embed-examples"; interface EmbedConfig { prompt: string; context: string; model: string; mode: string; thinking: boolean; reasoning: boolean; planning: boolean; fast: boolean; max: boolean; lightColor: string; darkColor: string; height: number; themeMode: "auto" | "light" | "dark"; filetree: string; showFiletree: boolean; showDiff: boolean; diffFilename: string; diffOldText: string; diffNewText: string; flashButton: string; mcpTools: string; showMcpTools: boolean; } const MODELS = [ { value: "GPT-5", label: "GPT-5" }, { value: "GPT-4o", label: "GPT-4o" }, { value: "o3", label: "o3" }, { value: "o4-mini", label: "o4-mini" }, { value: "Claude 4.5 Sonnet", label: "Claude 4.5 Sonnet" }, { value: "Claude 4 Opus", label: "Claude 4 Opus" }, { value: "Gemini 3", label: "Gemini 3" }, { value: "Gemini 2.5 Pro", label: "Gemini 2.5 Pro" }, { value: "Grok 4", label: "Grok 4" }, { value: "DeepSeek R2", label: "DeepSeek R2" }, { value: "Llama 4", label: "Llama 4" }, { value: "custom", label: "Custom..." }, ]; const COLOR_PRESETS = [ { name: "Blue", light: "#3b82f6", dark: "#60a5fa" }, { name: "Green", light: "#10b981", dark: "#34d399" }, { name: "Orange", light: "#f97316", dark: "#fb923c" }, { name: "Purple", light: "#8b5cf6", dark: "#a78bfa" }, { name: "Pink", light: "#ec4899", dark: "#f472b6" }, { name: "Red", light: "#ef4444", dark: "#f87171" }, ]; const STORAGE_KEY = "embedDesignerConfig"; const defaultConfig: EmbedConfig = { prompt: "Hello! This is a sample prompt to show how the embed preview works.", context: "@assistant, #example", model: "GPT-5", mode: "chat", thinking: false, reasoning: false, planning: false, fast: false, max: false, lightColor: "#3b82f6", darkColor: "#60a5fa", height: 400, themeMode: "auto", filetree: "", showFiletree: false, showDiff: false, diffFilename: "", diffOldText: "", diffNewText: "", flashButton: "none", mcpTools: "", showMcpTools: false, }; export function EmbedDesigner() { const t = useTranslations("developers"); const [config, setConfig] = useState<EmbedConfig>(defaultConfig); const [customModel, setCustomModel] = useState(""); const [copied, setCopied] = useState(false); const [previewKey, setPreviewKey] = useState(0); useEffect(() => { const saved = localStorage.getItem(STORAGE_KEY); if (saved) { try { const parsed = JSON.parse(saved); setConfig({ ...defaultConfig, ...parsed }); if (!MODELS.find(m => m.value === parsed.model)) { setCustomModel(parsed.model); } } catch (e) { console.error("Error loading saved config:", e); } } }, []); useEffect(() => { localStorage.setItem(STORAGE_KEY, JSON.stringify(config)); }, [config]); const updateConfig = useCallback((updates: Partial<EmbedConfig>) => { setConfig(prev => ({ ...prev, ...updates })); }, []); const generatePreviewURL = useCallback(() => { const params = new URLSearchParams(); if (config.prompt) params.set("prompt", config.prompt); if (config.context) params.set("context", config.context); if (config.model !== "GPT 4o") params.set("model", config.model === "custom" ? customModel : config.model); if (config.mode !== "chat") params.set("mode", config.mode); if (config.thinking) params.set("thinking", "true"); if (config.reasoning) params.set("reasoning", "true"); if (config.planning) params.set("planning", "true"); if (config.fast) params.set("fast", "true"); if (config.max) params.set("max", "true"); params.set("lightColor", config.lightColor); params.set("darkColor", config.darkColor); params.set("themeMode", config.themeMode); if (config.showFiletree && config.filetree) params.set("filetree", config.filetree); if (config.showDiff) { params.set("showDiff", "true"); if (config.diffFilename) params.set("diffFilename", config.diffFilename); if (config.flashButton !== "none") params.set("flashButton", config.flashButton); if (config.diffOldText) params.set("diffOldText", config.diffOldText.substring(0, 150)); if (config.diffNewText) params.set("diffNewText", config.diffNewText.substring(0, 150)); } if (config.showMcpTools && config.mcpTools) params.set("mcpTools", config.mcpTools); return `/embed?${params.toString()}`; }, [config, customModel]); const generateEmbedCode = useCallback(() => { const url = `${typeof window !== "undefined" ? window.location.origin : ""}${generatePreviewURL()}`; return `<iframe src="${url}" width="100%" height="${config.height}" frameborder="0" style="border-radius: 12px; border: 1px solid #e5e7eb;"> </iframe>`; }, [config.height, generatePreviewURL]); const handleCopyEmbed = async () => { await navigator.clipboard.writeText(generateEmbedCode()); setCopied(true); toast.success(t("embedCopied")); setTimeout(() => setCopied(false), 2000); }; const loadExample = (exampleValue: string) => { const example = EMBED_EXAMPLES.find(e => e.value === exampleValue); if (example) { updateConfig({ ...defaultConfig, ...example.config, }); setPreviewKey(prev => prev + 1); toast.success(`${example.label} loaded!`); } }; const resetConfig = () => { setConfig(defaultConfig); setCustomModel(""); localStorage.removeItem(STORAGE_KEY); setPreviewKey(prev => prev + 1); toast.success(t("settingsCleared")); }; return ( <div className="h-full flex overflow-hidden"> {/* Left Panel - Settings */} <div className="w-80 h-full flex flex-col border-r bg-muted/20 shrink-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("embedSettings")}</span> <Button variant="ghost" size="icon" className="h-6 w-6" onClick={resetConfig} title={t("reset")}> <RotateCcw className="h-3 w-3" /> </Button> </div> <ScrollArea className="flex-1 min-h-0"> <div className="p-4 space-y-4"> {/* Load Example */} <div className="space-y-1.5"> <Label className="text-xs">{t("loadExample")}</Label> <Select onValueChange={loadExample}> <SelectTrigger className="h-8 text-xs"> <SelectValue placeholder={t("chooseExample")} /> </SelectTrigger> <SelectContent> {Array.from(new Set(EMBED_EXAMPLES.map(ex => ex.category))).map(category => ( <SelectGroup key={category}> <SelectLabel className="text-[10px] text-muted-foreground font-semibold uppercase tracking-wider">{category}</SelectLabel> {EMBED_EXAMPLES.filter(ex => ex.category === category).map(ex => ( <SelectItem key={ex.value} value={ex.value} className="text-xs"> {ex.label} </SelectItem> ))} </SelectGroup> ))} </SelectContent> </Select> </div> {/* Prompt Section */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Prompt</h3> <div className="space-y-1.5"> <Label className="text-xs">Context</Label> <Input value={config.context} onChange={e => updateConfig({ context: e.target.value })} placeholder="file.py, @web, @codebase, #image" className="h-8 text-xs" /> </div> <div className="space-y-1.5"> <Label className="text-xs">Prompt Text</Label> <Textarea value={config.prompt} onChange={e => updateConfig({ prompt: e.target.value })} placeholder="Enter your prompt..." className="min-h-[100px] text-xs resize-none" /> </div> </div> {/* AI Settings */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">AI Settings</h3> <div className="grid grid-cols-2 gap-2"> <div className="space-y-1.5"> <Label className="text-xs">Model</Label> <Select value={MODELS.find(m => m.value === config.model) ? config.model : "custom"} onValueChange={v => updateConfig({ model: v })} > <SelectTrigger className="h-8 text-xs"> <SelectValue /> </SelectTrigger> <SelectContent> {MODELS.map(m => ( <SelectItem key={m.value} value={m.value} className="text-xs"> {m.label} </SelectItem> ))} </SelectContent> </Select> </div> <div className="space-y-1.5"> <Label className="text-xs">Mode</Label> <Select value={config.mode} onValueChange={v => updateConfig({ mode: v })}> <SelectTrigger className="h-8 text-xs"> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="chat" className="text-xs">Chat</SelectItem> <SelectItem value="code" className="text-xs">Code</SelectItem> <SelectItem value="ask" className="text-xs">Ask</SelectItem> <SelectItem value="plan" className="text-xs">Plan</SelectItem> </SelectContent> </Select> </div> </div> {config.model === "custom" && ( <div className="space-y-1.5"> <Label className="text-xs">Custom Model</Label> <Input value={customModel} onChange={e => setCustomModel(e.target.value)} placeholder="Enter model name" className="h-8 text-xs" /> </div> )} <div className="flex items-center justify-between"> <Label className="text-xs">Thinking</Label> <Switch checked={config.thinking} onCheckedChange={v => updateConfig({ thinking: v })} /> </div> <div className="flex items-center justify-between"> <Label className="text-xs">Reasoning</Label> <Switch checked={config.reasoning} onCheckedChange={v => updateConfig({ reasoning: v })} /> </div> <div className="flex items-center justify-between"> <Label className="text-xs">Planning</Label> <Switch checked={config.planning} onCheckedChange={v => updateConfig({ planning: v })} /> </div> <div className="flex items-center justify-between"> <Label className="text-xs">Fast</Label> <Switch checked={config.fast} onCheckedChange={v => updateConfig({ fast: v })} /> </div> <div className="flex items-center justify-between"> <Label className="text-xs">Max</Label> <Switch checked={config.max} onCheckedChange={v => updateConfig({ max: v })} /> </div> </div> {/* File Tree */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">File Tree</h3> <div className="flex items-center justify-between"> <Label className="text-xs">Show File Tree</Label> <Switch checked={config.showFiletree} onCheckedChange={v => updateConfig({ showFiletree: v })} /> </div> {config.showFiletree && ( <Textarea value={config.filetree} onChange={e => updateConfig({ filetree: e.target.value })} placeholder={`src/\nsrc/components/\nsrc/components/Button.tsx`} className="min-h-[80px] text-xs font-mono resize-none" /> )} </div> {/* Diff View */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Diff View</h3> <div className="flex items-center justify-between"> <Label className="text-xs">Show Diff</Label> <Switch checked={config.showDiff} onCheckedChange={v => updateConfig({ showDiff: v })} /> </div> {config.showDiff && ( <> <Input value={config.diffFilename} onChange={e => updateConfig({ diffFilename: e.target.value })} placeholder="Filename" className="h-8 text-xs" /> <Textarea value={config.diffOldText} onChange={e => updateConfig({ diffOldText: e.target.value })} placeholder="Old code..." className="min-h-[60px] text-xs font-mono resize-none bg-red-50 dark:bg-red-950/20" /> <Textarea value={config.diffNewText} onChange={e => updateConfig({ diffNewText: e.target.value })} placeholder="New code..." className="min-h-[60px] text-xs font-mono resize-none bg-green-50 dark:bg-green-950/20" /> <div className="space-y-1.5"> <Label className="text-xs">Flash Button</Label> <Select value={config.flashButton} onValueChange={v => updateConfig({ flashButton: v })}> <SelectTrigger className="h-8 text-xs"> <SelectValue /> </SelectTrigger> <SelectContent> <SelectItem value="none" className="text-xs">None</SelectItem> <SelectItem value="accept" className="text-xs">Accept</SelectItem> <SelectItem value="reject" className="text-xs">Reject</SelectItem> </SelectContent> </Select> </div> </> )} </div> {/* MCP Tools */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">MCP Tools</h3> <div className="flex items-center justify-between"> <Label className="text-xs">Show MCP Tools</Label> <Switch checked={config.showMcpTools} onCheckedChange={v => updateConfig({ showMcpTools: v })} /> </div> {config.showMcpTools && ( <Textarea value={config.mcpTools} onChange={e => updateConfig({ mcpTools: e.target.value })} placeholder={`github:create_issue\ngithub:search_code\nfilesystem:read_file`} className="min-h-[80px] text-xs font-mono resize-none" /> )} </div> {/* Appearance */} <div className="space-y-3 pt-2 border-t"> <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Appearance</h3> <div className="space-y-1.5"> <Label className="text-xs">Theme</Label> <div className="flex gap-1"> {(["auto", "light", "dark"] as const).map(mode => ( <Button key={mode} variant={config.themeMode === mode ? "default" : "outline"} size="sm" className="flex-1 h-7 text-xs" onClick={() => { updateConfig({ themeMode: mode }); setPreviewKey(k => k + 1); }} > {mode.charAt(0).toUpperCase() + mode.slice(1)} </Button> ))} </div> </div> <div className="space-y-1.5"> <Label className="text-xs">Color Presets</Label> <div className="flex gap-1 flex-wrap"> {COLOR_PRESETS.map(preset => ( <button key={preset.name} className="w-6 h-6 rounded-full border-2 border-transparent hover:border-foreground/50 transition-colors" style={{ backgroundColor: preset.light }} onClick={() => { updateConfig({ lightColor: preset.light, darkColor: preset.dark }); setPreviewKey(k => k + 1); }} title={preset.name} /> ))} </div> </div> <div className="grid grid-cols-2 gap-2"> <div className="space-y-1.5"> <Label className="text-xs">Light Color</Label> <div className="flex gap-1"> <input type="color" value={config.lightColor} onChange={e => { updateConfig({ lightColor: e.target.value }); setPreviewKey(k => k + 1); }} className="w-8 h-8 rounded cursor-pointer" /> <Input value={config.lightColor} onChange={e => updateConfig({ lightColor: e.target.value })} onBlur={() => setPreviewKey(k => k + 1)} className="h-8 text-xs flex-1" /> </div> </div> <div className="space-y-1.5"> <Label className="text-xs">Dark Color</Label> <div className="flex gap-1"> <input type="color" value={config.darkColor} onChange={e => { updateConfig({ darkColor: e.target.value }); setPreviewKey(k => k + 1); }} className="w-8 h-8 rounded cursor-pointer" /> <Input value={config.darkColor} onChange={e => updateConfig({ darkColor: e.target.value })} onBlur={() => setPreviewKey(k => k + 1)} className="h-8 text-xs flex-1" /> </div> </div> </div> <div className="space-y-1.5"> <div className="flex justify-between"> <Label className="text-xs">Height</Label> <span className="text-xs text-muted-foreground">{config.height}px</span> </div> <input type="range" value={config.height} onChange={e => updateConfig({ height: parseInt(e.target.value) })} min={200} max={800} step={10} className="w-full h-1.5 bg-muted rounded-full appearance-none cursor-pointer accent-primary" /> </div> </div> </div> </ScrollArea> </div> {/* Right Panel - Preview & Code */} <div className="flex-1 h-full flex flex-col min-w-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("preview")}</span> <div className="flex items-center gap-2"> <Button variant="ghost" size="sm" className="h-7 gap-1.5 text-xs" asChild> <a href={generatePreviewURL()} target="_blank" rel="noopener noreferrer"> <ExternalLink className="h-3 w-3" /> {t("openInNewTab")} </a> </Button> <Button variant="default" size="sm" className="h-7 gap-1.5 text-xs" onClick={handleCopyEmbed}> {copied ? <Check className="h-3 w-3" /> : <Code2 className="h-3 w-3" />} {t("copyEmbedCode")} </Button> </div> </div> {/* Preview Area */} <div className="flex-1 min-h-0 p-4 overflow-hidden bg-[repeating-conic-gradient(#80808010_0%_25%,transparent_0%_50%)] dark:bg-[repeating-conic-gradient(#40404020_0%_25%,transparent_0%_50%)] bg-[length:20px_20px] flex items-center justify-center"> <div className="w-full max-w-[800px] rounded-xl border shadow-lg overflow-hidden bg-background" style={{ height: config.height }} > <iframe key={previewKey} src={generatePreviewURL()} className="w-full h-full border-0" title="Embed Preview" /> </div> </div> {/* Embed Code */} <div className="min-h-32 max-h-64 border-t shrink-0 flex flex-col resize-y overflow-hidden"> <div className="h-8 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-xs font-medium text-muted-foreground">{t("embedCode")}</span> <span className="text-[10px] text-muted-foreground/60 uppercase tracking-wider">HTML</span> </div> <div className="flex-1 overflow-auto bg-zinc-100 dark:bg-zinc-900"> <pre className="p-3 text-xs font-mono leading-relaxed whitespace-pre-wrap break-all"> <code className="text-zinc-700 dark:text-zinc-300"> <span className="text-pink-600 dark:text-pink-400">&lt;iframe</span>{"\n"} {" "}<span className="text-sky-600 dark:text-sky-400">src</span>=<span className="text-amber-600 dark:text-amber-300">&quot;{typeof window !== "undefined" ? window.location.origin : ""}{generatePreviewURL()}&quot;</span>{"\n"} {" "}<span className="text-sky-600 dark:text-sky-400">width</span>=<span className="text-amber-600 dark:text-amber-300">&quot;100%&quot;</span>{"\n"} {" "}<span className="text-sky-600 dark:text-sky-400">height</span>=<span className="text-amber-600 dark:text-amber-300">&quot;{config.height}&quot;</span>{"\n"} {" "}<span className="text-sky-600 dark:text-sky-400">frameborder</span>=<span className="text-amber-600 dark:text-amber-300">&quot;0&quot;</span>{"\n"} {" "}<span className="text-sky-600 dark:text-sky-400">style</span>=<span className="text-amber-600 dark:text-amber-300">&quot;border-radius: 12px; border: 1px solid #e5e7eb;&quot;</span><span className="text-pink-600 dark:text-pink-400">&gt;</span>{"\n"} <span className="text-pink-600 dark:text-pink-400">&lt;/iframe&gt;</span> </code> </pre> </div> </div> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/developers/prompt-enhancer.tsx
src/components/developers/prompt-enhancer.tsx
"use client"; import { useState, useEffect } from "react"; import { useTranslations } from "next-intl"; import { useTheme } from "next-themes"; import Editor from "@monaco-editor/react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Loader2, Sparkles, Copy, Check, Trash2, HardDrive } from "lucide-react"; import { toast } from "sonner"; import { RunPromptButton } from "@/components/prompts/run-prompt-button"; import { ScrollArea } from "@/components/ui/scroll-area"; const OUTPUT_TYPES = [ { value: "text", label: "Text" }, { value: "image", label: "Image" }, { value: "video", label: "Video" }, { value: "sound", label: "Sound" }, ] as const; const OUTPUT_FORMATS = [ { value: "text", label: "Text" }, { value: "structured_json", label: "JSON" }, { value: "structured_yaml", label: "YAML" }, ] as const; type OutputType = (typeof OUTPUT_TYPES)[number]["value"]; type OutputFormat = (typeof OUTPUT_FORMATS)[number]["value"]; interface EnhanceResponse { original: string; improved: string; outputType: OutputType; outputFormat: OutputFormat; inspirations: Array<{ id: string; slug: string | null; title: string; similarity: number }>; model: string; } interface SavedPrompt { id: string; input: string; output: string; outputType: OutputType; outputFormat: OutputFormat; createdAt: number; } const STORAGE_KEY = "promptEnhancerHistory"; const MAX_HISTORY = 50; function loadHistory(): SavedPrompt[] { if (typeof window === "undefined") return []; try { const saved = localStorage.getItem(STORAGE_KEY); return saved ? JSON.parse(saved) : []; } catch { return []; } } function saveHistory(history: SavedPrompt[]) { if (typeof window === "undefined") return; localStorage.setItem(STORAGE_KEY, JSON.stringify(history.slice(0, MAX_HISTORY))); } export function PromptEnhancer() { const t = useTranslations("developers"); const { theme } = useTheme(); const [prompt, setPrompt] = useState(""); const [outputType, setOutputType] = useState<OutputType>("text"); const [outputFormat, setOutputFormat] = useState<OutputFormat>("text"); const [isLoading, setIsLoading] = useState(false); const [result, setResult] = useState<EnhanceResponse | null>(null); const [copied, setCopied] = useState(false); const [history, setHistory] = useState<SavedPrompt[]>([]); const [selectedId, setSelectedId] = useState<string | null>(null); // Load history from localStorage on mount useEffect(() => { setHistory(loadHistory()); }, []); // Determine language for Monaco based on output format const getEditorLanguage = () => { if (outputFormat === "structured_json") return "json"; if (outputFormat === "structured_yaml") return "yaml"; return "markdown"; }; const addToHistory = (input: string, output: string, type: OutputType, format: OutputFormat) => { const newItem: SavedPrompt = { id: Date.now().toString(), input, output, outputType: type, outputFormat: format, createdAt: Date.now(), }; const newHistory = [newItem, ...history].slice(0, MAX_HISTORY); setHistory(newHistory); saveHistory(newHistory); setSelectedId(newItem.id); }; const deleteFromHistory = (id: string) => { const newHistory = history.filter((item) => item.id !== id); setHistory(newHistory); saveHistory(newHistory); if (selectedId === id) { setSelectedId(null); setResult(null); setPrompt(""); } }; const loadFromHistory = (item: SavedPrompt) => { setPrompt(item.input); setOutputType(item.outputType); setOutputFormat(item.outputFormat); setResult({ original: item.input, improved: item.output, outputType: item.outputType, outputFormat: item.outputFormat, inspirations: [], model: "", }); setSelectedId(item.id); }; const handleEnhance = async () => { if (!prompt.trim()) { toast.error(t("enterPrompt")); return; } setIsLoading(true); try { const response = await fetch("/api/improve-prompt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: prompt.trim(), outputType, outputFormat }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || t("enhanceFailed")); } setResult(data); addToHistory(prompt.trim(), data.improved, outputType, outputFormat); toast.success(t("enhanceSuccess")); } catch (error) { toast.error( error instanceof Error ? error.message : t("enhanceFailed") ); } finally { setIsLoading(false); } }; const handleCopy = async () => { if (result?.improved) { await navigator.clipboard.writeText(result.improved); setCopied(true); toast.success(t("copied")); setTimeout(() => setCopied(false), 2000); } }; return ( <div className="h-full flex overflow-hidden"> {/* History Sidebar */} <div className="w-64 h-full flex flex-col border-r bg-muted/20 shrink-0"> <div className="p-3 border-b"> <h3 className="text-sm font-medium">{t("history")}</h3> <p className="text-xs text-muted-foreground flex items-center gap-1 mt-1"> <HardDrive className="h-3 w-3" /> {t("storedOnDevice")} </p> </div> <ScrollArea className="flex-1"> <div className="p-2 space-y-1"> {history.length === 0 ? ( <p className="text-xs text-muted-foreground text-center py-4"> {t("noHistory")} </p> ) : ( history.map((item) => ( <div key={item.id} className={`group relative p-2 rounded-md cursor-pointer text-xs hover:bg-muted transition-colors overflow-hidden ${ selectedId === item.id ? "bg-muted" : "" }`} onClick={() => loadFromHistory(item)} > <p className="font-medium truncate pr-6">{item.input.slice(0, 30)}</p> <p className="text-muted-foreground truncate mt-0.5"> → {item.output.slice(0, 25)} </p> <Button variant="ghost" size="icon" className="absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => { e.stopPropagation(); deleteFromHistory(item.id); }} > <Trash2 className="h-3 w-3" /> </Button> </div> )) )} </div> </ScrollArea> </div> {/* Left Panel - Input */} <div className="flex-1 h-full flex flex-col border-r min-w-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("inputPrompt")}</span> <div className="flex items-center gap-2"> <div className="flex items-center gap-1"> <label className="text-xs text-muted-foreground">{t("outputType")}:</label> <Select value={outputType} onValueChange={(v) => setOutputType(v as OutputType)}> <SelectTrigger className="!h-6 w-[72px] text-xs !py-0 px-1.5"> <SelectValue /> </SelectTrigger> <SelectContent> {OUTPUT_TYPES.map((type) => ( <SelectItem key={type.value} value={type.value} className="text-xs"> {type.label} </SelectItem> ))} </SelectContent> </Select> </div> <div className="flex items-center gap-1"> <label className="text-xs text-muted-foreground">{t("outputFormat")}:</label> <Select value={outputFormat} onValueChange={(v) => setOutputFormat(v as OutputFormat)}> <SelectTrigger className="!h-6 w-[64px] text-xs !py-0 px-1.5"> <SelectValue /> </SelectTrigger> <SelectContent> {OUTPUT_FORMATS.map((format) => ( <SelectItem key={format.value} value={format.value} className="text-xs"> {format.label} </SelectItem> ))} </SelectContent> </Select> </div> </div> </div> <div className="flex-1 flex flex-col min-h-0"> <Textarea placeholder={t("inputPlaceholder")} value={prompt} onChange={(e) => setPrompt(e.target.value)} className="flex-1 resize-none font-mono text-sm min-h-0 rounded-none border-0" /> </div> <div className="h-10 px-4 border-t bg-background flex items-center justify-between shrink-0"> <div className="text-xs text-muted-foreground"> {prompt.length.toLocaleString()} / 10,000 </div> <Button onClick={handleEnhance} disabled={isLoading || !prompt.trim()} size="sm" className="h-7 gap-1.5" > {isLoading ? ( <> <Loader2 className="h-3.5 w-3.5 animate-spin" /> {t("enhancing")} </> ) : ( <> <Sparkles className="h-3.5 w-3.5" /> {t("enhance")} </> )} </Button> </div> </div> {/* Right Panel - Output */} <div className="flex-1 h-full flex flex-col min-w-0 overflow-hidden"> <div className="h-10 px-4 border-b bg-muted/30 flex items-center justify-between shrink-0"> <span className="text-sm font-medium text-muted-foreground">{t("enhancedPrompt")}</span> {result && ( <div className="flex items-center gap-2"> <span className="text-xs text-muted-foreground"> {result.model} </span> <Button variant="ghost" size="icon" onClick={handleCopy} className="h-6 w-6" > {copied ? ( <Check className="h-3 w-3" /> ) : ( <Copy className="h-3 w-3" /> )} </Button> <RunPromptButton content={result.improved} size="sm" variant="default" className="h-7 bg-green-600 hover:bg-green-700 text-white" /> </div> )} </div> <div className="flex-1 min-h-0 overflow-hidden"> {result ? ( <Editor height="100%" language={getEditorLanguage()} value={result.improved} theme={theme === "dark" ? "vs-dark" : "light"} options={{ readOnly: true, minimap: { enabled: false }, fontSize: 13, lineNumbers: "on", wordWrap: "on", scrollBeyondLastLine: false, automaticLayout: true, padding: { top: 8, bottom: 8 }, folding: true, renderLineHighlight: "none", }} /> ) : ( <div className="h-full flex items-center justify-center text-muted-foreground text-sm"> {t("enhanceToSeeResult")} </div> )} </div> {result && result.inspirations.length > 0 && ( <div className="p-4 pt-2 space-y-2 border-t"> <p className="text-xs font-medium text-muted-foreground"> {t("inspiredBy")}: </p> <div className="flex flex-wrap gap-1.5"> {result.inspirations.map((ins) => { const promptPath = `/prompts/${ins.id}${ins.slug ? `_${ins.slug}` : ""}`; return ( <a key={ins.id} href={promptPath} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2 py-0.5 text-xs hover:bg-primary/20 transition-colors" > {ins.title} <span className="text-muted-foreground"> {ins.similarity}% </span> </a> ); })} </div> </div> )} </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/seo/structured-data.tsx
src/components/seo/structured-data.tsx
import { getConfig } from "@/lib/config"; interface StructuredDataProps { type: "website" | "organization" | "breadcrumb" | "prompt" | "softwareApp" | "itemList"; data?: { breadcrumbs?: Array<{ name: string; url: string }>; prompt?: { id: string; name: string; description: string; content: string; author?: string; authorUrl?: string; datePublished?: string; dateModified?: string; category?: string; tags?: string[]; voteCount?: number; }; items?: Array<{ name: string; url: string; description?: string; image?: string; }>; }; } export async function StructuredData({ type, data }: StructuredDataProps) { const config = await getConfig(); const baseUrl = process.env.NEXTAUTH_URL || "https://prompts.chat"; const schemas: Record<string, object | null> = { organization: { "@context": "https://schema.org", "@type": "Organization", name: config.branding.name, url: baseUrl, logo: { "@type": "ImageObject", url: `${baseUrl}${config.branding.logo}`, width: 512, height: 512, }, description: config.branding.description, sameAs: [ "https://github.com/f/awesome-chatgpt-prompts", "https://x.com/promptschat", "https://x.com/fkadev", ], }, website: { "@context": "https://schema.org", "@type": "WebSite", name: config.branding.name, url: baseUrl, description: config.branding.description, potentialAction: { "@type": "SearchAction", target: { "@type": "EntryPoint", urlTemplate: `${baseUrl}/prompts?q={search_term_string}`, }, "query-input": "required name=search_term_string", }, publisher: { "@type": "Organization", name: config.branding.name, logo: { "@type": "ImageObject", url: `${baseUrl}${config.branding.logo}`, }, }, }, breadcrumb: data?.breadcrumbs && data.breadcrumbs.length > 0 ? { "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: data.breadcrumbs.map((item, index) => ({ "@type": "ListItem", position: index + 1, name: item.name, item: item.url.startsWith("http") ? item.url : `${baseUrl}${item.url}`, })), } : null, prompt: data?.prompt ? { "@context": "https://schema.org", "@type": "HowTo", "@id": `${baseUrl}/prompts/${data.prompt.id}`, name: data.prompt.name, description: data.prompt.description || `AI prompt: ${data.prompt.name}`, step: [ { "@type": "HowToStep", name: "Copy the prompt", text: data.prompt.content.substring(0, 500) + (data.prompt.content.length > 500 ? "..." : ""), position: 1, }, { "@type": "HowToStep", name: "Paste into your AI assistant", text: "Open ChatGPT, Claude, Gemini, or your preferred AI assistant and paste the prompt.", position: 2, }, { "@type": "HowToStep", name: "Get your response", text: "The AI will respond according to the prompt instructions.", position: 3, }, ], tool: [ { "@type": "HowToTool", name: "AI Assistant (ChatGPT, Claude, Gemini, etc.)", }, ], totalTime: "PT2M", author: data.prompt.author ? { "@type": "Person", name: data.prompt.author, url: data.prompt.authorUrl, } : undefined, datePublished: data.prompt.datePublished, dateModified: data.prompt.dateModified, publisher: { "@type": "Organization", name: config.branding.name, logo: { "@type": "ImageObject", url: `${baseUrl}${config.branding.logo}`, }, }, mainEntityOfPage: { "@type": "WebPage", "@id": `${baseUrl}/prompts/${data.prompt.id}`, }, aggregateRating: data.prompt.voteCount && data.prompt.voteCount > 0 ? { "@type": "AggregateRating", ratingValue: 5, bestRating: 5, ratingCount: data.prompt.voteCount, } : undefined, keywords: data.prompt.tags?.join(", ") || data.prompt.category, } : null, softwareApp: { "@context": "https://schema.org", "@type": "WebApplication", name: config.branding.name, description: config.branding.description, url: baseUrl, applicationCategory: "UtilitiesApplication", browserRequirements: "Requires JavaScript. Requires HTML5.", softwareVersion: "1.0", offers: { "@type": "Offer", price: "0", priceCurrency: "USD", availability: "https://schema.org/InStock", }, featureList: [ "AI prompt library", "Prompt sharing and discovery", "Community contributions", "Version history", "Categories and tags", ], screenshot: `${baseUrl}/og.png`, }, itemList: data?.items ? { "@context": "https://schema.org", "@type": "ItemList", itemListElement: data.items.map((item, index) => ({ "@type": "ListItem", position: index + 1, item: { "@type": "HowTo", name: item.name, description: item.description, url: item.url.startsWith("http") ? item.url : `${baseUrl}${item.url}`, }, })), } : null, }; const schema = schemas[type]; if (!schema) return null; return ( <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} /> ); } export async function WebsiteStructuredData() { return ( <> <StructuredData type="organization" /> <StructuredData type="website" /> <StructuredData type="softwareApp" /> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/api/improve-prompt-demo.tsx
src/components/api/improve-prompt-demo.tsx
"use client"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Loader2, Sparkles, Copy, Check } from "lucide-react"; import { toast } from "sonner"; const OUTPUT_TYPES = [ { value: "text", label: "Text" }, { value: "image", label: "Image" }, { value: "video", label: "Video" }, { value: "sound", label: "Sound" }, ] as const; const OUTPUT_FORMATS = [ { value: "text", label: "Text" }, { value: "structured_json", label: "JSON" }, { value: "structured_yaml", label: "YAML" }, ] as const; type OutputType = (typeof OUTPUT_TYPES)[number]["value"]; type OutputFormat = (typeof OUTPUT_FORMATS)[number]["value"]; interface ImproveResponse { original: string; improved: string; outputType: OutputType; outputFormat: OutputFormat; inspirations: Array<{ title: string; similarity: number }>; model: string; } export function ImprovePromptDemo() { const [prompt, setPrompt] = useState(""); const [outputType, setOutputType] = useState<OutputType>("text"); const [outputFormat, setOutputFormat] = useState<OutputFormat>("text"); const [isLoading, setIsLoading] = useState(false); const [result, setResult] = useState<ImproveResponse | null>(null); const [copied, setCopied] = useState(false); const handleImprove = async () => { if (!prompt.trim()) { toast.error("Please enter a prompt to improve"); return; } setIsLoading(true); setResult(null); try { const response = await fetch("/api/improve-prompt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: prompt.trim(), outputType, outputFormat }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "Failed to improve prompt"); } setResult(data); toast.success("Prompt improved successfully!"); } catch (error) { toast.error( error instanceof Error ? error.message : "Failed to improve prompt" ); } finally { setIsLoading(false); } }; const handleCopy = async () => { if (result?.improved) { await navigator.clipboard.writeText(result.improved); setCopied(true); toast.success("Copied to clipboard"); setTimeout(() => setCopied(false), 2000); } }; return ( <div className="space-y-6"> <div className="space-y-4"> <div className="flex flex-col gap-4 sm:flex-row sm:items-end"> <div className="flex-1 space-y-2"> <label className="text-sm font-medium">Your Prompt</label> <Textarea placeholder="Enter a prompt to improve... e.g., 'write a blog post about AI'" value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={4} className="resize-none" /> </div> </div> <div className="flex flex-col gap-4 sm:flex-row sm:items-center"> <div className="space-y-2"> <label className="text-sm font-medium">Output Type</label> <Select value={outputType} onValueChange={(v) => setOutputType(v as OutputType)}> <SelectTrigger className="w-[140px]"> <SelectValue /> </SelectTrigger> <SelectContent> {OUTPUT_TYPES.map((t) => ( <SelectItem key={t.value} value={t.value}> {t.label} </SelectItem> ))} </SelectContent> </Select> </div> <div className="space-y-2"> <label className="text-sm font-medium">Output Format</label> <Select value={outputFormat} onValueChange={(v) => setOutputFormat(v as OutputFormat)}> <SelectTrigger className="w-[140px]"> <SelectValue /> </SelectTrigger> <SelectContent> {OUTPUT_FORMATS.map((f) => ( <SelectItem key={f.value} value={f.value}> {f.label} </SelectItem> ))} </SelectContent> </Select> </div> <Button onClick={handleImprove} disabled={isLoading || !prompt.trim()} className="gap-2 sm:mt-6" > {isLoading ? ( <> <Loader2 className="h-4 w-4 animate-spin" /> Improving... </> ) : ( <> <Sparkles className="h-4 w-4" /> Improve Prompt </> )} </Button> </div> </div> {result && ( <div className="space-y-4 rounded-lg border bg-muted/30 p-4"> <div className="flex items-center justify-between"> <h3 className="font-medium">Improved Prompt</h3> <div className="flex items-center gap-2"> <span className="text-xs text-muted-foreground"> Model: {result.model} </span> <Button variant="ghost" size="sm" onClick={handleCopy} className="h-8 gap-1" > {copied ? ( <Check className="h-3.5 w-3.5" /> ) : ( <Copy className="h-3.5 w-3.5" /> )} Copy </Button> </div> </div> <div className="rounded-md bg-background p-4"> <pre className="whitespace-pre-wrap text-sm">{result.improved}</pre> </div> {result.inspirations.length > 0 && ( <div className="space-y-2"> <h4 className="text-sm font-medium text-muted-foreground"> Inspired by similar prompts: </h4> <div className="flex flex-wrap gap-2"> {result.inspirations.map((ins, i) => ( <span key={i} className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2.5 py-0.5 text-xs" > {ins.title} <span className="text-muted-foreground"> ({ins.similarity}%) </span> </span> ))} </div> </div> )} </div> )} <div className="rounded-lg bg-muted p-4 font-mono text-sm overflow-x-auto"> <p className="text-muted-foreground mb-2"># API Request</p> <pre>{`curl -X POST ${typeof window !== "undefined" ? window.location.origin : ""}/api/improve-prompt \\ -H "Content-Type: application/json" \\ -d '{ "prompt": "${prompt.slice(0, 50).replace(/"/g, '\\"')}${prompt.length > 50 ? "..." : ""}", "outputType": "${outputType}", "outputFormat": "${outputFormat}" }'`}</pre> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/providers/theme-styles.tsx
src/components/providers/theme-styles.tsx
"use client"; // ThemeStyles is now a no-op since styles are applied server-side in layout.tsx // This component is kept for potential future dynamic theme switching interface ThemeStylesProps { radius: "none" | "sm" | "md" | "lg"; variant: "flat" | "default" | "brutal"; density: "compact" | "default" | "comfortable"; primaryColor: string; } export function ThemeStyles(_props: ThemeStylesProps) { // Styles are now applied server-side to prevent flash // This component can be extended for dynamic theme switching if needed return null; }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/providers/index.tsx
src/components/providers/index.tsx
"use client"; import { ThemeProvider } from "next-themes"; import { SessionProvider } from "next-auth/react"; import { Toaster } from "@/components/ui/sonner"; import { NextIntlClientProvider, AbstractIntlMessages } from "next-intl"; import { ThemeStyles } from "./theme-styles"; import { BrandingProvider } from "./branding-provider"; interface ThemeConfig { radius: "none" | "sm" | "md" | "lg"; variant: "flat" | "default" | "brutal"; density: "compact" | "default" | "comfortable"; colors: { primary: string; }; } interface BrandingConfig { name: string; logo: string; description: string; useCloneBranding?: boolean; } interface ProvidersProps { children: React.ReactNode; locale: string; messages: AbstractIntlMessages; theme: ThemeConfig; branding: BrandingConfig; } export function Providers({ children, locale, messages, theme, branding }: ProvidersProps) { return ( <SessionProvider> <NextIntlClientProvider locale={locale} messages={messages}> <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange > <ThemeStyles radius={theme.radius} variant={theme.variant} density={theme.density} primaryColor={theme.colors.primary} /> <BrandingProvider branding={branding}> {children} </BrandingProvider> <Toaster position="bottom-right" /> </ThemeProvider> </NextIntlClientProvider> </SessionProvider> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/providers/locale-detector.tsx
src/components/providers/locale-detector.tsx
"use client"; import { useEffect } from "react"; import { useLocale } from "next-intl"; import { LOCALE_COOKIE } from "@/lib/i18n/config"; /** * Client component that saves the auto-detected locale to a cookie on first visit. * This ensures the detected language is remembered without requiring user interaction. */ export function LocaleDetector() { const locale = useLocale(); useEffect(() => { // Check if locale cookie already exists const hasLocaleCookie = document.cookie .split(";") .some((c) => c.trim().startsWith(`${LOCALE_COOKIE}=`)); // If no cookie exists, save the current (auto-detected) locale if (!hasLocaleCookie && locale) { document.cookie = `${LOCALE_COOKIE}=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`; } }, [locale]); return null; }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/providers/branding-provider.tsx
src/components/providers/branding-provider.tsx
"use client"; import { createContext, useContext, type ReactNode } from "react"; interface BrandingContextValue { name: string; logo: string; logoDark?: string; description: string; appStoreUrl?: string; chromeExtensionUrl?: string; useCloneBranding?: boolean; } const BrandingContext = createContext<BrandingContextValue | null>(null); interface BrandingProviderProps { children: ReactNode; branding: BrandingContextValue; } export function BrandingProvider({ children, branding }: BrandingProviderProps) { return ( <BrandingContext.Provider value={branding}> {children} </BrandingContext.Provider> ); } export function useBranding(): BrandingContextValue { const context = useContext(BrandingContext); if (!context) { throw new Error("useBranding must be used within a BrandingProvider"); } return context; }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/download-prompt-dropdown.tsx
src/components/prompts/download-prompt-dropdown.tsx
"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { Download, FileText, FileCode, Check, Link } from "lucide-react"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { toast } from "sonner"; interface DownloadPromptDropdownProps { promptId: string; promptSlug?: string; promptType?: string; } export function DownloadPromptDropdown({ promptId, promptSlug, promptType }: DownloadPromptDropdownProps) { const t = useTranslations("prompts"); const [copiedFormat, setCopiedFormat] = useState<"md" | "yml" | null>(null); const isSkill = promptType === "SKILL"; const getFileName = (format: "md" | "yml") => { const base = promptSlug ? `${promptId}_${promptSlug}` : promptId; const filePrefix = isSkill ? "SKILL" : "prompt"; return `${base}.${filePrefix}.${format}`; }; const getFileUrl = (format: "md" | "yml") => { if (typeof window === "undefined") return ""; const base = promptSlug ? `${promptId}_${promptSlug}` : promptId; const filePrefix = isSkill ? "SKILL" : "prompt"; return `${window.location.origin}/prompts/${base}.${filePrefix}.${format}`; }; const handleDownload = async (format: "md" | "yml") => { const url = getFileUrl(format); try { const response = await fetch(url); if (!response.ok) throw new Error("Failed to fetch"); const content = await response.text(); const blob = new Blob([content], { type: "text/plain;charset=utf-8" }); const downloadUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = downloadUrl; a.download = getFileName(format); document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(downloadUrl); toast.success(t("downloadStarted")); } catch { toast.error(t("downloadFailed")); } }; const handleCopyUrl = async (format: "md" | "yml") => { const url = getFileUrl(format); try { await navigator.clipboard.writeText(url); setCopiedFormat(format); toast.success(t("urlCopied")); setTimeout(() => setCopiedFormat(null), 2000); } catch { toast.error(t("failedToCopyUrl")); } }; // For SKILL type, show a simple button instead of dropdown if (isSkill) { return ( <Button variant="ghost" size="sm" onClick={() => handleDownload("md")}> <Download className="h-4 w-4 mr-1" /> {t("downloadSkillMd")} </Button> ); } return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="sm"> <Download className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-48"> <DropdownMenuItem onClick={() => handleDownload("md")}> <FileText className="h-4 w-4 mr-2" /> {t("downloadMarkdown")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleDownload("yml")}> <FileCode className="h-4 w-4 mr-2" /> {t("downloadYaml")} </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem onClick={() => handleCopyUrl("md")}> {copiedFormat === "md" ? ( <Check className="h-4 w-4 mr-2 text-green-500" /> ) : ( <Link className="h-4 w-4 mr-2" /> )} {t("copyMarkdownUrl")} </DropdownMenuItem> <DropdownMenuItem onClick={() => handleCopyUrl("yml")}> {copiedFormat === "yml" ? ( <Check className="h-4 w-4 mr-2 text-green-500" /> ) : ( <Link className="h-4 w-4 mr-2" /> )} {t("copyYamlUrl")} </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/prompt-list.tsx
src/components/prompts/prompt-list.tsx
"use client"; import Link from "next/link"; import { useTranslations } from "next-intl"; import { SearchX } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Masonry } from "@/components/ui/masonry"; import { PromptCard, type PromptCardProps } from "@/components/prompts/prompt-card"; export interface PromptListProps { prompts: PromptCardProps["prompt"][]; currentPage: number; totalPages: number; pinnedIds?: Set<string>; showPinButton?: boolean; } export function PromptList({ prompts, currentPage, totalPages, pinnedIds, showPinButton = false }: PromptListProps) { const t = useTranslations("prompts"); if (prompts.length === 0) { return ( <div className="flex flex-col items-center justify-center py-16 text-center"> <div className="rounded-full bg-muted p-4 mb-4"> <SearchX className="h-8 w-8 text-muted-foreground" /> </div> <h3 className="text-lg font-medium mb-1">{t("noPrompts")}</h3> <p className="text-sm text-muted-foreground max-w-sm"> {t("noPromptsDescription")} </p> </div> ); } return ( <div className="space-y-4"> <Masonry columnCount={{ default: 1, md: 2, lg: 3 }} gap={16}> {prompts.map((prompt) => ( <PromptCard key={prompt.id} prompt={prompt} showPinButton={showPinButton} isPinned={pinnedIds?.has(prompt.id) ?? false} /> ))} </Masonry> {/* Pagination */} {totalPages > 1 && ( <div className="flex items-center justify-center gap-2 pt-4"> <Button variant="outline" size="sm" className="h-7 text-xs" disabled={currentPage <= 1} asChild={currentPage > 1}> {currentPage > 1 ? <Link href={`?page=${currentPage - 1}`} prefetch={false}>Previous</Link> : <span>Previous</span>} </Button> <span className="text-xs text-muted-foreground">{currentPage} / {totalPages}</span> <Button variant="outline" size="sm" className="h-7 text-xs" disabled={currentPage >= totalPages} asChild={currentPage < totalPages}> {currentPage < totalPages ? <Link href={`?page=${currentPage + 1}`} prefetch={false}>Next</Link> : <span>Next</span>} </Button> </div> )} </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/prompt-flow-section.tsx
src/components/prompts/prompt-flow-section.tsx
"use client"; import { useState } from "react"; import { PromptConnections } from "./prompt-connections"; import { ReportPromptDialog } from "./report-prompt-dialog"; interface PromptFlowSectionProps { promptId: string; promptTitle: string; canEdit: boolean; isOwner: boolean; isLoggedIn: boolean; } export function PromptFlowSection({ promptId, promptTitle, canEdit, isOwner, isLoggedIn, }: PromptFlowSectionProps) { const [expanded, setExpanded] = useState(false); return ( <div className="pt-2"> {/* Button row: [add next step] - spacer - [report] */} <div className="flex items-center justify-end gap-2"> <PromptConnections promptId={promptId} promptTitle={promptTitle} canEdit={canEdit} buttonOnly expanded={expanded} onExpandChange={setExpanded} /> <div className="flex-1" /> {!isOwner && ( <ReportPromptDialog promptId={promptId} isLoggedIn={isLoggedIn} /> )} </div> {/* Prompt Flow section below */} <PromptConnections promptId={promptId} promptTitle={promptTitle} canEdit={canEdit} sectionOnly expanded={expanded} onExpandChange={setExpanded} /> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/change-request-actions.tsx
src/components/prompts/change-request-actions.tsx
"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { Check, X, Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { toast } from "sonner"; import { analyticsPrompt } from "@/lib/analytics"; interface ChangeRequestActionsProps { changeRequestId: string; promptId: string; } export function ChangeRequestActions({ changeRequestId, promptId }: ChangeRequestActionsProps) { const router = useRouter(); const t = useTranslations("changeRequests"); const tCommon = useTranslations("common"); const [isLoading, setIsLoading] = useState(false); const [action, setAction] = useState<"approve" | "reject" | null>(null); const [reviewNote, setReviewNote] = useState(""); const handleAction = async (selectedAction: "approve" | "reject") => { setIsLoading(true); setAction(selectedAction); try { const response = await fetch(`/api/prompts/${promptId}/changes/${changeRequestId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: selectedAction === "approve" ? "APPROVED" : "REJECTED", reviewNote: reviewNote || undefined, }), }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || "Failed to update change request"); } analyticsPrompt.changeRequest(promptId, selectedAction === "approve" ? "approve" : "dismiss"); toast.success(selectedAction === "approve" ? t("approvedSuccess") : t("rejectedSuccess")); router.refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : tCommon("somethingWentWrong")); } finally { setIsLoading(false); setAction(null); } }; return ( <div className="space-y-3"> <p className="text-sm font-medium">{t("reviewActions")}</p> <Textarea id="reviewNote" value={reviewNote} onChange={(e) => setReviewNote(e.target.value)} placeholder={t("reviewNotePlaceholder")} className="min-h-[60px] text-sm" /> <div className="flex gap-2"> <Button onClick={() => handleAction("approve")} disabled={isLoading} size="sm" className="flex-1 bg-green-600 hover:bg-green-700" > {isLoading && action === "approve" ? ( <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> ) : ( <Check className="h-4 w-4 mr-1.5" /> )} {t("approve")} </Button> <Button onClick={() => handleAction("reject")} disabled={isLoading} variant="destructive" size="sm" className="flex-1" > {isLoading && action === "reject" ? ( <Loader2 className="h-4 w-4 mr-1.5 animate-spin" /> ) : ( <X className="h-4 w-4 mr-1.5" /> )} {t("reject")} </Button> </div> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/run-prompt-button.tsx
src/components/prompts/run-prompt-button.tsx
"use client"; import { useState, useCallback } from "react"; import { Play, ExternalLink, Zap, Clipboard, Heart } from "lucide-react"; import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger, } from "@/components/ui/sheet"; import { analyticsPrompt } from "@/lib/analytics"; import { useIsMobile } from "@/hooks/use-mobile"; import { useBranding } from "@/components/providers/branding-provider"; interface Platform { id: string; name: string; baseUrl: string; supportsQuerystring?: boolean; isDeeplink?: boolean; subOptions?: { name: string; baseUrl: string }[]; sponsor?: boolean; } // Image generation platforms (Mitte.ai) const imagePlatforms: Platform[] = [ { id: "mitte-image", name: "Mitte.ai", baseUrl: "https://mitte.ai", sponsor: true, subOptions: [ { name: "Nano Banana", baseUrl: "https://mitte.ai?model=nano-banana" }, { name: "Nano Banana Pro", baseUrl: "https://mitte.ai?model=nano-banana-pro" }, { name: "Flux 2 Flex", baseUrl: "https://mitte.ai?model=flux-2-flex" }, { name: "Flux 2", baseUrl: "https://mitte.ai?model=flux-2" }, ], }, ]; // Video generation platforms (Mitte.ai) const videoPlatforms: Platform[] = [ { id: "mitte-video", name: "Mitte.ai", baseUrl: "https://mitte.ai", sponsor: true, subOptions: [ { name: "Veo 3.1", baseUrl: "https://mitte.ai?model=veo-31" }, { name: "Kling 2.6", baseUrl: "https://mitte.ai?model=kling-26" }, { name: "Sora 2", baseUrl: "https://mitte.ai?model=sora-2" }, ], }, ]; // Code platforms (IDEs + code generation tools) const codePlatforms: Platform[] = [ { id: "windsurf", name: "Windsurf", baseUrl: "windsurf://", isDeeplink: true, supportsQuerystring: false, sponsor: true }, { id: "vscode", name: "VS Code", baseUrl: "vscode://", isDeeplink: true, supportsQuerystring: false }, { id: "vscode-insiders", name: "VS Code Insiders", baseUrl: "vscode-insiders://", isDeeplink: true, supportsQuerystring: false }, { id: "cursor", name: "Cursor", baseUrl: "cursor://anysphere.cursor-deeplink/prompt", isDeeplink: true }, { id: "goose", name: "Goose", baseUrl: "goose://recipe", isDeeplink: true }, { id: "github-copilot", name: "GitHub Copilot", baseUrl: "https://github.com/copilot", subOptions: [ { name: "Copilot Chat", baseUrl: "https://github.com/copilot" }, { name: "Copilot Agents", baseUrl: "https://github.com/copilot/agents" }, ], }, { id: "bolt", name: "Bolt", baseUrl: "https://bolt.new" }, { id: "lovable", name: "Lovable", baseUrl: "https://lovable.dev" }, { id: "v0", name: "v0", baseUrl: "https://v0.dev/chat" }, { id: "ai2sql", name: "AI2SQL", baseUrl: "https://builder.ai2sql.io/dashboard/builder-all-lp?tab=generate" }, ]; // Chat platforms (AI assistants) const chatPlatforms: Platform[] = [ { id: "chatgpt", name: "ChatGPT", baseUrl: "https://chatgpt.com" }, { id: "claude", name: "Claude", baseUrl: "https://claude.ai/new" }, { id: "copilot", name: "Microsoft Copilot", baseUrl: "https://copilot.microsoft.com", supportsQuerystring: false }, { id: "deepseek", name: "DeepSeek", baseUrl: "https://chat.deepseek.com", supportsQuerystring: false }, { id: "fal", name: "fal.ai Sandbox", baseUrl: "https://fal.ai/sandbox" }, { id: "gemini", name: "Gemini", baseUrl: "https://gemini.google.com/app", supportsQuerystring: false }, { id: "goose", name: "Goose", baseUrl: "goose://recipe", isDeeplink: true }, { id: "grok", name: "Grok", baseUrl: "https://grok.com/chat?reasoningMode=none", subOptions: [ { name: "Grok", baseUrl: "https://grok.com/chat?reasoningMode=none" }, { name: "Grok Deep Search", baseUrl: "https://grok.com/chat?reasoningMode=deepsearch" }, { name: "Grok Think", baseUrl: "https://grok.com/chat?reasoningMode=think" }, ], }, { id: "huggingface", name: "HuggingChat", baseUrl: "https://huggingface.co/chat" }, { id: "llama", name: "Meta AI", baseUrl: "https://www.meta.ai" }, { id: "manus", name: "Manus", baseUrl: "https://manus.im/app" }, { id: "mistral", name: "Le Chat", baseUrl: "https://chat.mistral.ai/chat" }, { id: "perplexity", name: "Perplexity", baseUrl: "https://www.perplexity.ai" }, { id: "phind", name: "Phind", baseUrl: "https://www.phind.com" }, { id: "pi", name: "Pi", baseUrl: "https://pi.ai", supportsQuerystring: false }, { id: "poe", name: "Poe", baseUrl: "https://poe.com", supportsQuerystring: false }, { id: "you", name: "You.com", baseUrl: "https://you.com" }, ]; function buildUrl(platformId: string, baseUrl: string, promptText: string, promptTitle?: string, promptDescription?: string): string { const encoded = encodeURIComponent(promptText); switch (platformId) { // IDE deeplinks case "cursor": return `${baseUrl}?text=${encoded}`; case "goose": { const config = JSON.stringify({ version: "1.0.0", title: promptTitle || "Prompt", description: promptDescription || "", instructions: "This is a prompt imported from [**prompts.chat**](https://prompts.chat). Follow the instructions below to complete the task.", prompt: promptText, activities: [ "message:This prompt was imported from [**prompts.chat**](https://prompts.chat). Follow the instructions below to complete the task.", "Do it now", "Learn more about the instructions" ] }); const base64Config = btoa(config); return `${baseUrl}?config=${base64Config}`; } // Web platforms case "ai2sql": return `${baseUrl}&prompt=${encoded}`; case "bolt": return `${baseUrl}?prompt=${encoded}`; case "chatgpt": return `${baseUrl}/?q=${encoded}`; case "claude": return `${baseUrl}?q=${encoded}`; case "copilot": return `${baseUrl}/?q=${encoded}`; case "deepseek": return `${baseUrl}/?q=${encoded}`; case "github-copilot": return `${baseUrl}?prompt=${encoded}`; case "grok": return `${baseUrl}&q=${encoded}`; case "fal": return `${baseUrl}?prompt=${encoded}`; case "huggingface": return `${baseUrl}/?prompt=${encoded}`; case "lovable": return `${baseUrl}/?autosubmit=true#prompt=${encoded}`; case "mistral": return `${baseUrl}?q=${encoded}`; case "perplexity": return `${baseUrl}/search?q=${encoded}`; case "phind": return `${baseUrl}/search?q=${encoded}`; case "poe": return `${baseUrl}/?q=${encoded}`; case "v0": return `${baseUrl}?q=${encoded}`; case "you": return `${baseUrl}/search?q=${encoded}`; case "mitte-image": case "mitte-video": return `${baseUrl}&prompt=${encoded}`; default: return `${baseUrl}?q=${encoded}`; } } interface UnfilledVariable { name: string; defaultValue: string; } interface RunPromptButtonProps { content: string; title?: string; description?: string; variant?: "default" | "ghost" | "outline"; size?: "default" | "sm" | "icon"; className?: string; unfilledVariables?: UnfilledVariable[]; onVariablesFilled?: (values: Record<string, string>) => void; getContentWithVariables?: (values: Record<string, string>) => string; promptId?: string; categoryName?: string; parentCategoryName?: string; emphasized?: boolean; promptType?: "TEXT" | "IMAGE" | "VIDEO" | "AUDIO" | "STRUCTURED" | "SKILL"; } // Check if category or parent category suggests code-related content function isCodeCategory(name?: string): boolean { if (!name) return false; const lower = name.toLowerCase(); return lower.includes("code") || lower.includes("coding") || lower.includes("vibe"); } function getDefaultTab(categoryName?: string, parentCategoryName?: string): "chat" | "code" { if (isCodeCategory(categoryName) || isCodeCategory(parentCategoryName)) { return "code"; } return "chat"; } export function RunPromptButton({ content, title, description, variant = "outline", size = "sm", className, unfilledVariables = [], onVariablesFilled, getContentWithVariables, promptId, categoryName, parentCategoryName, emphasized = false, promptType = "TEXT" }: RunPromptButtonProps) { const t = useTranslations("prompts"); const tCommon = useTranslations("common"); const isMobile = useIsMobile(); const { useCloneBranding } = useBranding(); const [dialogOpen, setDialogOpen] = useState(false); const [variableDialogOpen, setVariableDialogOpen] = useState(false); const [sheetOpen, setSheetOpen] = useState(false); const [activeTab, setActiveTab] = useState<"chat" | "code">(() => getDefaultTab(categoryName, parentCategoryName)); const [pendingPlatform, setPendingPlatform] = useState<{ id: string; name: string; baseUrl: string; supportsQuerystring?: boolean } | null>(null); const [variableValues, setVariableValues] = useState<Record<string, string>>({}); // Initialize variable values when dialog opens const openVariableDialog = useCallback((platform: Platform, baseUrl: string) => { const initial: Record<string, string> = {}; for (const v of unfilledVariables) { initial[v.name] = v.defaultValue; } setVariableValues(initial); setPendingPlatform({ id: platform.id, name: platform.name, baseUrl, supportsQuerystring: platform.supportsQuerystring }); setVariableDialogOpen(true); }, [unfilledVariables]); const handleVariableSubmit = useCallback(() => { if (onVariablesFilled) { onVariablesFilled(variableValues); } setVariableDialogOpen(false); if (pendingPlatform) { const finalContent = getContentWithVariables ? getContentWithVariables(variableValues) : content; if (pendingPlatform.supportsQuerystring === false) { navigator.clipboard.writeText(finalContent); setDialogOpen(true); } else { const url = buildUrl(pendingPlatform.id, pendingPlatform.baseUrl, finalContent, title, description); // Only open in new tab for http/https URLs if (url.startsWith("http://") || url.startsWith("https://")) { window.open(url, "_blank"); } else { window.location.href = url; } setPendingPlatform(null); } analyticsPrompt.run(promptId, pendingPlatform.name); } }, [variableValues, onVariablesFilled, pendingPlatform, getContentWithVariables, content, promptId]); const handleRun = (platform: Platform, baseUrl: string) => { // Check if there are unfilled variables (empty values) const hasUnfilled = unfilledVariables.some(v => !v.defaultValue || v.defaultValue.trim() === ""); if (hasUnfilled) { // Show variable fill dialog first (for both query string and copy flows) openVariableDialog(platform, baseUrl); return; } if (platform.supportsQuerystring === false) { navigator.clipboard.writeText(content); setPendingPlatform({ id: platform.id, name: platform.name, baseUrl, supportsQuerystring: platform.supportsQuerystring }); setDialogOpen(true); analyticsPrompt.run(promptId, platform.name); } else { const url = buildUrl(platform.id, baseUrl, content, title, description); // Only open in new tab for http/https URLs if (url.startsWith("http://") || url.startsWith("https://")) { window.open(url, "_blank"); } else { window.location.href = url; } analyticsPrompt.run(promptId, platform.name); } }; const handleOpenPlatform = () => { if (pendingPlatform) { window.open(pendingPlatform.baseUrl, "_blank"); setDialogOpen(false); setPendingPlatform(null); } }; const handleRunAndClose = (platform: Platform, baseUrl: string) => { setSheetOpen(false); handleRun(platform, baseUrl); }; // Get media platforms based on prompt type (only if not using clone branding) const mediaPlatforms = useCloneBranding ? [] : (promptType === "IMAGE" ? imagePlatforms : promptType === "VIDEO" ? videoPlatforms : imagePlatforms); const isMediaPrompt = promptType === "IMAGE" || promptType === "VIDEO"; // Get platforms based on active tab, merge with media platforms // Sponsors go to top, then rest sorted alphabetically const basePlatforms = activeTab === "code" ? codePlatforms : chatPlatforms; const sortedBasePlatforms = [...basePlatforms].sort((a, b) => { // Sponsors first (unless useCloneBranding is true) if (!useCloneBranding) { if (a.sponsor && !b.sponsor) return -1; if (!a.sponsor && b.sponsor) return 1; } return a.name.localeCompare(b.name); }); const activePlatforms = isMediaPrompt ? [...mediaPlatforms, ...sortedBasePlatforms] : [...sortedBasePlatforms, ...mediaPlatforms].sort((a, b) => { if (!useCloneBranding) { if (a.sponsor && !b.sponsor) return -1; if (!a.sponsor && b.sponsor) return 1; } return a.name.localeCompare(b.name); }); // Render platform item for mobile const renderMobilePlatform = (platform: Platform) => { if (platform.subOptions) { return ( <div key={platform.id} className="space-y-1"> <div className="flex items-center gap-3 px-3 py-2 text-base text-muted-foreground"> {platform.sponsor && !useCloneBranding ? ( <Heart className="h-4 w-4 text-pink-500 fill-pink-500" /> ) : ( <Zap className="h-4 w-4 text-green-500" /> )} {platform.name} </div> <div className="pl-6 space-y-1"> {platform.subOptions.map((option) => ( <button key={option.baseUrl} onClick={() => handleRunAndClose(platform, option.baseUrl)} className="flex items-center gap-3 w-full px-3 py-3 text-base hover:bg-accent rounded-md text-left" > {option.name} </button> ))} </div> </div> ); } return ( <button key={platform.id} onClick={() => handleRunAndClose(platform, platform.baseUrl)} className="flex items-center gap-3 w-full px-3 py-3 text-base hover:bg-accent rounded-md text-left" > {platform.sponsor && !useCloneBranding ? ( <Heart className="h-4 w-4 text-pink-500 fill-pink-500" /> ) : platform.supportsQuerystring === false ? ( <Clipboard className="h-4 w-4 text-muted-foreground" /> ) : ( <Zap className="h-4 w-4 text-green-500" /> )} {platform.name} </button> ); }; // Render platform item for desktop dropdown const renderDropdownPlatform = (platform: Platform) => { if (platform.subOptions) { return ( <DropdownMenuSub key={platform.id}> <DropdownMenuSubTrigger className="flex items-center gap-2"> {platform.sponsor && !useCloneBranding ? ( <Heart className="h-3 w-3 text-pink-500 fill-pink-500" /> ) : ( <Zap className="h-3 w-3 text-green-500" /> )} {platform.name} </DropdownMenuSubTrigger> <DropdownMenuSubContent> {platform.subOptions.map((option) => ( <DropdownMenuItem key={option.baseUrl} onClick={() => handleRun(platform, option.baseUrl)} > {option.name} </DropdownMenuItem> ))} </DropdownMenuSubContent> </DropdownMenuSub> ); } return ( <DropdownMenuItem key={platform.id} onClick={() => handleRun(platform, platform.baseUrl)} className="flex items-center gap-2" > {platform.sponsor && !useCloneBranding ? ( <Heart className="h-3 w-3 text-pink-500 fill-pink-500" /> ) : platform.supportsQuerystring === false ? ( <Clipboard className="h-3 w-3 text-muted-foreground" /> ) : ( <Zap className="h-3 w-3 text-green-500" /> )} {platform.name} </DropdownMenuItem> ); }; // Tab buttons render function const renderTabButtons = (size: "default" | "small" = "default") => ( <div className={`flex gap-1 ${size === "small" ? "p-1" : "p-1.5"} bg-muted rounded-md`}> <button onClick={() => setActiveTab("chat")} className={`flex-1 ${size === "small" ? "px-2 py-1 text-xs" : "px-3 py-1.5 text-sm"} font-medium rounded transition-colors ${ activeTab === "chat" ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground" }`} > Chat </button> <button onClick={() => setActiveTab("code")} className={`flex-1 ${size === "small" ? "px-2 py-1 text-xs" : "px-3 py-1.5 text-sm"} font-medium rounded transition-colors ${ activeTab === "code" ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground" }`} > Code </button> </div> ); return ( <> {/* Mobile: Bottom Sheet */} {isMobile ? ( <Sheet open={sheetOpen} onOpenChange={setSheetOpen}> <SheetTrigger asChild> <Button variant={emphasized ? undefined : variant} size={size} className={emphasized ? `bg-green-600 hover:bg-green-700 text-white ${className || ""}` : className}> <Play className="h-4 w-4" /> {size !== "icon" && <span className="ml-1.5">{t("run")}</span>} </Button> </SheetTrigger> <SheetContent side="bottom" className="max-h-[70vh]"> <SheetHeader> <SheetTitle>{t("run")}</SheetTitle> </SheetHeader> <div className="py-2"> {renderTabButtons()} </div> <div className="overflow-y-auto flex-1 py-2"> {activePlatforms.map(renderMobilePlatform)} </div> </SheetContent> </Sheet> ) : ( /* Desktop: Dropdown */ <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant={emphasized ? undefined : variant} size={size} className={emphasized ? `bg-green-600 hover:bg-green-700 text-white ${className || ""}` : className}> <Play className="h-4 w-4" /> {size !== "icon" && <span className="ml-1.5">{t("run")}</span>} </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-52"> <div className="p-1"> {renderTabButtons("small")} </div> <DropdownMenuSeparator /> <div className="max-h-64 overflow-y-auto"> {activePlatforms.map(renderDropdownPlatform)} </div> </DropdownMenuContent> </DropdownMenu> )} <Dialog open={dialogOpen} onOpenChange={setDialogOpen}> <DialogContent> <DialogHeader> <DialogTitle>{t("promptCopied")}</DialogTitle> <DialogDescription> {t("promptCopiedDescription", { platform: pendingPlatform?.name ?? "" })} </DialogDescription> </DialogHeader> <DialogFooter> <Button variant="outline" onClick={() => setDialogOpen(false)}> {t("cancel")} </Button> <Button onClick={handleOpenPlatform}> <ExternalLink className="h-4 w-4 mr-2" /> {t("openPlatform", { platform: pendingPlatform?.name ?? "" })} </Button> </DialogFooter> </DialogContent> </Dialog> {/* Variable Fill Dialog */} <Dialog open={variableDialogOpen} onOpenChange={setVariableDialogOpen}> <DialogContent className="sm:max-w-md"> <DialogHeader> <DialogTitle>{tCommon("fillVariables")}</DialogTitle> <DialogDescription> {tCommon("fillVariablesDescription")} </DialogDescription> </DialogHeader> <div className="space-y-4 py-4"> {unfilledVariables.map((variable) => ( <div key={variable.name} className="space-y-2"> <label htmlFor={`run-var-${variable.name}`} className="text-sm font-medium"> {variable.name} </label> <input id={`run-var-${variable.name}`} type="text" value={variableValues[variable.name] || ""} onChange={(e) => setVariableValues(prev => ({ ...prev, [variable.name]: e.target.value }))} placeholder={variable.defaultValue || variable.name} className="w-full px-3 py-2 border rounded-md text-sm bg-background" /> </div> ))} </div> <DialogFooter> <Button variant="outline" onClick={() => setVariableDialogOpen(false)}> {t("cancel")} </Button> <Button onClick={handleVariableSubmit}> <Play className="h-4 w-4 mr-2" /> {t("run")} </Button> </DialogFooter> </DialogContent> </Dialog> </> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/mini-prompt-card.tsx
src/components/prompts/mini-prompt-card.tsx
"use client"; import Link from "next/link"; import { Badge } from "@/components/ui/badge"; import { getPromptUrl } from "@/lib/urls"; interface MiniPromptCardProps { prompt: { id: string; slug?: string | null; title: string; description?: string | null; contentPreview: string; type: string; tags: string[]; }; } export function MiniPromptCard({ prompt }: MiniPromptCardProps) { return ( <Link href={getPromptUrl(prompt.id, prompt.slug)} target="_blank" prefetch={false} className="block p-2 border rounded-md hover:bg-accent/50 transition-colors text-xs" > <div className="flex items-start justify-between gap-2 mb-1"> <span className="font-medium line-clamp-1 flex-1">{prompt.title}</span> <Badge variant="outline" className="text-[9px] shrink-0 py-0 px-1"> {prompt.type} </Badge> </div> <p className="text-muted-foreground line-clamp-2 mb-1.5"> {prompt.contentPreview} </p> {prompt.tags.length > 0 && ( <div className="flex flex-wrap gap-1"> {prompt.tags.slice(0, 3).map((tag) => ( <span key={tag} className="px-1 py-0.5 rounded text-[9px] bg-muted text-muted-foreground" > {tag} </span> ))} </div> )} </Link> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/hf-data-studio-dropdown.tsx
src/components/prompts/hf-data-studio-dropdown.tsx
"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { useTheme } from "next-themes"; import { ChevronDown, Play, ExternalLink, Sparkles, Loader2 } from "lucide-react"; import Editor from "@monaco-editor/react"; import { Button } from "@/components/ui/button"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import SQL_EXAMPLES from "@/data/sql-examples.json"; const DEFAULT_SQL = SQL_EXAMPLES[0].sql; const HF_DATASET_URL = "https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/viewer"; interface HFDataStudioDropdownProps { aiGenerationEnabled?: boolean; } export function HFDataStudioDropdown({ aiGenerationEnabled = false }: HFDataStudioDropdownProps) { const t = useTranslations("prompts.hfDataStudio"); const { resolvedTheme } = useTheme(); const [sql, setSql] = useState(DEFAULT_SQL); const [aiPrompt, setAiPrompt] = useState(""); const [isGenerating, setIsGenerating] = useState(false); const [showAiInput, setShowAiInput] = useState(false); const handleOpenDataset = () => { window.open(HF_DATASET_URL, "_blank"); }; const handleRun = () => { const encodedSql = encodeURIComponent(sql); const url = `${HF_DATASET_URL}?views[]=train&sql=${encodedSql}`; window.open(url, "_blank"); }; const handleGenerateSQL = async () => { if (!aiPrompt.trim() || isGenerating) return; setIsGenerating(true); try { const response = await fetch("/api/generate/sql", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: aiPrompt }), }); if (!response.ok) throw new Error("Failed to generate SQL"); const data = await response.json(); setSql(data.sql); } catch (error) { console.error("SQL generation error:", error); } finally { setIsGenerating(false); } }; return ( <div className="flex w-full sm:w-auto"> <Button size="sm" variant="outline" className="h-8 text-xs rounded-e-none border-e-0 flex-1 sm:flex-initial" onClick={handleOpenDataset} > 🤗 {t("button")} </Button> <Popover modal> <PopoverTrigger asChild> <Button size="sm" variant="outline" className="h-8 px-2 rounded-s-none" > <ChevronDown className="h-3 w-3" /> </Button> </PopoverTrigger> <PopoverContent align="end" className="w-[calc(100vw-2rem)] sm:w-[500px] p-3" sideOffset={8} collisionPadding={16}> <div className="space-y-3"> {/* Header with Examples Select + AI Button */} <div className="flex items-center justify-between gap-2"> <div className="flex flex-1 items-stretch"> <Select onValueChange={(value) => setSql(value)}> <SelectTrigger className={`h-8 text-xs flex-1 ${aiGenerationEnabled ? "rounded-e-none border-e-0" : ""}`} size="sm"> <SelectValue placeholder={t("selectExample")} /> </SelectTrigger> <SelectContent> {SQL_EXAMPLES.map((example, index) => ( <SelectItem key={index} value={example.sql} className="text-xs"> {example.label} </SelectItem> ))} </SelectContent> </Select> {aiGenerationEnabled && ( <Button size="sm" variant={showAiInput ? "secondary" : "outline"} className="rounded-s-none border-s-0" onClick={() => setShowAiInput(!showAiInput)} title={t("aiGenerate")} > <Sparkles className="h-3.5 w-3.5" /> </Button> )} </div> <a href={HF_DATASET_URL} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 shrink-0" > {t("openDataset")} <ExternalLink className="h-3 w-3" /> </a> </div> {/* AI Input (toggled) */} {aiGenerationEnabled && showAiInput && ( <div className="flex rounded-md focus-within:ring-1 focus-within:ring-ring focus-within:border-foreground/30"> <input placeholder={t("aiPlaceholder")} value={aiPrompt} onChange={(e) => setAiPrompt(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleGenerateSQL()} className="h-8 text-xs flex-1 rounded-s-md rounded-e-none border border-e-0 border-input bg-transparent px-3 py-1 outline-none placeholder:text-muted-foreground" autoFocus /> <Button size="sm" variant="outline" className="rounded-s-none border-s-0 text-[11px] bg-muted/50 hover:bg-muted" onClick={handleGenerateSQL} disabled={isGenerating || !aiPrompt.trim()} > {isGenerating ? ( <Loader2 className="h-3 w-3 animate-spin" /> ) : ( t("generateSql") )} </Button> </div> )} {/* SQL Editor */} <div dir="ltr" className="border rounded-md overflow-hidden text-left"> <Editor height="200px" defaultLanguage="sql" value={sql} onChange={(value) => setSql(value || "")} theme={resolvedTheme === "dark" ? "vs-dark" : "light"} options={{ minimap: { enabled: false }, fontSize: 12, lineNumbers: "on", scrollBeyondLastLine: false, automaticLayout: true, tabSize: 2, wordWrap: "on", }} /> </div> {/* Run Button */} <Button size="sm" className="w-full" onClick={handleRun}> <Play className="h-3.5 w-3.5 mr-1.5" /> {t("runQuery")} </Button> </div> </PopoverContent> </Popover> </div> ); }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false
f/awesome-chatgpt-prompts
https://github.com/f/awesome-chatgpt-prompts/blob/bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b/src/components/prompts/filter-context.tsx
src/components/prompts/filter-context.tsx
"use client"; import { createContext, useContext, useState, ReactNode } from "react"; interface FilterContextType { isFilterPending: boolean; setFilterPending: (pending: boolean) => void; } const FilterContext = createContext<FilterContextType | null>(null); export function FilterProvider({ children }: { children: ReactNode }) { const [isFilterPending, setFilterPending] = useState(false); return ( <FilterContext.Provider value={{ isFilterPending, setFilterPending }}> {children} </FilterContext.Provider> ); } export function useFilterContext() { const context = useContext(FilterContext); if (!context) { throw new Error("useFilterContext must be used within FilterProvider"); } return context; }
typescript
CC0-1.0
bb3b291f516f3f034b1066a2b2fdd85ec4b13e0b
2026-01-04T15:25:31.495589Z
false