Spaces:
Sleeping
Sleeping
initial commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- DockerfileAdded+19
- README.md+22-36
- app/(public)/layout.tsxAdded+15
- app/(public)/page.tsxAdded+44
- app/(public)/projects/page.tsxAdded+33
- app/api/ask-ai/route.tsAdded+406
- app/api/auth/route.tsAdded+94
- app/api/me/projects/[namespace]/[repoId]/route.tsAdded+162
- app/api/me/projects/route.tsAdded+126
- app/api/me/route.tsAdded+25
- app/auth/callback/page.tsxAdded+27
- app/auth/page.tsxAdded+36
- app/globals.cssDeleted-26
- app/layout.tsx+81-12
- app/page.tsxDeleted-103
- app/projects/[namespace]/[repoId]/page.tsxAdded+39
- app/projects/new/page.tsxAdded+5
- assets/globals.cssAdded+146
- assets/logo.svgAdded
- assets/space.svgAdded
- components.jsonAdded+21
- components/contexts/app-context.tsxAdded+57
- components/contexts/user-context.tsxAdded+8
- components/editor/ask-ai/index.tsxAdded+376
- components/editor/ask-ai/re-imagine.tsxAdded+140
- components/editor/ask-ai/settings.tsxAdded+212
- components/editor/deploy-button/index.tsxAdded+171
- components/editor/footer/index.tsxAdded+118
- components/editor/header/index.tsxAdded+69
- components/editor/history/index.tsxAdded+69
- components/editor/index.tsxAdded+311
- components/editor/preview/index.tsxAdded+78
- components/editor/save-button/index.tsxAdded+76
- components/invite-friends/index.tsxAdded+85
- components/loading/index.tsxAdded+41
- components/login-modal/index.tsxAdded+61
- components/magic-ui/grid-pattern.tsxAdded+69
- components/my-projects/index.tsxAdded+41
- components/my-projects/project-card.tsxAdded+74
- components/pro-modal/index.tsxAdded+93
- components/providers/tanstack-query-provider.tsxAdded+19
- components/public/navigation/index.tsxAdded+156
- components/space/ask-ai/index.tsxAdded+41
- components/ui/avatar.tsxAdded+53
- components/ui/button.tsxAdded+67
- components/ui/dialog.tsxAdded+143
- components/ui/dropdown-menu.tsxAdded+257
- components/ui/input.tsxAdded+21
- components/ui/popover.tsxAdded+48
- components/ui/select.tsxAdded+185
12345678910111213141516171819FROM node:20-alpineUSER root
USER 1000WORKDIR /usr/src/app# Copy package.json and package-lock.json to the containerCOPY --chown=1000 package.json package-lock.json ./
# Copy the rest of the application files to the containerCOPY --chown=1000 . .
RUN npm installRUN npm run build
# Expose the application port (assuming your app runs on port 3000)EXPOSE 3000
# Start the applicationCMD ["npm", "start"]123456789101112131415161718192021222324252627282930313233343536This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).## Getting StartedFirst, run the development server:```bashnpm run dev# oryarn dev# orpnpm dev# orbun dev```Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.## Learn MoreTo learn more about Next.js, take a look at the following resources:- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!## Deploy on VercelThe easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.12345678910111213141516171819202122---title: DeepSite v2emoji: 🐳colorFrom: bluecolorTo: bluesdk: dockerpinned: trueapp_port: 5173license: mitshort_description: Generate any application with DeepSeekmodels:- deepseek-ai/DeepSeek-V3-0324- deepseek-ai/DeepSeek-R1-0528---# DeepSite 🐳DeepSite is a coding platform powered by DeepSeek AI, designed to make coding smarter and more efficient. Tailored for developers, data scientists, and AI engineers, it integrates generative AI into your coding projects to enhance creativity and productivity.## How to use it locallyFollow [this discussion](https://huggingface.co/spaces/enzostvs/deepsite/discussions/74)
123456789101112131415import Navigation from "@/components/public/navigation";
export default async function PublicLayout({ children,}: Readonly<{ children: React.ReactNode;}>) { return ( <div className="min-h-screen bg-black z-1 relative"> <div className="background__noisy" /> <Navigation /> {children} </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344import { AskAi } from "@/components/space/ask-ai";import { redirect } from "next/navigation";export default function Home() { redirect("/projects/new"); return ( <> <header className="container mx-auto pt-20 px-6 relative flex flex-col items-center justify-center text-center"> <div className="rounded-full border border-neutral-100/10 bg-neutral-100/5 text-xs text-neutral-300 px-3 py-1 max-w-max mx-auto mb-2"> ✨ DeepSite Public Beta </div> <h1 className="text-8xl font-semibold text-white font-mono max-w-4xl"> Code your website with AI in seconds </h1> <p className="text-2xl text-neutral-300/80 mt-4 text-center max-w-2xl"> Vibe Coding has never been so easy. </p> <div className="mt-14 max-w-2xl w-full mx-auto"> <AskAi /> </div> <div className="absolute inset-0 pointer-events-none -z-[1]"> <div className="w-full h-full bg-gradient-to-r from-purple-500 to-pink-500 opacity-10 blur-3xl rounded-full" /> <div className="w-2/3 h-3/4 bg-gradient-to-r from-blue-500 to-teal-500 opacity-24 blur-3xl absolute -top-20 right-10 transform rotate-12" /> <div className="w-1/2 h-1/2 bg-gradient-to-r from-amber-500 to-rose-500 opacity-20 blur-3xl absolute bottom-0 left-10 rounded-3xl" /> <div className="w-48 h-48 bg-gradient-to-r from-cyan-500 to-indigo-500 opacity-20 blur-3xl absolute top-1/3 right-1/3 rounded-lg transform -rotate-15" /> </div> </header> <div id="community" className="h-screen flex items-center justify-center"> <h1 className="text-7xl font-extrabold text-white font-mono"> Community Driven </h1> </div> <div id="deploy" className="h-screen flex items-center justify-center"> <h1 className="text-7xl font-extrabold text-white font-mono"> Deploy your website in seconds </h1> </div> <div id="features" className="h-screen flex items-center justify-center"> <h1 className="text-7xl font-extrabold text-white font-mono"> Features that make you smile </h1> </div> </> );}123456789101112131415161718192021222324252627282930313233import { cookies } from "next/headers";import { redirect } from "next/navigation";
import { apiServer } from "@/lib/api";import MY_TOKEN_KEY from "@/lib/get-cookie-name";import { MyProjects } from "@/components/my-projects";
async function getMyProjects() { const cookieStore = await cookies(); const token = cookieStore.get(MY_TOKEN_KEY())?.value; if (!token) return { redirectUrl: true, projects: [] }; try { const { data } = await apiServer.get("/me/projects", { headers: { Authorization: `Bearer ${token}`, }, });
return { projects: data.projects, }; } catch { return { projects: [] }; }}export default async function ProjectsPage() { const { redirectUrl, projects } = await getMyProjects(); if (redirectUrl) { redirect("/"); }
return <MyProjects projects={projects} />;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406/* eslint-disable @typescript-eslint/no-explicit-any */import type { NextRequest } from "next/server";import { NextResponse } from "next/server";import { headers } from "next/headers";import { InferenceClient } from "@huggingface/inference";
import { MODELS, PROVIDERS } from "@/lib/providers";import { DIVIDER, FOLLOW_UP_SYSTEM_PROMPT, INITIAL_SYSTEM_PROMPT, MAX_REQUESTS_PER_IP, REPLACE_END, SEARCH_START,} from "@/lib/prompts";import MY_TOKEN_KEY from "@/lib/get-cookie-name";
const ipAddresses = new Map();
export async function POST(request: NextRequest) { const authHeaders = await headers(); const userToken = request.cookies.get(MY_TOKEN_KEY())?.value;
const body = await request.json(); const { prompt, provider, model, redesignMarkdown } = body;
if (!model || (!prompt && !redesignMarkdown)) { return NextResponse.json( { ok: false, error: "Missing required fields" }, { status: 400 } ); }
const selectedModel = MODELS.find( (m) => m.value === model || m.label === model ); if (!selectedModel) { return NextResponse.json( { ok: false, error: "Invalid model selected" }, { status: 400 } ); }
if (!selectedModel.providers.includes(provider) && provider !== "auto") { return NextResponse.json( { ok: false, error: `The selected model does not support the ${provider} provider.`, openSelectProvider: true, }, { status: 400 } ); }
let token = userToken; let billTo: string | null = null;
/** * Handle local usage token, this bypass the need for a user token * and allows local testing without authentication. * This is useful for development and testing purposes. */ if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) { token = process.env.HF_TOKEN; }
const ip = authHeaders.get("x-forwarded-for")?.split(",")[0].trim() || authHeaders.get("x-real-ip") || "0.0.0.0";
if (!token) { ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1); if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) { return NextResponse.json( { ok: false, openLogin: true, message: "Log In to continue using the service", }, { status: 429 } ); }
token = process.env.DEFAULT_HF_TOKEN as string; billTo = "huggingface"; }
const DEFAULT_PROVIDER = PROVIDERS.novita; const selectedProvider = provider === "auto" ? PROVIDERS[selectedModel.autoProvider as keyof typeof PROVIDERS] : PROVIDERS[provider as keyof typeof PROVIDERS] ?? DEFAULT_PROVIDER;
try { // Create a stream response const encoder = new TextEncoder(); const stream = new TransformStream(); const writer = stream.writable.getWriter();
// Start the response const response = new NextResponse(stream.readable, { headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-cache", Connection: "keep-alive", }, });
// Process in background (async () => { let completeResponse = ""; try { const client = new InferenceClient(token); const chatCompletion = client.chatCompletionStream( { model: selectedModel.value, provider: selectedProvider.id as any, messages: [ { role: "system", content: INITIAL_SYSTEM_PROMPT, }, { role: "user", content: redesignMarkdown ? `Here is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown.` : prompt, }, ], max_tokens: selectedProvider.max_tokens, }, billTo ? { billTo } : {} );
while (true) { const { done, value } = await chatCompletion.next(); if (done) { break; }
const chunk = value.choices[0]?.delta?.content; if (chunk) { let newChunk = chunk; if (!selectedModel?.isThinker) { if (provider !== "sambanova") { await writer.write(encoder.encode(chunk)); completeResponse += chunk;
if (completeResponse.includes("</html>")) { break; } } else { if (chunk.includes("</html>")) { newChunk = newChunk.replace(/<\/html>[\s\S]*/, "</html>"); } completeResponse += newChunk; await writer.write(encoder.encode(newChunk)); if (newChunk.includes("</html>")) { break; } } } else { const lastThinkTagIndex = completeResponse.lastIndexOf("</think>"); completeResponse += newChunk; await writer.write(encoder.encode(newChunk)); if (lastThinkTagIndex !== -1) { const afterLastThinkTag = completeResponse.slice( lastThinkTagIndex + "</think>".length ); if (afterLastThinkTag.includes("</html>")) { break; } } } } } } catch (error: any) { if (error.message?.includes("exceeded your monthly included credits")) { await writer.write( encoder.encode( JSON.stringify({ ok: false, openProModal: true, message: error.message, }) ) ); } else { await writer.write( encoder.encode( JSON.stringify({ ok: false, message: error.message || "An error occurred while processing your request.", }) ) ); } } finally { await writer.close(); } })();
return response; } catch (error: any) { return NextResponse.json( { ok: false, openSelectProvider: true, message: error?.message || "An error occurred while processing your request.", }, { status: 500 } ); }}
export async function PUT(request: NextRequest) { const authHeaders = await headers(); const userToken = request.cookies.get(MY_TOKEN_KEY())?.value;
const body = await request.json(); const { prompt, html, previousPrompt, provider } = body;
if (!prompt || !html) { return NextResponse.json( { ok: false, error: "Missing required fields" }, { status: 400 } ); }
const selectedModel = MODELS[0];
let token = userToken; let billTo: string | null = null;
/** * Handle local usage token, this bypass the need for a user token * and allows local testing without authentication. * This is useful for development and testing purposes. */ if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) { token = process.env.HF_TOKEN; }
const ip = authHeaders.get("x-forwarded-for")?.split(",")[0].trim() || authHeaders.get("x-real-ip") || "0.0.0.0";
if (!token) { ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1); if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) { return NextResponse.json( { ok: false, openLogin: true, message: "Log In to continue using the service", }, { status: 429 } ); }
token = process.env.DEFAULT_HF_TOKEN as string; billTo = "huggingface"; }
const client = new InferenceClient(token);
const DEFAULT_PROVIDER = PROVIDERS.novita; const selectedProvider = provider === "auto" ? PROVIDERS[selectedModel.autoProvider as keyof typeof PROVIDERS] : PROVIDERS[provider as keyof typeof PROVIDERS] ?? DEFAULT_PROVIDER;
try { const response = await client.chatCompletion( { model: selectedModel.value, provider: selectedProvider.id as any, messages: [ { role: "system", content: FOLLOW_UP_SYSTEM_PROMPT, }, { role: "user", content: previousPrompt ? previousPrompt : "You are modifying the HTML file based on the user's request.", }, { role: "assistant", content: `The current code is: \n\`\`\`html\n${html}\n\`\`\``, }, { role: "user", content: prompt, }, ], ...(selectedProvider.id !== "sambanova" ? { max_tokens: selectedProvider.max_tokens, } : {}), }, billTo ? { billTo } : {} );
const chunk = response.choices[0]?.message?.content; if (!chunk) { return NextResponse.json( { ok: false, message: "No content returned from the model" }, { status: 400 } ); }
if (chunk) { const updatedLines: number[][] = []; let newHtml = html; let position = 0; let moreBlocks = true;
while (moreBlocks) { const searchStartIndex = chunk.indexOf(SEARCH_START, position); if (searchStartIndex === -1) { moreBlocks = false; continue; }
const dividerIndex = chunk.indexOf(DIVIDER, searchStartIndex); if (dividerIndex === -1) { moreBlocks = false; continue; }
const replaceEndIndex = chunk.indexOf(REPLACE_END, dividerIndex); if (replaceEndIndex === -1) { moreBlocks = false; continue; }
const searchBlock = chunk.substring( searchStartIndex + SEARCH_START.length, dividerIndex ); const replaceBlock = chunk.substring( dividerIndex + DIVIDER.length, replaceEndIndex );
if (searchBlock.trim() === "") { newHtml = `${replaceBlock}\n${newHtml}`; updatedLines.push([1, replaceBlock.split("\n").length]); } else { const blockPosition = newHtml.indexOf(searchBlock); if (blockPosition !== -1) { const beforeText = newHtml.substring(0, blockPosition); const startLineNumber = beforeText.split("\n").length; const replaceLines = replaceBlock.split("\n").length; const endLineNumber = startLineNumber + replaceLines - 1;
updatedLines.push([startLineNumber, endLineNumber]); newHtml = newHtml.replace(searchBlock, replaceBlock); } }
position = replaceEndIndex + REPLACE_END.length; }
return NextResponse.json({ ok: true, html: newHtml, updatedLines, }); } else { return NextResponse.json( { ok: false, message: "No content returned from the model" }, { status: 400 } ); } } catch (error: any) { if (error.message?.includes("exceeded your monthly included credits")) { return NextResponse.json( { ok: false, openProModal: true, message: error.message, }, { status: 402 } ); } return NextResponse.json( { ok: false, openSelectProvider: true, message: error.message || "An error occurred while processing your request.", }, { status: 500 } ); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { NextRequest, NextResponse } from "next/server";
export async function GET() { const redirect_uri = process.env.REDIRECT_URI; const loginRedirectUrl = `https://huggingface.co/oauth/authorize?client_id=${process.env.HUGGINGFACE_CLIENT_ID}&redirect_uri=${redirect_uri}&response_type=code&scope=openid%20profile%20write-repos%20manage-repos%20inference-api&prompt=consent&state=1234567890`;
return NextResponse.json( { redirect: loginRedirectUrl, }, { status: 200, headers: { "Content-Type": "application/json", }, } );}
export async function POST(req: NextRequest) { const body = await req.json(); const { code } = body;
if (!code) { return NextResponse.json( { error: "Code is required" }, { status: 400, headers: { "Content-Type": "application/json", }, } ); }
const Authorization = `Basic ${Buffer.from( `${process.env.HUGGINGFACE_CLIENT_ID}:${process.env.HUGGINGFACE_CLIENT_SECRET}` ).toString("base64")}`;
const redirect_uri = process.env.REDIRECT_URI as string; const request_auth = await fetch("https://huggingface.co/oauth/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization, }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri, }), });
const response = await request_auth.json(); if (!response.access_token) { return NextResponse.json( { error: "Failed to retrieve access token" }, { status: 400, headers: { "Content-Type": "application/json", }, } ); }
const userResponse = await fetch("https://huggingface.co/api/whoami-v2", { headers: { Authorization: `Bearer ${response.access_token}`, }, });
if (!userResponse.ok) { return NextResponse.json( { user: null, errCode: userResponse.status }, { status: userResponse.status } ); } const user = await userResponse.json();
return NextResponse.json( { access_token: response.access_token, expires_in: response.expires_in, user, }, { status: 200, headers: { "Content-Type": "application/json", }, } );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, uploadFile } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";import { getPTag } from "@/lib/utils";
export async function GET( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
await dbConnect(); const param = await params; const { namespace, repoId } = param;
const project = await Project.findOne({ user_id: user.id, space_id: `${namespace}/${repoId}`, }).lean(); if (!project) { return NextResponse.json( { ok: false, error: "Project not found", }, { status: 404 } ); } const space_url = `https://huggingface.co/spaces/${namespace}/${repoId}/raw/main/index.html`; try { const space = await spaceInfo({ name: namespace + "/" + repoId, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static" || space.private) { return NextResponse.json( { ok: false, error: "Space is not a static space or is private", }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user", }, { status: 403 } ); }
const response = await fetch(space_url); if (!response.ok) { return NextResponse.json( { ok: false, error: "Failed to fetch space HTML", }, { status: 404 } ); } let html = await response.text(); // remove the last p tag including this url https://enzostvs-deepsite.hf.space html = html.replace(getPTag(namespace + "/" + repoId), "");
return NextResponse.json( { project: { ...project, html, }, ok: true, }, { status: 200 } );
// eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { if (error.statusCode === 404) { await Project.deleteOne({ user_id: user.id, space_id: `${namespace}/${repoId}`, }); return NextResponse.json( { error: "Space not found", ok: false }, { status: 404 } ); } return NextResponse.json( { error: error.message, ok: false }, { status: 500 } ); }}
export async function PUT( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
await dbConnect(); const param = await params; const { namespace, repoId } = param; const { html, prompts } = await req.json();
const project = await Project.findOne({ user_id: user.id, space_id: `${namespace}/${repoId}`, }).lean(); if (!project) { return NextResponse.json( { ok: false, error: "Project not found", }, { status: 404 } ); }
const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
const newHtml = html.replace(/<\/body>/, `${getPTag(repo.name)}</body>`); const file = new File([newHtml], "index.html", { type: "text/html" }); await uploadFile({ repo, file, accessToken: user.token as string, commitTitle: `${prompts[prompts.length - 1]} - Follow Up Deployment`, });
await Project.updateOne( { user_id: user.id, space_id: `${namespace}/${repoId}` }, { $set: { prompts: [ ...(project && "prompts" in project ? project.prompts : []), ...prompts, ], }, } ); return NextResponse.json({ ok: true }, { status: 200 });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import { NextRequest, NextResponse } from "next/server";import { createRepo, RepoDesignation, uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";import { COLORS, getPTag } from "@/lib/utils";// import type userexport async function GET() { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
await dbConnect();
const projects = await Project.find({ user_id: user?.id, }) .sort({ _createdAt: -1 }) .limit(100) .lean(); if (!projects) { return NextResponse.json( { ok: false, projects: [], }, { status: 404 } ); } return NextResponse.json( { ok: true, projects, }, { status: 200 } );}
/** * This API route creates a new project in Hugging Face Spaces. * It requires an Authorization header with a valid token and a JSON body with the project details. */export async function POST(request: NextRequest) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const { title, html, prompts } = await request.json();
if (!title || !html) { return NextResponse.json( { message: "Title and HTML content are required.", ok: false }, { status: 400 } ); }
await dbConnect();
try { let readme = ""; let newHtml = html;
const newTitle = title .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .split("-") .filter(Boolean) .join("-") .slice(0, 96);
const repo: RepoDesignation = { type: "space", name: `${user.name}/${newTitle}`, };
const { repoUrl } = await createRepo({ repo, accessToken: user.token as string, }); const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)]; const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)]; readme = `---title: ${newTitle}emoji: 🐳colorFrom: ${colorFrom}colorTo: ${colorTo}sdk: staticpinned: falsetags: - deepsite---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference`;
newHtml = html.replace(/<\/body>/, `${getPTag(repo.name)}</body>`); const file = new File([newHtml], "index.html", { type: "text/html" }); const readmeFile = new File([readme], "README.md", { type: "text/markdown", }); const files = [file, readmeFile]; await uploadFiles({ repo, files, accessToken: user.token as string, commitTitle: `${prompts[prompts.length - 1]} - Initial Deployment`, }); const path = repoUrl.split("/").slice(-2).join("/"); const project = await Project.create({ user_id: user.id, space_id: path, prompts, }); return NextResponse.json({ project, path, ok: true }, { status: 201 }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { return NextResponse.json( { error: err.message, ok: false }, { status: 500 } ); }}12345678910111213141516171819202122232425import { headers } from "next/headers";import { NextResponse } from "next/server";
export async function GET() { const authHeaders = await headers(); const token = authHeaders.get("Authorization"); if (!token) { return NextResponse.json({ user: null, errCode: 401 }, { status: 401 }); }
const userResponse = await fetch("https://huggingface.co/api/whoami-v2", { headers: { Authorization: `${token}`, }, });
if (!userResponse.ok) { return NextResponse.json( { user: null, errCode: userResponse.status }, { status: userResponse.status } ); } const user = await userResponse.json(); return NextResponse.json({ user, errCode: null }, { status: 200 });}123456789101112131415161718192021222324252627"use client";
import { use } from "react";import { useBroadcastChannel } from "@/lib/useBroadcastChannel";import { useMount } from "react-use";
export default function AuthCallback({ searchParams,}: { searchParams: Promise<{ code: string }>;}) { const { code } = use(searchParams);
const { postMessage } = useBroadcastChannel("auth", () => {}); useMount(() => { if (code) { postMessage({ code: code, type: "user-oauth", }); window.close(); return; } });
return <div>Login in progress ...</div>;}123456789101112131415161718192021222324252627282930313233343536import { redirect } from "next/navigation";import { Metadata } from "next";import { apiServer } from "@/lib/api";
async function getLoginUrl() { try { const res = await apiServer.get("/auth"); return res.data; } catch (error) { return error; }}
export const revalidate = 1;
export const metadata: Metadata = { robots: "noindex, nofollow",};
export default async function Auth() { const login = await getLoginUrl(); if (login?.redirect) { redirect(login.redirect); }
return ( <div className="p-4"> <div className="border bg-red-500/10 border-red-500/20 text-red-500 px-5 py-3 rounded-lg"> <h1 className="text-xl font-bold">Error</h1> <p className="text-sm"> An error occurred while trying to log in. Please try again later. </p> </div> </div> );}1234567891011121314151617181920212223242526@import "tailwindcss";
:root { --background: #ffffff; --foreground: #171717;}
@theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --font-sans: var(--font-geist-sans); --font-mono: var(--font-geist-mono);}
@media (prefers-color-scheme: dark) { :root { --background: #0a0a0a; --foreground: #ededed; }}
body { background: var(--background); color: var(--foreground); font-family: Arial, Helvetica, sans-serif;}123456789101112131415161718192021222324252627282930313233import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";const geistSans = Geist({variable: "--font-geist-sans",subsets: ["latin"],});const geistMono = Geist_Mono({variable: "--font-geist-mono",subsets: ["latin"],});export const metadata: Metadata = {title: "Create Next App",description: "Generated by create next app",};export default function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {return (<html lang="en"><bodyclassName={`${geistSans.variable} ${geistMono.variable} antialiased`}>{children}</body></html>);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102/* eslint-disable @typescript-eslint/no-explicit-any */import type { Metadata, Viewport } from "next";import { Inter, PT_Sans } from "next/font/google";import { cookies } from "next/headers";import TanstackProvider from "@/components/providers/tanstack-query-provider";import "@/assets/globals.css";import { Toaster } from "@/components/ui/sonner";import MY_TOKEN_KEY from "@/lib/get-cookie-name";import { apiServer } from "@/lib/api";import AppContext from "@/components/contexts/app-context";const inter = Inter({variable: "--font-inter-sans",subsets: ["latin"],});const ptSans = PT_Sans({variable: "--font-ptSans-mono",subsets: ["latin"],weight: ["400", "700"],});export const metadata: Metadata = {title: "DeepSite | Build with AI ✨",description:"DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.",openGraph: {title: "DeepSite | Build with AI ✨",description:"DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.",url: "https://deepsite.hf.co",siteName: "DeepSite",images: [{url: "https://deepsite.hf.co/banner.png",width: 1200,height: 630,alt: "DeepSite Open Graph Image",},],},twitter: {card: "summary_large_image",title: "DeepSite | Build with AI ✨",description:"DeepSite is a web development tool that helps you build websites with AI, no code required. Let's deploy your website with DeepSite and enjoy the magic of AI.",images: ["https://deepsite.hf.co/banner.png"],},appleWebApp: {capable: true,title: "DeepSite",statusBarStyle: "black-translucent",},themeColor: "#000000",icons: {icon: "/logo.svg",shortcut: "/logo.svg",apple: "/logo.svg",},};export const viewport: Viewport = {initialScale: 1,maximumScale: 1,themeColor: "#000000",};async function getMe() {const cookieStore = await cookies();const token = cookieStore.get(MY_TOKEN_KEY())?.value;if (!token) return { user: null, errCode: null };try {const res = await apiServer.get("/me", {headers: {Authorization: `Bearer ${token}`,},});return { user: res.data.user, errCode: null };} catch (err: any) {return { user: null, errCode: err.status };}}export default async function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {const data = await getMe();return (<html lang="en"><bodyclassName={`${inter.variable} ${ptSans.variable} antialiased bg-black dark`}><Toaster richColors position="bottom-center" /><TanstackProvider><AppContext me={data}>{children}</AppContext></TanstackProvider></body></html>);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import Image from "next/image";
export default function Home() { return ( <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <Image className="dark:invert" src="/next.svg" alt="Next.js logo" width={180} height={38} priority /> <ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> <li className="mb-2 tracking-[-.01em]"> Get started by editing{" "} <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold"> app/page.tsx </code> . </li> <li className="tracking-[-.01em]"> Save and see your changes instantly. </li> </ol>
<div className="flex gap-4 items-center flex-col sm:flex-row"> <a className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto" href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <Image className="dark:invert" src="/vercel.svg" alt="Vercel logomark" width={20} height={20} /> Deploy now </a> <a className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]" href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > Read our docs </a> </div> </main> <footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center"> <a className="flex items-center gap-2 hover:underline hover:underline-offset-4" href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <Image aria-hidden src="/file.svg" alt="File icon" width={16} height={16} /> Learn </a> <a className="flex items-center gap-2 hover:underline hover:underline-offset-4" href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <Image aria-hidden src="/window.svg" alt="Window icon" width={16} height={16} /> Examples </a> <a className="flex items-center gap-2 hover:underline hover:underline-offset-4" href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <Image aria-hidden src="/globe.svg" alt="Globe icon" width={16} height={16} /> Go to nextjs.org → </a> </footer> </div> );}123456789101112131415161718192021222324252627282930313233343536373839import { cookies } from "next/headers";import { redirect } from "next/navigation";
import { apiServer } from "@/lib/api";import MY_TOKEN_KEY from "@/lib/get-cookie-name";import { AppEditor } from "@/components/editor";
async function getProject(namespace: string, repoId: string) { const cookieStore = await cookies(); const token = cookieStore.get(MY_TOKEN_KEY())?.value; if (!token) return {}; try { const { data } = await apiServer.get( `/me/projects/${namespace}/${repoId}`, { headers: { Authorization: `Bearer ${token}`, }, } );
return data.project; } catch { return {}; }}
export default async function ProjectNamespacePage({ params,}: { params: Promise<{ namespace: string; repoId: string }>;}) { const { namespace, repoId } = await params; const project = await getProject(namespace, repoId); if (!project?.html) { redirect("/projects"); } return <AppEditor project={project} />;}12345import { AppEditor } from "@/components/editor";
export default function ProjectsNewPage() { return <AppEditor />;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146@import "tailwindcss";@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --font-sans: var(--font-inter-sans); --font-mono: var(--font-ptSans-mono); --color-sidebar-ring: var(--sidebar-ring); --color-sidebar-border: var(--sidebar-border); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-accent: var(--sidebar-accent); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --color-sidebar-primary: var(--sidebar-primary); --color-sidebar-foreground: var(--sidebar-foreground); --color-sidebar: var(--sidebar); --color-chart-5: var(--chart-5); --color-chart-4: var(--chart-4); --color-chart-3: var(--chart-3); --color-chart-2: var(--chart-2); --color-chart-1: var(--chart-1); --color-ring: var(--ring); --color-input: var(--input); --color-border: var(--border); --color-destructive: var(--destructive); --color-accent-foreground: var(--accent-foreground); --color-accent: var(--accent); --color-muted-foreground: var(--muted-foreground); --color-muted: var(--muted); --color-secondary-foreground: var(--secondary-foreground); --color-secondary: var(--secondary); --color-primary-foreground: var(--primary-foreground); --color-primary: var(--primary); --color-popover-foreground: var(--popover-foreground); --color-popover: var(--popover); --color-card-foreground: var(--card-foreground); --color-card: var(--card); --radius-sm: calc(var(--radius) - 4px); --radius-md: calc(var(--radius) - 2px); --radius-lg: var(--radius); --radius-xl: calc(var(--radius) + 4px);}
:root { --radius: 0.625rem; --background: oklch(1 0 0); --foreground: oklch(0.145 0 0); --card: oklch(1 0 0); --card-foreground: oklch(0.145 0 0); --popover: oklch(1 0 0); --popover-foreground: oklch(0.145 0 0); --primary: oklch(0.205 0 0); --primary-foreground: oklch(0.985 0 0); --secondary: oklch(0.97 0 0); --secondary-foreground: oklch(0.205 0 0); --muted: oklch(0.97 0 0); --muted-foreground: oklch(0.556 0 0); --accent: oklch(0.97 0 0); --accent-foreground: oklch(0.205 0 0); --destructive: oklch(0.577 0.245 27.325); --border: oklch(0.922 0 0); --input: oklch(0.922 0 0); --ring: oklch(0.708 0 0); --chart-1: oklch(0.646 0.222 41.116); --chart-2: oklch(0.6 0.118 184.704); --chart-3: oklch(0.398 0.07 227.392); --chart-4: oklch(0.828 0.189 84.429); --chart-5: oklch(0.769 0.188 70.08); --sidebar: oklch(0.985 0 0); --sidebar-foreground: oklch(0.145 0 0); --sidebar-primary: oklch(0.205 0 0); --sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-accent: oklch(0.97 0 0); --sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-border: oklch(0.922 0 0); --sidebar-ring: oklch(0.708 0 0);}
.dark { --background: oklch(0.145 0 0); --foreground: oklch(0.985 0 0); --card: oklch(0.205 0 0); --card-foreground: oklch(0.985 0 0); --popover: oklch(0.205 0 0); --popover-foreground: oklch(0.985 0 0); --primary: oklch(0.922 0 0); --primary-foreground: oklch(0.205 0 0); --secondary: oklch(0.269 0 0); --secondary-foreground: oklch(0.985 0 0); --muted: oklch(0.269 0 0); --muted-foreground: oklch(0.708 0 0); --accent: oklch(0.269 0 0); --accent-foreground: oklch(0.985 0 0); --destructive: oklch(0.704 0.191 22.216); --border: oklch(1 0 0 / 10%); --input: oklch(1 0 0 / 15%); --ring: oklch(0.556 0 0); --chart-1: oklch(0.488 0.243 264.376); --chart-2: oklch(0.696 0.17 162.48); --chart-3: oklch(0.769 0.188 70.08); --chart-4: oklch(0.627 0.265 303.9); --chart-5: oklch(0.645 0.246 16.439); --sidebar: oklch(0.205 0 0); --sidebar-foreground: oklch(0.985 0 0); --sidebar-primary: oklch(0.488 0.243 264.376); --sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-accent: oklch(0.269 0 0); --sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-border: oklch(1 0 0 / 10%); --sidebar-ring: oklch(0.556 0 0);}
@layer base { * { @apply border-border outline-ring/50; } body { @apply bg-background text-foreground; } html { @apply scroll-smooth; }}
.background__noisy { @apply bg-blend-normal pointer-events-none opacity-90; background-size: 25ww auto; background-image: url("/background_noisy.webp"); @apply fixed w-screen h-screen -z-1 top-0 left-0;}
.monaco-editor .margin { @apply !bg-neutral-900;}.monaco-editor .monaco-editor-background { @apply !bg-neutral-900;}.monaco-editor .line-numbers { @apply !text-neutral-500;}
.matched-line { @apply bg-sky-500/30;}123456789101112131415161718192021{ "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "", "css": "app/globals.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657/* eslint-disable @typescript-eslint/no-explicit-any */"use client";
import { useUser } from "@/hooks/useUser";import { usePathname, useRouter } from "next/navigation";import { useMount } from "react-use";import { UserContext } from "@/components/contexts/user-context";import { User } from "@/types";import { toast } from "sonner";import { useBroadcastChannel } from "@/lib/useBroadcastChannel";
export default function AppContext({ children, me: initialData,}: { children: React.ReactNode; me?: { user: User | null; errCode: number | null; };}) { const { loginFromCode, user, logout, loading, errCode } = useUser(initialData); const pathname = usePathname(); const router = useRouter();
useMount(() => { if (!initialData?.user && !user) { if ([401, 403].includes(errCode as number)) { logout(); } else if (pathname.includes("/spaces")) { if (errCode) { toast.error("An error occured while trying to log in"); } // If we did not manage to log in (probs because api is down), we simply redirect to the home page router.push("/"); } } });
const events: any = {};
useBroadcastChannel("auth", (message) => { if (pathname.includes("/auth/callback")) return;
if (!message.code) return; if (message.type === "user-oauth" && message?.code && !events.code) { loginFromCode(message.code); } });
return ( <UserContext value={{ user, loading, logout } as any}> {children} </UserContext> );}12345678"use client";
import { createContext } from "react";import { User } from "@/types";
export const UserContext = createContext({ user: undefined as User | undefined,});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376"use client";/* eslint-disable @typescript-eslint/no-explicit-any */import { useState, useRef } from "react";import classNames from "classnames";import { toast } from "sonner";import { useLocalStorage, useUpdateEffect } from "react-use";import { ArrowUp, ChevronDown } from "lucide-react";import { FaStopCircle } from "react-icons/fa";
import { defaultHTML } from "@/lib/consts";import ProModal from "@/components/pro-modal";import { Button } from "@/components/ui/button";import { MODELS } from "@/lib/providers";import { HtmlHistory } from "@/types";import { InviteFriends } from "@/components/invite-friends";import { Settings } from "@/components/editor/ask-ai/settings";import { LoginModal } from "@/components/login-modal";import { ReImagine } from "@/components/editor/ask-ai/re-imagine";import Loading from "@/components/loading";
export function AskAI({ html, setHtml, onScrollToBottom, isAiWorking, setisAiWorking, onNewPrompt, onSuccess,}: { html: string; setHtml: (html: string) => void; onScrollToBottom: () => void; isAiWorking: boolean; onNewPrompt: (prompt: string) => void; htmlHistory?: HtmlHistory[]; setisAiWorking: React.Dispatch<React.SetStateAction<boolean>>; onSuccess: (h: string, p: string, n?: number[][]) => void;}) { const refThink = useRef<HTMLDivElement | null>(null); const audio = useRef<HTMLAudioElement | null>(null);
const [open, setOpen] = useState(false); const [prompt, setPrompt] = useState(""); const [hasAsked, setHasAsked] = useState(false); const [previousPrompt, setPreviousPrompt] = useState(""); const [provider, setProvider] = useLocalStorage("provider", "auto"); const [model, setModel] = useLocalStorage("model", MODELS[0].value); const [openProvider, setOpenProvider] = useState(false); const [providerError, setProviderError] = useState(""); const [openProModal, setOpenProModal] = useState(false); const [think, setThink] = useState<string | undefined>(undefined); const [openThink, setOpenThink] = useState(false); const [isThinking, setIsThinking] = useState(true); const [controller, setController] = useState<AbortController | null>(null);
const callAi = async (redesignMarkdown?: string) => { if (isAiWorking) return; if (!redesignMarkdown && !prompt.trim()) return; setisAiWorking(true); setProviderError(""); setThink(""); setOpenThink(false); setIsThinking(true);
let contentResponse = ""; let thinkResponse = ""; let lastRenderTime = 0;
const isFollowUp = html !== defaultHTML; const abortController = new AbortController(); setController(abortController); try { onNewPrompt(prompt); if (isFollowUp && !redesignMarkdown) { // TODO use @/lib/api instead of fetch directly (if possible) const request = await fetch("/api/ask-ai", { method: "PUT", body: JSON.stringify({ prompt, provider, previousPrompt, model, html, }), headers: { "Content-Type": "application/json", "x-forwarded-for": window.location.hostname, "x-real-ip": window.location.hostname, }, signal: abortController.signal, }); if (request && request.body) { const res = await request.json(); if (!request.ok) { if (res.openLogin) { setOpen(true); } else if (res.openSelectProvider) { setOpenProvider(true); setProviderError(res.message); } else if (res.openProModal) { setOpenProModal(true); } else { toast.error(res.message); } setisAiWorking(false); return; } setHtml(res.html); toast.success("AI responded successfully"); setPreviousPrompt(prompt); setPrompt(""); setisAiWorking(false); onSuccess(res.html, prompt, res.updatedLines); if (audio.current) audio.current.play(); } } else { const request = await fetch("/api/ask-ai", { method: "POST", body: JSON.stringify({ prompt, provider, model, redesignMarkdown, }), headers: { "Content-Type": "application/json", "x-forwarded-for": window.location.hostname, "x-real-ip": window.location.hostname, }, signal: abortController.signal, }); if (request && request.body) { if (!request.ok) { const res = await request.json(); if (res.openLogin) { setOpen(true); } else if (res.openSelectProvider) { setOpenProvider(true); setProviderError(res.message); } else if (res.openProModal) { setOpenProModal(true); } else { toast.error(res.message); } setisAiWorking(false); return; } const reader = request.body.getReader(); const decoder = new TextDecoder("utf-8"); const selectedModel = MODELS.find( (m: { value: string }) => m.value === model ); let contentThink: string | undefined = undefined; const read = async () => { const { done, value } = await reader.read(); if (done) { toast.success("AI responded successfully"); setPreviousPrompt(prompt); setPrompt(""); setisAiWorking(false); setHasAsked(true); setModel(MODELS[0].value); if (audio.current) audio.current.play();
// Now we have the complete HTML including </html>, so set it to be sure const finalDoc = contentResponse.match( /<!DOCTYPE html>[\s\S]*<\/html>/ )?.[0]; if (finalDoc) { setHtml(finalDoc); } onSuccess(finalDoc ?? contentResponse, prompt);
return; }
const chunk = decoder.decode(value, { stream: true }); thinkResponse += chunk; if (selectedModel?.isThinker) { const thinkMatch = thinkResponse.match(/<think>[\s\S]*/)?.[0]; if (thinkMatch && !thinkResponse?.includes("</think>")) { if ((contentThink?.length ?? 0) < 3) { setOpenThink(true); } setThink(thinkMatch.replace("<think>", "").trim()); contentThink += chunk; return read(); } }
contentResponse += chunk;
const newHtml = contentResponse.match( /<!DOCTYPE html>[\s\S]*/ )?.[0]; if (newHtml) { setIsThinking(false); let partialDoc = newHtml; if ( partialDoc.includes("<head>") && !partialDoc.includes("</head>") ) { partialDoc += "\n</head>"; } if ( partialDoc.includes("<body") && !partialDoc.includes("</body>") ) { partialDoc += "\n</body>"; } if (!partialDoc.includes("</html>")) { partialDoc += "\n</html>"; }
// Throttle the re-renders to avoid flashing/flicker const now = Date.now(); if (now - lastRenderTime > 300) { setHtml(partialDoc); lastRenderTime = now; }
if (partialDoc.length > 200) { onScrollToBottom(); } } read(); };
read(); } } } catch (error: any) { setisAiWorking(false); toast.error(error.message); if (error.openLogin) { setOpen(true); } } };
const stopController = () => { if (controller) { controller.abort(); setController(null); setisAiWorking(false); setThink(""); setOpenThink(false); setIsThinking(false); } };
useUpdateEffect(() => { if (refThink.current) { refThink.current.scrollTop = refThink.current.scrollHeight; } }, [think]);
useUpdateEffect(() => { if (!isThinking) { setOpenThink(false); } }, [isThinking]);
return ( <> <div className="bg-neutral-800 border border-neutral-700 rounded-2xl ring-[4px] focus-within:ring-neutral-500/30 focus-within:border-neutral-600 ring-transparent z-10 absolute bottom-3 left-3 w-[calc(100%-20px)] group"> {think && ( <div className="w-full border-b border-neutral-700 relative overflow-hidden"> <header className="flex items-center justify-between px-5 py-2.5 group hover:bg-neutral-600/20 transition-colors duration-200 cursor-pointer" onClick={() => { setOpenThink(!openThink); }} > <p className="text-sm font-medium text-neutral-300 group-hover:text-neutral-200 transition-colors duration-200"> {isThinking ? "DeepSite is thinking..." : "DeepSite's plan"} </p> <ChevronDown className={classNames( "size-4 text-neutral-400 group-hover:text-neutral-300 transition-all duration-200", { "rotate-180": openThink, } )} /> </header> <main ref={refThink} className={classNames( "overflow-y-auto transition-all duration-200 ease-in-out", { "max-h-[0px]": !openThink, "min-h-[250px] max-h-[250px] border-t border-neutral-700": openThink, } )} > <p className="text-[13px] text-neutral-400 whitespace-pre-line px-5 pb-4 pt-3"> {think} </p> </main> </div> )} <div className="w-full relative flex items-center justify-between"> {isAiWorking && ( <div className="absolute bg-neutral-800 rounded-lg bottom-0 left-4 w-[calc(100%-30px)] h-full z-1 flex items-center justify-between max-lg:text-sm"> <div className="flex items-center justify-start gap-2"> <Loading overlay={false} className="!size-4" /> <p className="text-neutral-400 text-sm"> AI is {isThinking ? "thinking" : "coding"}...{" "} </p> </div> <div className="text-xs text-neutral-400 px-1 py-0.5 rounded-md border border-neutral-600 flex items-center justify-center gap-1.5 bg-neutral-800 hover:brightness-110 transition-all duration-200 cursor-pointer" onClick={stopController} > <FaStopCircle /> Stop generation </div> </div> )} <input type="text" disabled={isAiWorking} className="w-full bg-transparent text-sm outline-none text-white placeholder:text-neutral-400 p-4" placeholder={ hasAsked ? "Ask DeepSite for edits" : "Ask DeepSite anything..." } value={prompt} onChange={(e) => setPrompt(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { callAi(); } }} /> </div> <div className="flex items-center justify-between gap-2 px-4 pb-3"> <div className="flex-1 flex items-center justify-start gap-1.5"> <ReImagine onRedesign={(md) => callAi(md)} /> <InviteFriends /> </div> <div className="flex items-center justify-end gap-2"> <Settings provider={provider as string} model={model as string} onChange={setProvider} onModelChange={setModel} open={openProvider} error={providerError} isFollowUp={html !== defaultHTML} onClose={setOpenProvider} /> <Button size="iconXs" disabled={isAiWorking || !prompt.trim()} onClick={() => callAi()} > <ArrowUp className="size-4" /> </Button> </div> </div> <LoginModal open={open} onClose={() => setOpen(false)} html={html} /> <ProModal html={html} open={openProModal} onClose={() => setOpenProModal(false)} /> </div> <audio ref={audio} id="audio" className="hidden"> <source src="/success.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio> </> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import { useState } from "react";import { Paintbrush } from "lucide-react";import { toast } from "sonner";
import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger,} from "@/components/ui/popover";import { Input } from "@/components/ui/input";import Loading from "@/components/loading";
export function ReImagine({ onRedesign,}: { onRedesign: (md: string) => void;}) { const [url, setUrl] = useState<string>(""); const [open, setOpen] = useState(false); const [isLoading, setIsLoading] = useState(false);
const checkIfUrlIsValid = (url: string) => { const urlPattern = new RegExp( /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/, "i" ); return urlPattern.test(url); };
const handleClick = async () => { if (!url) { toast.error("Please enter a URL."); return; } if (!checkIfUrlIsValid(url)) { toast.error("Please enter a valid URL."); return; } // Here you would typically handle the re-design logic setIsLoading(true); const request = await fetch("/api/re-design", { method: "POST", body: JSON.stringify({ url }), headers: { "Content-Type": "application/json", }, }); const response = await request.json(); if (response.ok) { setOpen(false); setUrl(""); onRedesign(response.markdown); toast.success("DeepSite is redesigning your site! Let him cook... 🔥"); } else { toast.error(response.message || "Failed to redesign the site."); } setIsLoading(false); };
return ( <Popover open={open} onOpenChange={setOpen}> <form> <PopoverTrigger asChild> <Button size="iconXs" variant="outline" className="!border-neutral-600 !text-neutral-400 !hover:!border-neutral-500 hover:!text-neutral-300" > <Paintbrush className="size-4" /> </Button> </PopoverTrigger> <PopoverContent align="start" className="!rounded-2xl !p-0 !bg-white !border-neutral-100 min-w-xs text-center overflow-hidden" > <header className="bg-neutral-50 p-6 border-b border-neutral-200/60"> <div className="flex items-center justify-center -space-x-4 mb-3"> <div className="size-9 rounded-full bg-pink-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 🎨 </div> <div className="size-11 rounded-full bg-amber-200 shadow-2xl flex items-center justify-center text-2xl z-2"> 🥳 </div> <div className="size-9 rounded-full bg-sky-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 💎 </div> </div> <p className="text-xl font-semibold text-neutral-950"> Redesign your Site! </p> <p className="text-sm text-neutral-500 mt-1.5"> Try our new Redesign feature to give your site a fresh look. </p> </header> <main className="space-y-4 p-6"> <div> <p className="text-sm text-neutral-700 mb-2"> Enter your website URL to get started: </p> <Input type="text" placeholder="https://example.com" value={url} onChange={(e) => setUrl(e.target.value)} onBlur={(e) => { const inputUrl = e.target.value.trim(); if (!inputUrl) { setUrl(""); return; } if (!checkIfUrlIsValid(inputUrl)) { toast.error("Please enter a valid URL."); return; } setUrl(inputUrl); }} className="!bg-white !border-neutral-300 !text-neutral-800 !placeholder:text-neutral-400 selection:!bg-blue-100" /> </div> <div> <p className="text-sm text-neutral-700 mb-2"> Then, let's redesign it! </p> <Button variant="black" onClick={handleClick} className="relative w-full" disabled={isLoading} > Redesign <Paintbrush className="size-4" /> {isLoading && <Loading className="ml-2 size-4 animate-spin" />} </Button> </div> </main> </PopoverContent> </form> </Popover> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import classNames from "classnames";import { PiGearSixFill } from "react-icons/pi";import { RiCheckboxCircleFill } from "react-icons/ri";
import { Popover, PopoverContent, PopoverTrigger,} from "@/components/ui/popover";import { PROVIDERS, MODELS } from "@/lib/providers";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue,} from "@/components/ui/select";import { useMemo } from "react";import { useUpdateEffect } from "react-use";import Image from "next/image";
export function Settings({ open, onClose, provider, model, error, isFollowUp = false, onChange, onModelChange,}: { open: boolean; provider: string; model: string; error?: string; isFollowUp?: boolean; onClose: React.Dispatch<React.SetStateAction<boolean>>; onChange: (provider: string) => void; onModelChange: (model: string) => void;}) { const modelAvailableProviders = useMemo(() => { const availableProviders = MODELS.find( (m: { value: string }) => m.value === model )?.providers; if (!availableProviders) return Object.keys(PROVIDERS); return Object.keys(PROVIDERS).filter((id) => availableProviders.includes(id) ); }, [model]);
useUpdateEffect(() => { if (provider !== "auto" && !modelAvailableProviders.includes(provider)) { onChange("auto"); } }, [model, provider]);
return ( <div className=""> <Popover open={open} onOpenChange={onClose}> <PopoverTrigger asChild> <Button variant="black" size="sm"> <PiGearSixFill className="size-4" /> Settings </Button> </PopoverTrigger> <PopoverContent className="!rounded-2xl p-0 !w-96 overflow-hidden !bg-neutral-900" align="center" > <header className="flex items-center justify-center text-sm px-4 py-3 border-b gap-2 bg-neutral-950 border-neutral-800 font-semibold text-neutral-200"> Customize Settings </header> <main className="px-4 pt-5 pb-6 space-y-5"> {/* <a href="https://huggingface.co/spaces/enzostvs/deepsite/discussions/74" target="_blank" className="w-full flex items-center justify-between text-neutral-300 bg-neutral-300/15 border border-neutral-300/15 pl-4 p-1.5 rounded-full text-sm font-medium hover:brightness-95" > How to use it locally? <Button size="xs">See guide</Button> </a> */} {error !== "" && ( <p className="text-red-500 text-sm font-medium mb-2 flex items-center justify-between bg-red-500/10 p-2 rounded-md"> {error} </p> )} <label className="block"> <p className="text-neutral-300 text-sm mb-2.5"> Choose a DeepSeek model </p> <Select defaultValue={model} onValueChange={onModelChange}> <SelectTrigger className="w-full"> <SelectValue placeholder="Select a DeepSeek model" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>DeepSeek models</SelectLabel> {MODELS.map( ({ value, label, isNew = false, isThinker = false, }: { value: string; label: string; isNew?: boolean; isThinker?: boolean; }) => ( <SelectItem key={value} value={value} className="" disabled={isThinker && isFollowUp} > {label} {isNew && ( <span className="text-xs bg-gradient-to-br from-sky-400 to-sky-600 text-white rounded-full px-1.5 py-0.5"> New </span> )} </SelectItem> ) )} </SelectGroup> </SelectContent> </Select> </label> {isFollowUp && ( <div className="bg-amber-500/10 border-amber-500/10 p-3 text-xs text-amber-500 border rounded-lg"> Note: You can't use a Thinker model for follow-up requests. We automatically switch to the default model for you. </div> )} <div className="flex flex-col gap-3"> <div className="flex items-center justify-between"> <div> <p className="text-neutral-300 text-sm mb-1.5"> Use auto-provider </p> <p className="text-xs text-neutral-400/70"> We'll automatically select the best provider for you based on your prompt. </p> </div> <div className={classNames( "bg-neutral-700 rounded-full min-w-10 w-10 h-6 flex items-center justify-between p-1 cursor-pointer transition-all duration-200", { "!bg-sky-500": provider === "auto", } )} onClick={() => { const foundModel = MODELS.find( (m: { value: string }) => m.value === model ); if (provider === "auto" && foundModel?.autoProvider) { onChange(foundModel.autoProvider); } else { onChange("auto"); } }} > <div className={classNames( "w-4 h-4 rounded-full shadow-md transition-all duration-200 bg-neutral-200", { "translate-x-4": provider === "auto", } )} /> </div> </div> <label className="block"> <p className="text-neutral-300 text-sm mb-2"> Inference Provider </p> <div className="grid grid-cols-2 gap-1.5"> {modelAvailableProviders.map((id: string) => ( <Button key={id} variant={id === provider ? "default" : "secondary"} size="sm" onClick={() => { onChange(id); }} > <Image src={`/providers/${id}.svg`} alt={PROVIDERS[id as keyof typeof PROVIDERS].name} className="size-5 mr-2" width={20} height={20} /> {PROVIDERS[id as keyof typeof PROVIDERS].name} {id === provider && ( <RiCheckboxCircleFill className="ml-2 size-4 text-blue-500" /> )} </Button> ))} </div> </label> </div> </main> </PopoverContent> </Popover> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171/* eslint-disable @typescript-eslint/no-explicit-any */import { useState } from "react";import { toast } from "sonner";import Image from "next/image";import { useRouter } from "next/navigation";import { MdSave } from "react-icons/md";import { Rocket } from "lucide-react";
import SpaceIcon from "@/assets/space.svg";import Loading from "@/components/loading";import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger,} from "@/components/ui/popover";import { Input } from "@/components/ui/input";import { api } from "@/lib/api";import { LoginModal } from "@/components/login-modal";import { useUser } from "@/hooks/useUser";
export function DeployButton({ html, prompts,}: { html: string; prompts: string[];}) { const router = useRouter(); const { user } = useUser(); const [loading, setLoading] = useState(false); const [open, setOpen] = useState(false);
const [config, setConfig] = useState({ title: "", });
const createSpace = async () => { if (!config.title) { toast.error("Please enter a title for your space."); return; } setLoading(true);
try { const res = await api.post("/me/projects", { title: config.title, html, prompts, }); if (res.data.ok) { router.push(`/projects/${res.data.path}?deploy=true`); } else { toast.error(res?.data?.error || "Failed to create space"); } } catch (err: any) { toast.error(err.response?.data?.error || err.message); } finally { setLoading(false); } };
return ( <div className="flex items-center justify-end gap-5"> <div className="relative flex items-center justify-end"> {user?.id ? ( <Popover> <PopoverTrigger asChild> <div> <Button variant="sky" className="max-lg:hidden !px-4"> <MdSave className="size-4" /> Save your Project </Button> <Button variant="sky" size="sm" className="lg:hidden"> Save </Button> </div> </PopoverTrigger> <PopoverContent className="!rounded-2xl !p-0 !bg-white !border-neutral-200 min-w-xs text-center overflow-hidden" align="end" > <header className="bg-neutral-50 p-6 border-b border-neutral-200/60"> <div className="flex items-center justify-center -space-x-4 mb-3"> <div className="size-9 rounded-full bg-amber-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 🚀 </div> <div className="size-11 rounded-full bg-red-200 shadow-2xl flex items-center justify-center z-2"> <Image src={SpaceIcon} alt="Space Icon" className="size-7" /> </div> <div className="size-9 rounded-full bg-sky-200 shadow-2xs flex items-center justify-center text-xl opacity-50"> 👻 </div> </div> <p className="text-xl font-semibold text-neutral-950"> Deploy your Project! </p> <p className="text-sm text-neutral-500 mt-1.5"> Deploy your project to a space on the Hub. Spaces are a way to share your project with the world. </p> </header> <main className="space-y-4 p-6"> <div> <p className="text-sm text-neutral-700 mb-2"> Choose a title for your space: </p> <Input type="text" placeholder="My Awesome Website" value={config.title} onChange={(e) => setConfig({ ...config, title: e.target.value }) } className="!bg-white !border-neutral-300 !text-neutral-800 !placeholder:text-neutral-400 selection:!bg-blue-100" /> </div> <div> <p className="text-sm text-neutral-700 mb-2"> Then, let's deploy it! </p> <Button variant="black" onClick={createSpace} className="relative w-full" disabled={loading} > Deploy <Rocket className="size-4" /> {loading && ( <Loading className="ml-2 size-4 animate-spin" /> )} </Button> </div> </main> </PopoverContent> </Popover> ) : ( <> <Button variant="sky" className="max-lg:hidden !px-4" onClick={() => setOpen(true)} > <MdSave className="size-4" /> Save your Project </Button> <Button variant="sky" size="sm" className="lg:hidden" onClick={() => setOpen(true)} > Save </Button> </> )} <LoginModal open={open} onClose={() => setOpen(false)} html={html} title="Log In to save your Project" description="Log In through your Hugging Face account to save your project and increase your monthly free limit." /> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import classNames from "classnames";import { FaMobileAlt } from "react-icons/fa";import { RefreshCcw, SparkleIcon } from "lucide-react";import { FaLaptopCode } from "react-icons/fa6";import { HtmlHistory } from "@/types";import { Button } from "@/components/ui/button";import { MdAdd } from "react-icons/md";import { History } from "@/components/editor/history";import { UserMenu } from "@/components/user-menu";import { useUser } from "@/hooks/useUser";
const DEVICES = [ { name: "desktop", icon: FaLaptopCode, }, { name: "mobile", icon: FaMobileAlt, },];
export function Footer({ onReset, htmlHistory, setHtml, device, setDevice, iframeRef,}: { onReset: () => void; htmlHistory?: HtmlHistory[]; device: "desktop" | "mobile"; setHtml: (html: string) => void; iframeRef?: React.RefObject<HTMLIFrameElement | null>; setDevice: React.Dispatch<React.SetStateAction<"desktop" | "mobile">>;}) { const { user } = useUser();
const handleRefreshIframe = () => { if (iframeRef?.current) { const iframe = iframeRef.current; const content = iframe.srcdoc; iframe.srcdoc = ""; setTimeout(() => { iframe.srcdoc = content; }, 10); } };
return ( <footer className="border-t bg-slate-200 border-slate-300 dark:bg-neutral-950 dark:border-neutral-800 px-3 py-2 flex items-center justify-between sticky bottom-0 z-20"> <div className="flex items-center gap-2"> {user && (user?.isLocalUse ? ( <> <div className="max-w-max bg-amber-500/10 rounded-full px-3 py-1 text-amber-500 border border-amber-500/20 text-sm font-semibold"> Local Usage </div> </> ) : ( <UserMenu /> ))} {user && <p className="text-neutral-700">|</p>} <Button size="sm" variant="secondary" onClick={onReset}> <MdAdd className="text-sm" /> <span>New Project</span> </Button> {htmlHistory && htmlHistory.length > 0 && ( <> <p className="text-neutral-700">|</p> <History history={htmlHistory} setHtml={setHtml} /> </> )} </div> <div className="flex justify-end items-center gap-2.5"> <a href="https://huggingface.co/spaces/victor/deepsite-gallery" target="_blank" > <Button size="sm" variant="ghost"> <SparkleIcon className="size-3.5" /> <span className="max-lg:hidden">DeepSite Gallery</span> </Button> </a> <Button size="sm" variant="default" onClick={handleRefreshIframe}> <RefreshCcw className="size-3.5" /> <span className="max-lg:hidden">Refresh Preview</span> </Button> <div className="flex items-center rounded-full p-0.5 bg-neutral-700/70 relative overflow-hidden z-0 max-lg:hidden gap-0.5"> <div className={classNames( "absolute left-0.5 top-0.5 rounded-full bg-white size-7 -z-[1] transition-all duration-200", { "translate-x-[calc(100%+2px)]": device === "mobile", } )} /> {DEVICES.map((deviceItem) => ( <button key={deviceItem.name} className={classNames( "rounded-full text-neutral-300 size-7 flex items-center justify-center cursor-pointer", { "!text-black": device === deviceItem.name, "hover:bg-neutral-800": device !== deviceItem.name, } )} onClick={() => setDevice(deviceItem.name as "desktop" | "mobile")} > <deviceItem.icon className="text-sm" /> </button> ))} </div> </div> </footer> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { ReactNode } from "react";import { Eye, MessageCircleCode } from "lucide-react";
import Logo from "@/assets/logo.svg";
import { Button } from "@/components/ui/button";import classNames from "classnames";import Image from "next/image";
const TABS = [ { value: "chat", label: "Chat", icon: MessageCircleCode, }, { value: "preview", label: "Preview", icon: Eye, },];
export function Header({ tab, onNewTab, children,}: { tab: string; onNewTab: (tab: string) => void; children?: ReactNode;}) { return ( <header className="border-b bg-slate-200 border-slate-300 dark:bg-neutral-950 dark:border-neutral-800 px-3 lg:px-6 py-2 grid grid-cols-3 sticky top-0 z-20"> <div className="flex items-center justify-start gap-3"> <h1 className="text-neutral-900 dark:text-white text-lg lg:text-xl font-bold flex items-center justify-start"> <Image src={Logo} alt="DeepSite Logo" className="size-6 lg:size-8 mr-2 invert-100 dark:invert-0" /> <p className="max-md:hidden flex items-center justify-start"> DeepSite <span className="font-mono bg-gradient-to-br from-sky-500 to-emerald-500 text-neutral-950 rounded-full text-xs ml-2 px-1.5 py-0.5"> {" "} v2 </span> </p> </h1> </div> <div className="flex items-center justify-center gap-1"> {TABS.map((item) => ( <Button key={item.value} variant={tab === item.value ? "secondary" : "ghost"} className={classNames("", { "opacity-60": tab !== item.value, })} size="sm" onClick={() => onNewTab(item.value)} > <item.icon className="size-4" /> <span className="hidden md:inline">{item.label}</span> </Button> ))} </div> <div className="flex items-center justify-end gap-3">{children}</div> </header> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { HtmlHistory } from "@/types";import { Popover, PopoverContent, PopoverTrigger,} from "@/components/ui/popover";import { Button } from "@/components/ui/button";
export function History({ history, setHtml,}: { history: HtmlHistory[]; setHtml: (html: string) => void;}) { return ( <Popover> <PopoverTrigger asChild> <Button variant="ghost" size="sm" className="max-lg:hidden"> {history?.length} edit{history.length !== 1 ? "s" : ""} </Button> </PopoverTrigger> <PopoverContent className="!rounded-2xl !p-0 overflow-hidden !bg-neutral-900" align="start" > <header className="text-sm px-4 py-3 border-b gap-2 bg-neutral-950 border-neutral-800 font-semibold text-neutral-200"> History </header> <main className="px-4 space-y-3"> <ul className="max-h-[250px] overflow-y-auto"> {history?.map((item, index) => ( <li key={index} className="text-gray-300 text-xs py-2 border-b border-gray-800 last:border-0 flex items-center justify-between gap-2" > <div className=""> <span className="line-clamp-1">{item.prompt}</span> <span className="text-gray-500 text-[10px]"> {new Date(item.createdAt).toLocaleDateString("en-US", { month: "2-digit", day: "2-digit", year: "2-digit", }) + " " + new Date(item.createdAt).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, })} </span> </div> <button className="bg-pink-500 text-white text-xs font-medium rounded-md px-2 py-1 transition-all duration-100 hover:bg-pink-600 cursor-pointer" onClick={() => { setHtml(item.html); }} > Select </button> </li> ))} </ul> </main> </PopoverContent> </Popover> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311"use client";import { useRef, useState } from "react";import { toast } from "sonner";import { editor } from "monaco-editor";import Editor from "@monaco-editor/react";import { CopyIcon } from "lucide-react";import { useCopyToClipboard, useEvent, useLocalStorage, useMount, useUnmount, useUpdateEffect,} from "react-use";import classNames from "classnames";import { useRouter, useSearchParams } from "next/navigation";
import { Header } from "@/components/editor/header";import { Footer } from "@/components/editor/footer";import { defaultHTML } from "@/lib/consts";import { Preview } from "@/components/editor/preview";import { useEditor } from "@/hooks/useEditor";import { AskAI } from "@/components/editor/ask-ai";import { DeployButton } from "./deploy-button";import { Project } from "@/types";import { SaveButton } from "./save-button";
export const AppEditor = ({ project }: { project?: Project | null }) => { const [htmlStorage, , removeHtmlStorage] = useLocalStorage("html_content"); const [, copyToClipboard] = useCopyToClipboard(); const { html, setHtml, htmlHistory, setHtmlHistory, prompts, setPrompts } = useEditor(project?.html ?? (htmlStorage as string) ?? defaultHTML); // get query params from URL const searchParams = useSearchParams(); const router = useRouter(); const deploy = searchParams.get("deploy") === "true";
const iframeRef = useRef<HTMLIFrameElement | null>(null); const preview = useRef<HTMLDivElement>(null); const editor = useRef<HTMLDivElement>(null); const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null); const resizer = useRef<HTMLDivElement>(null); // eslint-disable-next-line @typescript-eslint/no-explicit-any const monacoRef = useRef<any>(null);
const [currentTab, setCurrentTab] = useState("chat"); const [device, setDevice] = useState<"desktop" | "mobile">("desktop"); const [isResizing, setIsResizing] = useState(false); const [isAiWorking, setIsAiWorking] = useState(false);
/** * Resets the layout based on screen size * - For desktop: Sets editor to 1/3 width and preview to 2/3 * - For mobile: Removes inline styles to let CSS handle it */ const resetLayout = () => { if (!editor.current || !preview.current) return;
// lg breakpoint is 1024px based on useBreakpoint definition and Tailwind defaults if (window.innerWidth >= 1024) { // Set initial 1/3 - 2/3 sizes for large screens, accounting for resizer width const resizerWidth = resizer.current?.offsetWidth ?? 8; // w-2 = 0.5rem = 8px const availableWidth = window.innerWidth - resizerWidth; const initialEditorWidth = availableWidth / 3; // Editor takes 1/3 of space const initialPreviewWidth = availableWidth - initialEditorWidth; // Preview takes 2/3 editor.current.style.width = `${initialEditorWidth}px`; preview.current.style.width = `${initialPreviewWidth}px`; } else { // Remove inline styles for smaller screens, let CSS flex-col handle it editor.current.style.width = ""; preview.current.style.width = ""; } };
/** * Handles resizing when the user drags the resizer * Ensures minimum widths are maintained for both panels */ const handleResize = (e: MouseEvent) => { if (!editor.current || !preview.current || !resizer.current) return;
const resizerWidth = resizer.current.offsetWidth; const minWidth = 100; // Minimum width for editor/preview const maxWidth = window.innerWidth - resizerWidth - minWidth;
const editorWidth = e.clientX; const clampedEditorWidth = Math.max( minWidth, Math.min(editorWidth, maxWidth) ); const calculatedPreviewWidth = window.innerWidth - clampedEditorWidth - resizerWidth;
editor.current.style.width = `${clampedEditorWidth}px`; preview.current.style.width = `${calculatedPreviewWidth}px`; };
const handleMouseDown = () => { setIsResizing(true); document.addEventListener("mousemove", handleResize); document.addEventListener("mouseup", handleMouseUp); };
const handleMouseUp = () => { setIsResizing(false); document.removeEventListener("mousemove", handleResize); document.removeEventListener("mouseup", handleMouseUp); };
useMount(() => { if (deploy && project?._id) { toast.success("Your project is deployed! 🎉", { action: { label: "See Project", onClick: () => { window.open( `https://huggingface.co/spaces/${project?.space_id}`, "_blank" ); }, }, }); router.replace(`/projects/${project?.space_id}`); } if (htmlStorage) { removeHtmlStorage(); toast.warning("Previous HTML content restored from local storage."); }
resetLayout(); if (!resizer.current) return; resizer.current.addEventListener("mousedown", handleMouseDown); window.addEventListener("resize", resetLayout); }); useUnmount(() => { document.removeEventListener("mousemove", handleResize); document.removeEventListener("mouseup", handleMouseUp); if (resizer.current) { resizer.current.removeEventListener("mousedown", handleMouseDown); } window.removeEventListener("resize", resetLayout); });
// Prevent accidental navigation away when AI is working or content has changed useEvent("beforeunload", (e) => { if (isAiWorking || html !== defaultHTML) { e.preventDefault(); return ""; } });
useUpdateEffect(() => { if (currentTab === "chat") { // Reset editor width when switching to reasoning tab resetLayout(); // re-add the event listener for resizing if (resizer.current) { resizer.current.addEventListener("mousedown", handleMouseDown); } } else { if (preview.current) { // Reset preview width when switching to preview tab preview.current.style.width = "100%"; } } }, [currentTab]);
return ( <section className="h-screen bg-slate-100 dark:bg-neutral-950 flex flex-col"> <Header tab={currentTab} onNewTab={setCurrentTab}> {project?._id ? ( <SaveButton html={html} prompts={prompts} /> ) : ( <DeployButton html={html} prompts={prompts} /> )} </Header> <main className="bg-neutral-950 flex-1 max-lg:flex-col flex w-full"> {currentTab === "chat" && ( <> <div ref={editor} className="relative"> <CopyIcon className="size-4 absolute top-2 right-5 text-neutral-500 hover:text-neutral-300 z-2 cursor-pointer" onClick={() => { copyToClipboard(html); toast.success("HTML copied to clipboard!"); }} /> <Editor language="html" theme="vs-dark" className={classNames( "h-[calc(100dvh-98px)] lg:h-full bg-neutral-900 transition-all duration-200 ", { "pointer-events-none": isAiWorking, } )} options={{ colorDecorators: true, fontLigatures: true, theme: "vs-dark", minimap: { enabled: false }, scrollbar: { horizontal: "hidden", }, }} value={html} onChange={(value) => { const newValue = value ?? ""; setHtml(newValue); }} onMount={(editor, monaco) => { editorRef.current = editor; monacoRef.current = monaco; }} /> <AskAI html={html} setHtml={(newHtml: string) => { setHtml(newHtml); }} htmlHistory={htmlHistory} onSuccess={( finalHtml: string, p: string, updatedLines?: number[][] ) => { const currentHistory = [...htmlHistory]; currentHistory.unshift({ html: finalHtml, createdAt: new Date(), prompt: p, }); setHtmlHistory(currentHistory); // if xs or sm if (window.innerWidth <= 1024) { setCurrentTab("preview"); } if (updatedLines && updatedLines?.length > 0) { const decorations = updatedLines.map((line) => ({ range: new monacoRef.current.Range( line[0], 1, line[1], 1 ), options: { inlineClassName: "matched-line", }, })); setTimeout(() => { editorRef?.current ?.getModel() ?.deltaDecorations([], decorations);
editorRef.current?.revealLine(updatedLines[0][0]); }, 100); } }} isAiWorking={isAiWorking} setisAiWorking={setIsAiWorking} onNewPrompt={(prompt: string) => { setPrompts((prev) => [...prev, prompt]); }} onScrollToBottom={() => { editorRef.current?.revealLine( editorRef.current?.getModel()?.getLineCount() ?? 0 ); }} /> </div> <div ref={resizer} className="bg-neutral-800 hover:bg-sky-500 active:bg-sky-500 w-1.5 cursor-col-resize h-full max-lg:hidden" /> </> )} <Preview html={html} isResizing={isResizing} isAiWorking={isAiWorking} ref={preview} device={device} currentTab={currentTab} iframeRef={iframeRef} /> </main> <Footer onReset={() => { if (isAiWorking) { toast.warning("Please wait for the AI to finish working."); return; } if ( window.confirm("You're about to reset the editor. Are you sure?") ) { setHtml(defaultHTML); removeHtmlStorage(); editorRef.current?.revealLine( editorRef.current?.getModel()?.getLineCount() ?? 0 ); } }} htmlHistory={htmlHistory} setHtml={setHtml} iframeRef={iframeRef} device={device} setDevice={setDevice} /> </section> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"use client";import classNames from "classnames";import { toast } from "sonner";
import { cn } from "@/lib/utils";import { GridPattern } from "@/components/magic-ui/grid-pattern";
export const Preview = ({ html, isResizing, isAiWorking, ref, device, currentTab, iframeRef,}: { html: string; isResizing: boolean; isAiWorking: boolean; ref: React.RefObject<HTMLDivElement | null>; iframeRef?: React.RefObject<HTMLIFrameElement | null>; device: "desktop" | "mobile"; currentTab: string;}) => { return ( <div ref={ref} className={classNames( "w-full border-l border-gray-900 h-full relative z-0 flex items-center justify-center", { "lg:p-4": currentTab !== "preview", } )} onClick={(e) => { if (isAiWorking) { e.preventDefault(); e.stopPropagation(); toast.warning("Please wait for the AI to finish working."); } }} > <GridPattern x={-1} y={-1} strokeDasharray={"4 2"} className={cn( "[mask-image:radial-gradient(900px_circle_at_center,white,transparent)]" )} /> <iframe id="preview-iframe" ref={iframeRef} title="output" className={classNames( "w-full select-none transition-all duration-200 bg-black max-lg:h-full", { "pointer-events-none": isResizing || isAiWorking, "lg:max-w-md lg:mx-auto lg:h-[80dvh] lg:!rounded-[42px] lg:border-[8px] lg:border-neutral-700 lg:shadow-2xl": device === "mobile", "h-full": device === "desktop", "lg:border-[8px] lg:border-neutral-700 lg:shadow-2xl lg:rounded-[24px]": currentTab !== "preview" && device === "desktop", } )} srcDoc={html} onLoad={() => { if (iframeRef?.current?.contentWindow?.document?.body) { iframeRef.current.contentWindow.document.body.scrollIntoView({ block: isAiWorking ? "end" : "start", inline: "nearest", behavior: isAiWorking ? "instant" : "smooth", }); } }} /> </div> );};12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576/* eslint-disable @typescript-eslint/no-explicit-any */import { useState } from "react";import { toast } from "sonner";import { MdSave } from "react-icons/md";import { useParams } from "next/navigation";
import Loading from "@/components/loading";import { Button } from "@/components/ui/button";import { api } from "@/lib/api";
export function SaveButton({ html, prompts,}: { html: string; prompts: string[];}) { // get params from URL const { namespace, repoId } = useParams<{ namespace: string; repoId: string; }>(); const [loading, setLoading] = useState(false);
const updateSpace = async () => { setLoading(true);
try { const res = await api.put(`/me/projects/${namespace}/${repoId}`, { html, prompts, }); if (res.data.ok) { toast.success("Your space is updated! 🎉", { action: { label: "See Space", onClick: () => { window.open( `https://huggingface.co/spaces/${namespace}/${repoId}`, "_blank" ); }, }, }); } else { toast.error(res?.data?.error || "Failed to update space"); } } catch (err: any) { toast.error(err.response?.data?.error || err.message); } finally { setLoading(false); } };
return ( <> <Button variant="sky" className="max-lg:hidden !px-4" onClick={updateSpace} > <MdSave className="size-4" /> Save your Project{" "} {loading && <Loading className="ml-2 size-4 animate-spin" />} </Button> <Button variant="sky" size="sm" className="lg:hidden" onClick={updateSpace} > Save {loading && <Loading className="ml-2 size-4 animate-spin" />} </Button> </> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import { TiUserAdd } from "react-icons/ti";import { Link } from "lucide-react";import { FaXTwitter } from "react-icons/fa6";import { useCopyToClipboard } from "react-use";import { toast } from "sonner";
import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogTitle, DialogTrigger,} from "@/components/ui/dialog";
export function InviteFriends() { // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, copyToClipboard] = useCopyToClipboard();
return ( <Dialog> <form> <DialogTrigger asChild> <Button size="iconXs" variant="outline" className="!border-neutral-600 !text-neutral-400 !hover:!border-neutral-500 hover:!text-neutral-300" > <TiUserAdd className="size-4" /> </Button> </DialogTrigger> <DialogContent className="sm:max-w-lg lg:!p-8 !rounded-3xl !bg-white !border-neutral-100"> <DialogTitle className="hidden" /> <main> <div className="flex items-center justify-start -space-x-4 mb-5"> <div className="size-11 rounded-full bg-pink-300 shadow-2xs flex items-center justify-center text-2xl"> 😎 </div> <div className="size-11 rounded-full bg-amber-300 shadow-2xs flex items-center justify-center text-2xl z-2"> 😇 </div> <div className="size-11 rounded-full bg-sky-300 shadow-2xs flex items-center justify-center text-2xl"> 😜 </div> </div> <p className="text-xl font-semibold text-neutral-950 max-w-[200px]"> Invite your friends to join us! </p> <p className="text-sm text-neutral-500 mt-2 max-w-sm"> Support us and share the love and let them know about our awesome platform. </p> <div className="mt-4 space-x-3.5"> <a href="https://x.com/intent/post?url=https://enzostvs-deepsite.hf.space/&text=Checkout%20this%20awesome%20Ai%20Tool!%20Vibe%20coding%20has%20never%20been%20so%20easy✨" target="_blank" rel="noopener noreferrer" > <Button variant="lightGray" size="sm" className="!text-neutral-700" > <FaXTwitter className="size-4" /> Share on </Button> </a> <Button variant="lightGray" size="sm" className="!text-neutral-700" onClick={() => { copyToClipboard("https://enzostvs-deepsite.hf.space/"); toast.success("Invite link copied to clipboard!"); }} > <Link className="size-4" /> Copy Invite Link </Button> </div> </main> </DialogContent> </form> </Dialog> );}1234567891011121314151617181920212223242526272829303132333435363738394041import classNames from "classnames";
function Loading({ overlay = true, className,}: { overlay?: boolean; className?: string;}) { return ( <div className={classNames("", { "absolute left-0 top-0 h-full w-full flex items-center justify-center z-20 bg-black/50 rounded-full": overlay, })} > <svg className={`size-5 animate-spin text-white ${className}`} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" > <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" ></circle> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" ></path> </svg> </div> );}
export default Loading;12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { useLocalStorage } from "react-use";import { defaultHTML } from "@/lib/consts";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";import { useUser } from "@/hooks/useUser";
export const LoginModal = ({ open, html, onClose, title = "Log In to use DeepSite for free", description = "Log In through your Hugging Face account to continue using DeepSite and increase your monthly free limit.",}: { open: boolean; html: string; onClose: React.Dispatch<React.SetStateAction<boolean>>; title?: string; description?: string;}) => { const { openLoginWindow } = useUser(); const [, setStorage] = useLocalStorage("html_content"); const handleClick = async () => { if (html !== defaultHTML) { setStorage(html); } openLoginWindow(); onClose(false); }; return ( <Dialog open={open} onOpenChange={onClose}> <DialogContent className="sm:max-w-lg lg:!p-8 !rounded-3xl !bg-white !border-neutral-100"> <DialogTitle className="hidden" /> <main className="flex flex-col items-start text-left relative pt-2"> <div className="flex items-center justify-start -space-x-4 mb-5"> <div className="size-14 rounded-full bg-pink-200 shadow-2xs flex items-center justify-center text-3xl opacity-50"> 💪 </div> <div className="size-16 rounded-full bg-amber-200 shadow-2xl flex items-center justify-center text-4xl z-2"> 😎 </div> <div className="size-14 rounded-full bg-sky-200 shadow-2xs flex items-center justify-center text-3xl opacity-50"> 🙌 </div> </div> <p className="text-2xl font-bold text-neutral-950">{title}</p> <p className="text-neutral-500 text-base mt-2 max-w-sm"> {description} </p> <Button variant="black" size="lg" className="w-full !text-base !h-11 mt-8" onClick={handleClick} > Log In to Continue </Button> </main> </DialogContent> </Dialog> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { useId } from "react";import { cn } from "@/lib/utils";
interface GridPatternProps extends React.SVGProps<SVGSVGElement> { width?: number; height?: number; x?: number; y?: number; squares?: Array<[x: number, y: number]>; strokeDasharray?: string; className?: string; [key: string]: unknown;}
export function GridPattern({ width = 40, height = 40, x = -1, y = -1, strokeDasharray = "0", squares, className, ...props}: GridPatternProps) { const id = useId();
return ( <svg aria-hidden="true" className={cn( "pointer-events-none absolute inset-0 h-full w-full fill-gray-400/30 stroke-neutral-700 -z-[1]", className )} {...props} > <defs> <pattern id={id} width={width} height={height} patternUnits="userSpaceOnUse" x={x} y={y} > <path d={`M.5 ${height}V.5H${width}`} fill="none" strokeDasharray={strokeDasharray} /> </pattern> </defs> <rect width="100%" height="100%" strokeWidth={0} fill={`url(#${id})`} /> {squares && ( <svg x={x} y={y} className="overflow-visible"> {squares.map(([x, y]) => ( <rect strokeWidth="0" key={`${x}-${y}`} width={width - 1} height={height - 1} x={x * width + 1} y={y * height + 1} /> ))} </svg> )} </svg> );}1234567891011121314151617181920212223242526272829303132333435363738394041"use client";import { useUser } from "@/hooks/useUser";import { Project } from "@/types";import { redirect } from "next/navigation";import { ProjectCard } from "./project-card";import { Plus } from "lucide-react";import Link from "next/link";
export function MyProjects({ projects }: { projects: Project[] }) { const { user } = useUser(); if (!user) { redirect("/"); } return ( <> <section className="max-w-[86rem] py-12 px-4 mx-auto"> <div className="text-left"> <h1 className="text-3xl font-bold text-white"> <span className="capitalize">{user.fullname}</span>'s DeepSite Projects </h1> <p className="text-muted-foreground text-base mt-1 max-w-xl"> Create, manage, and explore your DeepSite projects. </p> </div> <div className="mt-8 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8"> <Link href="/projects/new" className="bg-neutral-900 rounded-xl h-44 flex items-center justify-center text-neutral-300 border border-neutral-800 hover:brightness-110 transition-all duration-200" > <Plus className="size-5 mr-1.5" /> Create Project </Link> {projects.map((project: Project) => ( <ProjectCard key={project._id} project={project} /> ))} </div> </section> </> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import Link from "next/link";import { formatDistance } from "date-fns";import { EllipsisVertical, Settings } from "lucide-react";
import { Project } from "@/types";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";
export function ProjectCard({ project }: { project: Project }) { return ( <div className="text-neutral-200 space-y-4 group cursor-pointer"> <Link href={`/projects/${project.space_id}`} className="relative bg-neutral-900 rounded-2xl overflow-hidden h-44 w-full flex items-center justify-end flex-col px-3 border border-neutral-800" > <iframe src={`https://${project.space_id.replace("/", "-")}.static.hf.space/`} frameBorder="0" className="absolute inset-0 w-full h-full top-0 left-0 group-hover:brightness-75 transition-all duration-200 pointer-events-none" ></iframe>
<Button variant="default" className="w-full transition-all duration-200 translate-y-full group-hover:-translate-y-3" > Open project </Button> </Link> <div className="flex items-start justify-between gap-3"> <div> <p className="text-neutral-200 text-base font-semibold line-clamp-1"> {project.space_id} </p> <p className="text-sm text-neutral-500"> Updated{" "} {formatDistance( new Date(project._updatedAt || Date.now()), new Date(), { addSuffix: true, } )} </p> </div> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon"> <EllipsisVertical className="text-neutral-400 size-5 hover:text-neutral-300 transition-colors duration-200 cursor-pointer" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent className="w-56" align="start"> <DropdownMenuGroup> <a href={`https://huggingface.co/spaces/${project.space_id}/settings`} target="_blank" > <DropdownMenuItem> <Settings className="size-4 text-neutral-100" /> Project Settings </DropdownMenuItem> </a> </DropdownMenuGroup> </DropdownMenuContent> </DropdownMenu> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import { useLocalStorage } from "react-use";import { defaultHTML } from "@/lib/consts";import { Button } from "../ui/button";import { Dialog, DialogContent } from "../ui/dialog";import { CheckCheck } from "lucide-react";
export const ProModal = ({ open, html, onClose,}: { open: boolean; html: string; onClose: React.Dispatch<React.SetStateAction<boolean>>;}) => { const [, setStorage] = useLocalStorage("html_content"); const handleProClick = () => { if (html !== defaultHTML) { setStorage(html); } }; return ( <Dialog open={open} onOpenChange={onClose}> <DialogContent className="sm:max-w-lg lg:!p-8 !rounded-3xl !bg-white !border-neutral-100"> <main className="flex flex-col items-start text-left relative pt-2"> <div className="flex items-center justify-start -space-x-4 mb-5"> <div className="size-14 rounded-full bg-pink-200 shadow-2xs flex items-center justify-center text-3xl opacity-50"> 🚀 </div> <div className="size-16 rounded-full bg-amber-200 shadow-2xl flex items-center justify-center text-4xl z-2"> 🤩 </div> <div className="size-14 rounded-full bg-sky-200 shadow-2xs flex items-center justify-center text-3xl opacity-50"> 🥳 </div> </div> <p className="text-2xl font-bold text-neutral-950"> Only 9$ for unlimited access! </p> <p className="text-neutral-500 text-base mt-2 max-w-sm"> It seems like you have reached the monthly free limit of DeepSite. </p> <hr className="bg-neutral-200 w-full max-w-[150px] my-6" /> <p className="text-lg mt-3 text-neutral-900 font-semibold"> Upgrade to a <ProTag className="mx-1" /> Account, and unlock: </p> <ul className="mt-3 space-y-1 text-neutral-500"> <li className="text-sm space-x-2 flex items-center justify-start gap-2"> <CheckCheck className="text-emerald-500 size-4" /> DeepSite unlimited access to all Inference Providers </li> <li className="text-sm space-x-2 flex items-center justify-start gap-2"> <CheckCheck className="text-emerald-500 size-4" /> Get highest priority and 8x more quota on Spaces ZeroGPU </li> <li className="text-sm space-x-2 flex items-center justify-start gap-2"> <CheckCheck className="text-emerald-500 size-4" /> Activate Dataset Viewer on private datasets </li> <li className="text-sm space-x-2 flex items-center justify-start gap-2"> <CheckCheck className="text-emerald-500 size-4" /> Get exclusive early access to new features and updates </li> <li className="text-sm space-x-2 flex items-center justify-start gap-2"> <CheckCheck className="text-emerald-500 size-4" /> Get free credits across all Inference Providers </li> <li className="text-sm text-neutral-500 space-x-2 flex items-center justify-start gap-2 mt-3"> ... and much more! </li> </ul> <Button variant="black" size="lg" className="w-full !text-base !h-11 mt-8" onClick={handleProClick} > Subscribe to PRO ($9/month) </Button> </main> </DialogContent> </Dialog> );};
const ProTag = ({ className }: { className?: string }) => ( <span className={`${className} bg-linear-to-br shadow-green-500/10 dark:shadow-green-500/20 inline-block -skew-x-12 border border-gray-200 from-pink-300 via-green-200 to-yellow-200 text-xs font-bold text-black shadow-lg rounded-md px-2.5 py-0.5`} > PRO </span>);export default ProModal;12345678910111213141516171819"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
export default function TanstackProvider({ children,}: { children: React.ReactNode;}) { const queryClient = new QueryClient();
return ( <QueryClientProvider client={queryClient}> {children} <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"use client";
import { useRef, useState } from "react";import Image from "next/image";import Link from "next/link";import { useMount, useUnmount } from "react-use";import classNames from "classnames";
import { Button } from "@/components/ui/button";import Logo from "@/assets/logo.svg";import { useUser } from "@/hooks/useUser";import { UserMenu } from "@/components/user-menu";
const navigationLinks = [ { name: "Create Website", href: "/projects/new", }, { name: "Features", href: "#features", }, { name: "Community", href: "#community", }, { name: "Deploy", href: "#deploy", },];
export default function Navigation() { const { openLoginWindow, user } = useUser(); const [hash, setHash] = useState("");
const selectorRef = useRef<HTMLDivElement>(null); const linksRef = useRef<HTMLLIElement[]>( new Array(navigationLinks.length).fill(null) ); const [isScrolled, setIsScrolled] = useState(false);
useMount(() => { const handleScroll = () => { const scrollTop = window.scrollY; setIsScrolled(scrollTop > 100); };
const initialHash = window.location.hash; if (initialHash) { setHash(initialHash); calculateSelectorPosition(initialHash); }
window.addEventListener("scroll", handleScroll); });
useUnmount(() => { window.removeEventListener("scroll", () => {}); });
const handleClick = (href: string) => { setHash(href); calculateSelectorPosition(href); };
const calculateSelectorPosition = (href: string) => { if (selectorRef.current && linksRef.current) { const index = navigationLinks.findIndex((l) => l.href === href); const targetLink = linksRef.current[index]; if (targetLink) { const targetRect = targetLink.getBoundingClientRect(); selectorRef.current.style.left = targetRect.left + "px"; selectorRef.current.style.width = targetRect.width + "px"; } } };
return ( <div className={classNames( "sticky top-0 z-10 transition-all duration-200 backdrop-blur-md", { "bg-black/30": isScrolled, } )} > <nav className="grid grid-cols-3 p-4 container mx-auto"> <Link href="/" className="flex items-center gap-1"> <Image src={Logo} className="w-9 mr-1" alt="DeepSite Logo" width={64} height={64} /> <p className="font-sans text-white text-xl font-bold">DeepSite</p> </Link> <ul className="flex items-center justify-center gap-6"> {navigationLinks.map((link) => ( <li key={link.name} ref={(el) => { const index = navigationLinks.findIndex( (l) => l.href === link.href ); if (el && linksRef.current[index] !== el) { linksRef.current[index] = el; } }} className="inline-block font-sans text-sm" > <Link href={link.href} className={classNames( "text-neutral-500 hover:text-primary transition-colors", { "text-primary": hash === link.href, } )} onClick={() => { handleClick(link.href); }} > {link.name} </Link> </li> ))} <div ref={selectorRef} className={classNames( "h-1 absolute bottom-4 transition-all duration-200 flex items-center justify-center", { "opacity-0": !hash, } )} > <div className="size-1 bg-white rounded-full" /> </div> </ul> <div className="flex items-center justify-end gap-2"> {user ? ( <UserMenu className="!pl-3 !pr-4 !py-2 !h-auto !rounded-lg" /> ) : ( <> <Button variant="link" size={"sm"} onClick={openLoginWindow}> Log In </Button> <Button size={"sm"}>Sign Up</Button> </> )} </div> </nav> </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041"use client";
import { ArrowUp } from "lucide-react";import { PiGearSixFill } from "react-icons/pi";import { TiUserAdd } from "react-icons/ti";
import { Button } from "@/components/ui/button";
export const AskAi = () => { return ( <div className="bg-neutral-800 border border-neutral-700 rounded-2xl ring-[4px] focus-within:ring-neutral-500/30 focus-within:border-neutral-600 ring-transparent group"> <textarea rows={3} className="w-full bg-transparent text-sm outline-none text-white placeholder:text-neutral-400 p-4 resize-none mb-1" placeholder="Ask DeepSite anything..." onChange={() => {}} onKeyDown={() => {}} /> <div className="flex items-center justify-between gap-2 px-4 pb-3"> <div className="flex-1 flex justify-start"> <Button size="iconXs" variant="outline" className="!border-neutral-600 !text-neutral-400 !hover:!border-neutral-500 hover:!text-neutral-300" > <TiUserAdd className="size-4" /> </Button> </div> <div className="flex items-center justify-end gap-2"> <Button variant="black" size="sm"> <PiGearSixFill className="size-4" /> Settings </Button> <Button size="iconXs"> <ArrowUp className="size-4" /> </Button> </div> </div> </div> );};1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"use client"
import * as React from "react"import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({ className, ...props}: React.ComponentProps<typeof AvatarPrimitive.Root>) { return ( <AvatarPrimitive.Root data-slot="avatar" className={cn( "relative flex size-8 shrink-0 overflow-hidden rounded-full", className )} {...props} /> )}
function AvatarImage({ className, ...props}: React.ComponentProps<typeof AvatarPrimitive.Image>) { return ( <AvatarPrimitive.Image data-slot="avatar-image" className={cn("aspect-square size-full", className)} {...props} /> )}
function AvatarFallback({ className, ...props}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) { return ( <AvatarPrimitive.Fallback data-slot="avatar-fallback" className={cn( "bg-muted flex size-full items-center justify-center rounded-full", className )} {...props} /> )}
export { Avatar, AvatarImage, AvatarFallback }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import * as React from "react";import { Slot } from "@radix-ui/react-slot";import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva( "inline-flex items-center cursor-pointer justify-center gap-2 whitespace-nowrap rounded-full text-sm font-sans font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", { variants: { variant: { default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", destructive: "bg-red-500 text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 [&_svg]:!text-white", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", lightGray: "bg-neutral-200/60 hover:bg-neutral-200", link: "text-primary underline-offset-4 hover:underline", ghostDarker: "text-white shadow-xs focus-visible:ring-black/40 bg-black/40 hover:bg-black/70", black: "bg-neutral-950 text-neutral-300 hover:brightness-110", sky: "bg-sky-500 text-white hover:brightness-110", }, size: { default: "h-9 px-4 py-2 has-[>svg]:px-3", sm: "h-8 rounded-full text-[13px] gap-1.5 px-3", lg: "h-10 rounded-full px-6 has-[>svg]:px-4", icon: "size-9", iconXs: "size-7", iconXss: "size-6", xs: "h-6 text-xs rounded-full pl-2 pr-2 gap-1", }, }, defaultVariants: { variant: "default", size: "default", }, });
function Button({ className, variant, size, asChild = false, ...props}: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & { asChild?: boolean; }) { const Comp = asChild ? Slot : "button";
return ( <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} /> );}
export { Button, buttonVariants };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"use client"
import * as React from "react"import * as DialogPrimitive from "@radix-ui/react-dialog"import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({ ...props}: React.ComponentProps<typeof DialogPrimitive.Root>) { return <DialogPrimitive.Root data-slot="dialog" {...props} />}
function DialogTrigger({ ...props}: React.ComponentProps<typeof DialogPrimitive.Trigger>) { return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />}
function DialogPortal({ ...props}: React.ComponentProps<typeof DialogPrimitive.Portal>) { return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />}
function DialogClose({ ...props}: React.ComponentProps<typeof DialogPrimitive.Close>) { return <DialogPrimitive.Close data-slot="dialog-close" {...props} />}
function DialogOverlay({ className, ...props}: React.ComponentProps<typeof DialogPrimitive.Overlay>) { return ( <DialogPrimitive.Overlay data-slot="dialog-overlay" className={cn( "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50", className )} {...props} /> )}
function DialogContent({ className, children, showCloseButton = true, ...props}: React.ComponentProps<typeof DialogPrimitive.Content> & { showCloseButton?: boolean}) { return ( <DialogPortal data-slot="dialog-portal"> <DialogOverlay /> <DialogPrimitive.Content data-slot="dialog-content" className={cn( "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg", className )} {...props} > {children} {showCloseButton && ( <DialogPrimitive.Close data-slot="dialog-close" className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4" > <XIcon /> <span className="sr-only">Close</span> </DialogPrimitive.Close> )} </DialogPrimitive.Content> </DialogPortal> )}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props} /> )}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="dialog-footer" className={cn( "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className )} {...props} /> )}
function DialogTitle({ className, ...props}: React.ComponentProps<typeof DialogPrimitive.Title>) { return ( <DialogPrimitive.Title data-slot="dialog-title" className={cn("text-lg leading-none font-semibold", className)} {...props} /> )}
function DialogDescription({ className, ...props}: React.ComponentProps<typeof DialogPrimitive.Description>) { return ( <DialogPrimitive.Description data-slot="dialog-description" className={cn("text-muted-foreground text-sm", className)} {...props} /> )}
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257"use client";
import * as React from "react";import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function DropdownMenu({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) { return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;}
function DropdownMenuPortal({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) { return ( <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} /> );}
function DropdownMenuTrigger({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) { return ( <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} /> );}
function DropdownMenuContent({ className, sideOffset = 4, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) { return ( <DropdownMenuPrimitive.Portal> <DropdownMenuPrimitive.Content data-slot="dropdown-menu-content" sideOffset={sideOffset} className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", className )} {...props} /> </DropdownMenuPrimitive.Portal> );}
function DropdownMenuGroup({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) { return ( <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} /> );}
function DropdownMenuItem({ className, inset, variant = "default", ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { inset?: boolean; variant?: "default" | "destructive";}) { return ( <DropdownMenuPrimitive.Item data-slot="dropdown-menu-item" data-inset={inset} data-variant={variant} className={cn( "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className )} {...props} /> );}
function DropdownMenuCheckboxItem({ className, children, checked, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) { return ( <DropdownMenuPrimitive.CheckboxItem data-slot="dropdown-menu-checkbox-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className )} checked={checked} {...props} > <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <DropdownMenuPrimitive.ItemIndicator> <CheckIcon className="size-4" /> </DropdownMenuPrimitive.ItemIndicator> </span> {children} </DropdownMenuPrimitive.CheckboxItem> );}
function DropdownMenuRadioGroup({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) { return ( <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} /> );}
function DropdownMenuRadioItem({ className, children, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) { return ( <DropdownMenuPrimitive.RadioItem data-slot="dropdown-menu-radio-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className )} {...props} > <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <DropdownMenuPrimitive.ItemIndicator> <CircleIcon className="size-2 fill-current" /> </DropdownMenuPrimitive.ItemIndicator> </span> {children} </DropdownMenuPrimitive.RadioItem> );}
function DropdownMenuLabel({ className, inset, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & { inset?: boolean;}) { return ( <DropdownMenuPrimitive.Label data-slot="dropdown-menu-label" data-inset={inset} className={cn( "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className )} {...props} /> );}
function DropdownMenuSeparator({ className, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) { return ( <DropdownMenuPrimitive.Separator data-slot="dropdown-menu-separator" className={cn("bg-border -mx-1 my-1 h-px", className)} {...props} /> );}
function DropdownMenuShortcut({ className, ...props}: React.ComponentProps<"span">) { return ( <span data-slot="dropdown-menu-shortcut" className={cn( "text-muted-foreground ml-auto text-xs tracking-widest", className )} {...props} /> );}
function DropdownMenuSub({ ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) { return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;}
function DropdownMenuSubTrigger({ className, inset, children, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & { inset?: boolean;}) { return ( <DropdownMenuPrimitive.SubTrigger data-slot="dropdown-menu-sub-trigger" data-inset={inset} className={cn( "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8", className )} {...props} > {children} <ChevronRightIcon className="ml-auto size-4" /> </DropdownMenuPrimitive.SubTrigger> );}
function DropdownMenuSubContent({ className, ...props}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) { return ( <DropdownMenuPrimitive.SubContent data-slot="dropdown-menu-sub-content" className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", className )} {...props} /> );}
export { DropdownMenu, DropdownMenuPortal, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuGroup, DropdownMenuLabel, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,};123456789101112131415161718192021import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) { return ( <input type={type} data-slot="input" className={cn( "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]", "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", className )} {...props} /> )}
export { Input }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"use client";
import * as React from "react";import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
function Popover({ ...props}: React.ComponentProps<typeof PopoverPrimitive.Root>) { return <PopoverPrimitive.Root data-slot="popover" {...props} />;}
function PopoverTrigger({ ...props}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) { return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;}
function PopoverContent({ className, align = "center", sideOffset = 4, ...props}: React.ComponentProps<typeof PopoverPrimitive.Content>) { return ( <PopoverPrimitive.Portal> <PopoverPrimitive.Content data-slot="popover-content" align={align} sideOffset={sideOffset} className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden", className )} {...props} /> </PopoverPrimitive.Portal> );}
function PopoverAnchor({ ...props}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) { return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"use client"
import * as React from "react"import * as SelectPrimitive from "@radix-ui/react-select"import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Select({ ...props}: React.ComponentProps<typeof SelectPrimitive.Root>) { return <SelectPrimitive.Root data-slot="select" {...props} />}
function SelectGroup({ ...props}: React.ComponentProps<typeof SelectPrimitive.Group>) { return <SelectPrimitive.Group data-slot="select-group" {...props} />}
function SelectValue({ ...props}: React.ComponentProps<typeof SelectPrimitive.Value>) { return <SelectPrimitive.Value data-slot="select-value" {...props} />}
function SelectTrigger({ className, size = "default", children, ...props}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { size?: "sm" | "default"}) { return ( <SelectPrimitive.Trigger data-slot="select-trigger" data-size={size} className={cn( "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className )} {...props} > {children} <SelectPrimitive.Icon asChild> <ChevronDownIcon className="size-4 opacity-50" /> </SelectPrimitive.Icon> </SelectPrimitive.Trigger> )}
function SelectContent({ className, children, position = "popper", ...props}: React.ComponentProps<typeof SelectPrimitive.Content>) { return ( <SelectPrimitive.Portal> <SelectPrimitive.Content data-slot="select-content" className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md", position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )} position={position} {...props} > <SelectScrollUpButton /> <SelectPrimitive.Viewport className={cn( "p-1", position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1" )} > {children} </SelectPrimitive.Viewport> <SelectScrollDownButton /> </SelectPrimitive.Content> </SelectPrimitive.Portal> )}
function SelectLabel({ className, ...props}: React.ComponentProps<typeof SelectPrimitive.Label>) { return ( <SelectPrimitive.Label data-slot="select-label" className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)} {...props} /> )}
function SelectItem({ className, children, ...props}: React.ComponentProps<typeof SelectPrimitive.Item>) { return ( <SelectPrimitive.Item data-slot="select-item" className={cn( "focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2", className )} {...props} > <span className="absolute right-2 flex size-3.5 items-center justify-center"> <SelectPrimitive.ItemIndicator> <CheckIcon className="size-4" /> </SelectPrimitive.ItemIndicator> </span> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> </SelectPrimitive.Item> )}
function SelectSeparator({ className, ...props}: React.ComponentProps<typeof SelectPrimitive.Separator>) { return ( <SelectPrimitive.Separator data-slot="select-separator" className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)} {...props} /> )}
function SelectScrollUpButton({ className, ...props}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) { return ( <SelectPrimitive.ScrollUpButton data-slot="select-scroll-up-button" className={cn( "flex cursor-default items-center justify-center py-1", className )} {...props} > <ChevronUpIcon className="size-4" /> </SelectPrimitive.ScrollUpButton> )}
function SelectScrollDownButton({ className, ...props}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) { return ( <SelectPrimitive.ScrollDownButton data-slot="select-scroll-down-button" className={cn( "flex cursor-default items-center justify-center py-1", className )} {...props} > <ChevronDownIcon className="size-4" /> </SelectPrimitive.ScrollDownButton> )}
export { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue,}DockerfileAdded+19
README.md+22-36
app/(public)/layout.tsxAdded+15
app/(public)/page.tsxAdded+44
app/(public)/projects/page.tsxAdded+33
app/api/ask-ai/route.tsAdded+406
app/api/auth/route.tsAdded+94
app/api/me/projects/[namespace]/[repoId]/route.tsAdded+162
app/api/me/projects/route.tsAdded+126
app/api/me/route.tsAdded+25
app/auth/callback/page.tsxAdded+27
app/auth/page.tsxAdded+36
app/globals.cssDeleted-26
app/layout.tsx+81-12
app/page.tsxDeleted-103
app/projects/[namespace]/[repoId]/page.tsxAdded+39
app/projects/new/page.tsxAdded+5
assets/globals.cssAdded+146
assets/logo.svgAdded
assets/space.svgAdded
components.jsonAdded+21
components/contexts/app-context.tsxAdded+57
components/contexts/user-context.tsxAdded+8
components/editor/ask-ai/index.tsxAdded+376
components/editor/ask-ai/re-imagine.tsxAdded+140
components/editor/ask-ai/settings.tsxAdded+212
components/editor/deploy-button/index.tsxAdded+171
components/editor/footer/index.tsxAdded+118
components/editor/header/index.tsxAdded+69
components/editor/history/index.tsxAdded+69
components/editor/index.tsxAdded+311
components/editor/preview/index.tsxAdded+78
components/editor/save-button/index.tsxAdded+76
components/invite-friends/index.tsxAdded+85
components/loading/index.tsxAdded+41
components/login-modal/index.tsxAdded+61
components/magic-ui/grid-pattern.tsxAdded+69
components/my-projects/index.tsxAdded+41
components/my-projects/project-card.tsxAdded+74
components/pro-modal/index.tsxAdded+93
components/providers/tanstack-query-provider.tsxAdded+19
components/public/navigation/index.tsxAdded+156
components/space/ask-ai/index.tsxAdded+41
components/ui/avatar.tsxAdded+53
components/ui/button.tsxAdded+67
components/ui/dialog.tsxAdded+143
components/ui/dropdown-menu.tsxAdded+257
components/ui/input.tsxAdded+21
components/ui/popover.tsxAdded+48
components/ui/select.tsxAdded+185