Spaces:
Sleeping
Sleeping
wip: remove readonly
Browse filesFiles changed (5)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240import { NextRequest, NextResponse } from "next/server";import { isAuthenticated } from "@/lib/auth";
export async function GET(req: NextRequest) { const user: any = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const { searchParams } = new URL(req.url); const spaceId = searchParams.get('spaceId'); const commitId = searchParams.get('commitId'); const path = searchParams.get('path') || '/'; if (!spaceId) { return NextResponse.json({ error: "spaceId parameter required" }, { status: 400 }); }
try { const spaceDomain = `${spaceId.replace("/", "-")}${commitId !== null? `--rev-${commitId.slice(0, 7)}` : ""}.static.hf.space`; const targetUrl = `https://${spaceDomain}${path}`;
console.log("targetUrl", targetUrl); const response = await fetch(targetUrl, { headers: { 'User-Agent': req.headers.get('user-agent') || '', }, });
if (!response.ok) { console.error('Failed to fetch from HF space:', response.status, response.statusText); return NextResponse.json({ error: "Failed to fetch content", details: `${response.status} ${response.statusText}`, targetUrl }, { status: response.status }); }
let content = await response.text(); const contentType = response.headers.get('content-type') || 'text/html';
// Rewrite relative URLs to go through the proxy if (contentType.includes('text/html')) { const baseUrl = `https://${spaceDomain}`; // Fix relative URLs in href attributes content = content.replace(/href="([^"]+)"/g, (match, url) => { if (url.startsWith('/') && !url.startsWith('//')) { // Relative URL starting with / return `href="${baseUrl}${url}"`; } else if (!url.includes('://') && !url.startsWith('#') && !url.startsWith('mailto:') && !url.startsWith('tel:')) { // Relative URL not starting with / return `href="${baseUrl}/${url}"`; } return match; }); // Fix relative URLs in src attributes content = content.replace(/src="([^"]+)"/g, (match, url) => { if (url.startsWith('/') && !url.startsWith('//')) { return `src="${baseUrl}${url}"`; } else if (!url.includes('://')) { return `src="${baseUrl}/${url}"`; } return match; }); // Add base tag to ensure relative URLs work correctly const baseTag = `<base href="${baseUrl}/">`; if (content.includes('<head>')) { content = content.replace('<head>', `<head>${baseTag}`); } else if (content.includes('<html>')) { content = content.replace('<html>', `<html><head>${baseTag}</head>`); } else { content = `<head>${baseTag}</head>` + content; } }
const injectedScript = ` <script> // Add event listeners and communicate with parent document.addEventListener('DOMContentLoaded', function() { let hoveredElement = null; let isEditModeEnabled = false; document.addEventListener('mouseover', function(event) { if (event.target !== document.body && event.target !== document.documentElement) { hoveredElement = event.target; const rect = event.target.getBoundingClientRect(); const message = { type: 'ELEMENT_HOVERED', data: { tagName: event.target.tagName, rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height }, element: event.target.outerHTML } }; parent.postMessage(message, '*'); } }); document.addEventListener('mouseout', function(event) { hoveredElement = null; parent.postMessage({ type: 'ELEMENT_MOUSE_OUT' }, '*'); }); // Handle clicks - prevent default only in edit mode document.addEventListener('click', function(event) { // Only prevent default if edit mode is enabled if (isEditModeEnabled) { event.preventDefault(); event.stopPropagation(); const rect = event.target.getBoundingClientRect(); parent.postMessage({ type: 'ELEMENT_CLICKED', data: { tagName: event.target.tagName, rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height }, element: event.target.outerHTML } }, '*'); } else { // In non-edit mode, handle link clicks to maintain proxy context const link = event.target.closest('a'); if (link && link.href) { event.preventDefault(); const url = new URL(link.href); // If it's an external link (different domain than the space), open in new tab if (url.hostname !== '${spaceDomain}') { window.open(link.href, '_blank'); } else { // For internal links within the space, navigate through the proxy // Extract the path and query parameters from the original link const targetPath = url.pathname + url.search + url.hash; // Get current proxy URL parameters const currentUrl = new URL(window.location.href); const spaceId = currentUrl.searchParams.get('spaceId') || ''; const commitId = currentUrl.searchParams.get('commitId') || ''; // Construct new proxy URL with the target path const proxyUrl = '/api/proxy/?' + 'spaceId=' + encodeURIComponent(spaceId) + (commitId ? '&commitId=' + encodeURIComponent(commitId) : '') + '&path=' + encodeURIComponent(targetPath); // Navigate to the new URL through the parent window parent.postMessage({ type: 'NAVIGATE_TO_PROXY', data: { proxyUrl: proxyUrl, targetPath: targetPath } }, '*'); } } } }); // Prevent form submissions when in edit mode document.addEventListener('submit', function(event) { if (isEditModeEnabled) { event.preventDefault(); event.stopPropagation(); } }); // Prevent other navigation events when in edit mode document.addEventListener('keydown', function(event) { if (isEditModeEnabled && event.key === 'Enter' && (event.target.tagName === 'A' || event.target.tagName === 'BUTTON')) { event.preventDefault(); event.stopPropagation(); } }); // Listen for messages from parent window.addEventListener('message', function(event) { if (event.data.type === 'ENABLE_EDIT_MODE') { isEditModeEnabled = true; document.body.style.userSelect = 'none'; document.body.style.pointerEvents = 'auto'; } else if (event.data.type === 'DISABLE_EDIT_MODE') { isEditModeEnabled = false; document.body.style.userSelect = ''; document.body.style.pointerEvents = ''; } }); // Notify parent that script is ready parent.postMessage({ type: 'PROXY_SCRIPT_READY' }, '*'); }); </script> `; let modifiedContent; if (content.includes('</body>')) { modifiedContent = content.replace( /<\/body>/i, `${injectedScript}</body>` ); } else { modifiedContent = content + injectedScript; } return new NextResponse(modifiedContent, { headers: { 'Content-Type': contentType, 'Cache-Control': 'no-cache, no-store, must-revalidate', }, });
} catch (error) { return NextResponse.json({ error: "Proxy request failed", details: error instanceof Error ? error.message : String(error), spaceId }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"use client";
import { useState } from "react";import classNames from "classnames";import { Button } from "@/components/ui/button";import Loading from "@/components/loading";import { History, ChevronUp, ChevronDown, MousePointerClick,} from "lucide-react";
interface HistoryNotificationProps { /** Whether the historical version notification should be visible */ isVisible: boolean; /** Whether the version promotion is in progress */ isPromotingVersion: boolean; /** Function to promote the current historical version */ onPromoteVersion: () => void; /** Function to go back to the current version */ onGoBackToCurrent: () => void; /** Additional CSS classes */ className?: string;}
export const HistoryNotification = ({ isVisible, isPromotingVersion, onPromoteVersion, onGoBackToCurrent, className,}: HistoryNotificationProps) => { const [isCollapsed, setIsCollapsed] = useState(false);
if (!isVisible) { return null; }
return ( <div className={classNames( "absolute bottom-4 left-4 z-10 bg-white/95 backdrop-blur-sm border border-neutral-200 rounded-xl shadow-lg transition-all duration-300 ease-in-out", className )} > {isCollapsed ? ( // Collapsed state <div className="flex items-center gap-2 p-3"> <History className="size-4 text-neutral-600" /> <span className="text-xs text-neutral-600 font-medium"> Historical Version </span> <Button variant="outline" size="iconXs" className="!rounded-md !border-neutral-200" onClick={() => setIsCollapsed(false)} > <ChevronUp className="text-neutral-400 size-3" /> </Button> </div> ) : ( // Expanded state <div className="p-4 max-w-sm w-full"> <div className="flex items-start gap-3"> <History className="size-4 text-neutral-600 translate-y-1.5" /> <div className="flex-1 min-w-0"> <div className="flex items-center justify-between mb-1"> <div className="flex items-center gap-2"> <p className="font-semibold text-sm text-neutral-800"> Historical Version </p> </div> <Button variant="outline" size="iconXs" className="!rounded-md !border-neutral-200" onClick={() => setIsCollapsed(true)} > <ChevronDown className="text-neutral-400 size-3" /> </Button> </div> <p className="text-xs text-neutral-600 leading-relaxed mb-3"> You're viewing a previous version of this project. Promote this version to make it current and deploy it live. </p> <div className="flex items-center gap-2"> <Button size="xs" variant="black" className="!pr-3" onClick={onPromoteVersion} disabled={isPromotingVersion} > {isPromotingVersion ? ( <Loading overlay={false} /> ) : ( <MousePointerClick className="size-3" /> )} Promote Version </Button> <Button size="xs" variant="outline" className=" !text-neutral-600 !border-neutral-200" disabled={isPromotingVersion} onClick={onGoBackToCurrent} > Go back to current </Button> </div> </div> </div> </div> )} </div> );};24 unmodified lines2526272829303132333436 unmodified lines7172737475767778798024 unmodified linesrepoId?: string;isNew?: boolean;}) => {const { project, setPages, files, currentPageData, currentTab } = useEditor(namespace,repoId);const [, copyToClipboard] = useCopyToClipboard();const monacoRef = useRef<any>(null);36 unmodified lineshorizontal: "hidden",},wordWrap: "on",readOnly: true,readOnlyMessage: {value:"You can't edit the code, ask DeepSite to do it for you!",isTrusted: true,},}}24 unmodified lines25262728293031323334353637383936 unmodified lines767778798081828384858624 unmodified linesrepoId?: string;isNew?: boolean;}) => {const {project,setPages,files,currentPageData,currentTab,currentCommit,} = useEditor(namespace, repoId);const { isAiWorking } = useAi();const [, copyToClipboard] = useCopyToClipboard();const monacoRef = useRef<any>(null);36 unmodified lineshorizontal: "hidden",},wordWrap: "on",readOnly: !!isAiWorking || !!currentCommit,readOnlyMessage: {value: currentCommit? "You can't edit the code, as this is an old version of the project.": "Wait for DeepSite to finish working...",isTrusted: true,},}}
13 unmodified lines141516171819202122232425267 unmodified lines343536373839404142434445464748495051525354555657585952 unmodified lines11211311411511611728 unmodified lines14614714814915015115210 unmodified lines1631641651661671681691701715 unmodified lines17717817918018118218326 unmodified lines2102112122132142152162172182191 unmodified line22122222322422522622712 unmodified lines24024124224324424524624724824925025146 unmodified lines2982993003013023033044 unmodified lines30931031131231331431531631731831932032132232332432532618 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743813 unmodified linesimport { defaultHTML } from "@/lib/consts";import { Button } from "@/components/ui/button";import { LivePreview } from "../live-preview";import {MousePointerClick,History,AlertCircle,ChevronDown,ChevronUp,} from "lucide-react";import { api } from "@/lib/api";import { toast } from "sonner";import Loading from "@/components/loading";7 unmodified linescurrentCommit,setCurrentCommit,currentPageData,} = useEditor();const {isEditableModeEnabled,setSelectedElement,isAiWorking,setIsEditableModeEnabled,} = useAi();const iframeSrc = project?.space_id? `/api/proxy/?spaceId=${encodeURIComponent(project.space_id)}${currentCommit ? `&commitId=${currentCommit}` : ""}`: "";const iframeRef = useRef<HTMLIFrameElement>(null);// For private projects, use srcDoc instead of proxy URLconst shouldUseCustomIframe = project?.private && currentPageData?.html;// Inject event handling script for private projectsconst injectInteractivityScript = (html: string) => {const interactivityScript = `<script>52 unmodified lineselement: event.target.outerHTML}}, '*');}});28 unmodified lines// Notify parent that script is readyparent.postMessage({type: 'PROXY_SCRIPT_READY'}, '*');});</script>10 unmodified linestagName: string;rect: { top: number; left: number; width: number; height: number };} | null>(null);const [isHistoryNotificationCollapsed, setIsHistoryNotificationCollapsed] =useState(false);const [isPromotingVersion, setIsPromotingVersion] = useState(false);// Handle PostMessage communication with iframeuseEffect(() => {5 unmodified linesconst { type, data } = event.data;switch (type) {case "PROXY_SCRIPT_READY":if (iframeRef.current?.contentWindow) {iframeRef.current.contentWindow.postMessage({26 unmodified linessetIsEditableModeEnabled(false);}break;case "NAVIGATE_TO_PROXY":// Handle navigation within the iframe while maintaining proxy contextif (iframeRef.current && data.proxyUrl) {iframeRef.current.src = data.proxyUrl;}break;}1 unmodified linewindow.addEventListener("message", handleMessage);return () => window.removeEventListener("message", handleMessage);}, [setSelectedElement, isEditableModeEnabled]);// Send edit mode state to iframe and clear hover state when disableduseUpdateEffect(() => {12 unmodified linesif (!isEditableModeEnabled) {setHoveredElement(null);}}, [isEditableModeEnabled,project?.space_id,shouldUseCustomIframe,currentPageData?.html,]);const promoteVersion = async () => {setIsPromotingVersion(true);46 unmodified lines</span></div>)}{isNew && !isAiWorking ? (<iframeclassName={classNames("w-full select-none transition-all duration-200 bg-black h-full",4 unmodified lines)}srcDoc={defaultHTML}/>) : iframeSrc === "" ||isLoadingProject ||(isAiWorking && iframeSrc == "") ||(shouldUseCustomIframe && !currentPageData?.html) ? (<div className="w-full h-full flex items-center justify-center relative"><div className="py-10 w-full relative z-1 max-w-3xl mx-auto text-center"><AiLoadingtext={isAiWorking && iframeSrc === ""? undefined: "Fetching your space..."}className="flex-col"/><AnimatedBlobs />18 unmodified linesdevice === "mobile",})}{...(shouldUseCustomIframe? {srcDoc: injectInteractivityScript(currentPageData?.html || ""),}: { src: iframeSrc })}allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; clipboard-read; clipboard-write; display-capture; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; serial; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking"/><divclassName={classNames("absolute bottom-4 left-4 z-10 bg-white/95 backdrop-blur-sm border border-neutral-200 rounded-xl shadow-lg transition-all duration-300 ease-in-out",{hidden: !currentCommit,})}>{isHistoryNotificationCollapsed ? (// Collapsed state<div className="flex items-center gap-2 p-3"><History className="size-4 text-neutral-600" /><span className="text-xs text-neutral-600 font-medium">Historical Version</span><Buttonvariant="outline"size="iconXs"className="!rounded-md !border-neutral-200"onClick={() => setIsHistoryNotificationCollapsed(false)}><ChevronUp className="text-neutral-400 size-3" /></Button></div>) : (// Expanded state<div className="p-4 max-w-sm w-full"><div className="flex items-start gap-3"><History className="size-4 text-neutral-600 translate-y-1.5" /><div className="flex-1 min-w-0"><div className="flex items-center justify-between mb-1"><div className="flex items-center gap-2"><p className="font-semibold text-sm text-neutral-800">Historical Version</p></div><Buttonvariant="outline"size="iconXs"className="!rounded-md !border-neutral-200"onClick={() => setIsHistoryNotificationCollapsed(true)}><ChevronDown className="text-neutral-400 size-3" /></Button></div><p className="text-xs text-neutral-600 leading-relaxed mb-3">You're viewing a previous version of this project. Promotethis version to make it current and deploy it live.</p><div className="flex items-center gap-2"><Buttonsize="xs"variant="black"className="!pr-3"onClick={() => promoteVersion()}disabled={isPromotingVersion}>{isPromotingVersion ? (<Loading overlay={false} />) : (<MousePointerClick className="size-3" />)}Promote Version</Button><Buttonsize="xs"variant="outline"className=" !text-neutral-600 !border-neutral-200"disabled={isPromotingVersion}onClick={() => setCurrentCommit(null)}>Go back to current</Button></div></div></div></div>)}</div></>)}</div>13 unmodified lines14151617181920217 unmodified lines293031323334353637383940414243444546474852 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214328 unmodified lines17217317417517617717810 unmodified lines1891901911921931941951965 unmodified lines20220320420520620720826 unmodified lines2352362372382392402412422432442452462472482492502512522532541 unmodified line25625725825926026126212 unmodified lines27527627727827928028128228328428528628728828929029129229329429529629729829930046 unmodified lines3473483493503513523534 unmodified lines35835936036136236336436536636736818 unmodified lines38738838939039139239339439539639739839940040140240340440540640740840941041141241341413 unmodified linesimport { defaultHTML } from "@/lib/consts";import { Button } from "@/components/ui/button";import { LivePreview } from "../live-preview";import { HistoryNotification } from "../history-notification";import { AlertCircle } from "lucide-react";import { api } from "@/lib/api";import { toast } from "sonner";import Loading from "@/components/loading";7 unmodified linescurrentCommit,setCurrentCommit,currentPageData,pages,setCurrentPage,} = useEditor();const {isEditableModeEnabled,setSelectedElement,isAiWorking,globalAiLoading,setIsEditableModeEnabled,} = useAi();const iframeRef = useRef<HTMLIFrameElement>(null);// Inject event handling scriptconst injectInteractivityScript = (html: string) => {const interactivityScript = `<script>52 unmodified lineselement: event.target.outerHTML}}, '*');} else {// Handle link clicks to navigate between pagesconst link = event.target.closest('a');if (link && link.href) {event.preventDefault();const url = new URL(link.href, window.location.href);// Check if it's a relative link (same origin)if (url.origin === window.location.origin || link.href.startsWith('/') || link.href.startsWith('./') || link.href.startsWith('../') || !link.href.includes('://')) {// Extract the path from the linklet targetPath = link.getAttribute('href') || '';// Handle relative pathsif (targetPath.startsWith('./')) {targetPath = targetPath.substring(2);} else if (targetPath.startsWith('/')) {targetPath = targetPath.substring(1);}// If no extension, assume .htmlif (!targetPath.includes('.') && !targetPath.includes('?') && !targetPath.includes('#')) {targetPath = targetPath === '' ? 'index.html' : targetPath + '.html';}// Send message to parent to navigate to the pageparent.postMessage({type: 'NAVIGATE_TO_PAGE',data: {targetPath: targetPath}}, '*');} else {// External link - open in new tabwindow.open(link.href, '_blank');}}}});28 unmodified lines// Notify parent that script is readyparent.postMessage({type: 'IFRAME_SCRIPT_READY'}, '*');});</script>10 unmodified linestagName: string;rect: { top: number; left: number; width: number; height: number };} | null>(null);const [isPromotingVersion, setIsPromotingVersion] = useState(false);const [stableHtml, setStableHtml] = useState<string>("");// Handle PostMessage communication with iframeuseEffect(() => {5 unmodified linesconst { type, data } = event.data;switch (type) {case "IFRAME_SCRIPT_READY":if (iframeRef.current?.contentWindow) {iframeRef.current.contentWindow.postMessage({26 unmodified linessetIsEditableModeEnabled(false);}break;case "NAVIGATE_TO_PAGE":// Handle navigation between pages by updating currentPageDataif (data.targetPath) {// Find the page in the pages arrayconst targetPage = pages.find((page) => page.path === data.targetPath);if (targetPage) {setCurrentPage(data.targetPath);} else {// If page doesn't exist, you might want to create it or show an errorconsole.warn(`Page not found: ${data.targetPath}`);toast.error(`Page not found: ${data.targetPath}`);}}break;}1 unmodified linewindow.addEventListener("message", handleMessage);return () => window.removeEventListener("message", handleMessage);}, [setSelectedElement, isEditableModeEnabled, pages, setCurrentPage]);// Send edit mode state to iframe and clear hover state when disableduseUpdateEffect(() => {12 unmodified linesif (!isEditableModeEnabled) {setHoveredElement(null);}}, [isEditableModeEnabled, stableHtml]);// Update stable HTML only when AI finishes working to prevent blinkinguseEffect(() => {if (!isAiWorking && !globalAiLoading && currentPageData?.html) {setStableHtml(currentPageData.html);}}, [isAiWorking, globalAiLoading, currentPageData?.html]);// Initialize stable HTML when component first loadsuseEffect(() => {if (currentPageData?.html &&!stableHtml &&!isAiWorking &&!globalAiLoading) {setStableHtml(currentPageData.html);}}, [currentPageData?.html, stableHtml, isAiWorking, globalAiLoading]);const promoteVersion = async () => {setIsPromotingVersion(true);46 unmodified lines</span></div>)}{isNew && !isLoadingProject ? (<iframeclassName={classNames("w-full select-none transition-all duration-200 bg-black h-full",4 unmodified lines)}srcDoc={defaultHTML}/>) : isLoadingProject || globalAiLoading ? (<div className="w-full h-full flex items-center justify-center relative"><div className="py-10 w-full relative z-1 max-w-3xl mx-auto text-center"><AiLoadingtext={isLoadingProject ? "Fetching your project..." : undefined}className="flex-col"/><AnimatedBlobs />18 unmodified linesdevice === "mobile",})}src={currentCommit? `https://${project?.space_id?.replaceAll("/","-")}--rev-${currentCommit.slice(0, 7)}.static.hf.space`: undefined}srcDoc={!currentCommit? injectInteractivityScript(stableHtml || ""): undefined}sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; clipboard-read; clipboard-write; display-capture; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; serial; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking"/><HistoryNotificationisVisible={!!currentCommit}isPromotingVersion={isPromotingVersion}onPromoteVersion={promoteVersion}onGoBackToCurrent={() => setCurrentCommit(null)}/></>)}</div>
66 unmodified lines6768697071727366 unmodified lines) : (<div className="absolute inset-0 w-full h-full overflow-hidden"><iframesrc={`/api/proxy/?spaceId=${encodeURIComponent(project.name)}`}className="w-[1200px] h-[675px] border-0 origin-top-left"style={{transform: "scale(0.5)",66 unmodified lines6768697071727374757666 unmodified lines) : (<div className="absolute inset-0 w-full h-full overflow-hidden"><iframesrc={`https://${project.name.replaceAll("/","-")}.static.hf.space`}className="w-[1200px] h-[675px] border-0 origin-top-left"style={{transform: "scale(0.5)",
app/api/proxy/route.tsDeleted-240
components/editor/history-notification/index.tsxAdded+119
components/editor/index.tsx+13-7
components/editor/preview/index.tsx+104-128
components/my-projects/project-card.tsx+4-1