import { useState, useEffect, useCallback, useRef } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { AppLayout } from '@/components/AppLayout'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; import { ZipImportDialog } from '@/components/ZipImportDialog'; import { useSeoMeta } from '@unhead/react'; import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useUserRepositories } from '@/hooks/useUserRepositories'; import { useContacts } from '@/hooks/useContacts'; import { useFollowedRepositories } from '@/hooks/useFollowedRepositories'; import { RepositoryCard } from '@/components/RepositoryCard'; import { Skeleton } from '@/components/ui/skeleton'; import { Card, CardContent } from '@/components/ui/card'; import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'; export default function Clone() { const { t } = useTranslation(); const [repoUrl, setRepoUrl] = useState(''); const [isCloning, setIsCloning] = useState(false); const [error, setError] = useState(null); const navigate = useNavigate(); const [searchParams] = useSearchParams(); const projectsManager = useProjectsManager(); const { toast } = useToast(); const autoCloneInitiatedRef = useRef(false); const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const { user } = useCurrentUser(); const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey); const { data: contacts = [] } = useContacts(user?.pubkey); const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts); const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects'); useSeoMeta({ title: `${t('importRepository')} - Shakespeare`, description: t('cloneGitRepository'), }); const extractRepoName = (url: string): string => { try { const cleanUrl = url.trim(); // Handle Nostr clone URIs if (cleanUrl.startsWith('nostr://')) { const path = cleanUrl.slice(8); // Remove 'nostr://' prefix const parts = path.split('/'); // Return the d-tag (last part) as the repo name if (parts.length >= 2) { return parts[parts.length - 1] || 'nostr-repo'; } return 'nostr-repo'; } // Extract from GitHub URLs, GitLab URLs, etc. const match = cleanUrl.match(/\/([^/]+?)(?:\.git)?(?:\/)?$/); if (match && match[1]) { return match[1]; } // Fallback: use the last part of the URL const parts = cleanUrl.split('/').filter(Boolean); const lastPart = parts[parts.length - 1]; return lastPart.replace('.git', '') || 'imported-repo'; } catch { return 'imported-repo'; } }; const validateGitUrl = useCallback((url: string): boolean => { if (!url.trim()) return false; // Check if it's a Nostr clone URI if (url.startsWith('nostr://')) { return true; // Git class will handle validation } // Basic URL validation try { new URL(url); } catch { return false; } // Check if it looks like a git repository URL const gitUrlPattern = /^https?:\/\/.*\.git$|^https?:\/\/github\.com\/.*\/.*$|^https?:\/\/gitlab\.com\/.*\/.*$/i; return gitUrlPattern.test(url) || url.includes('github.com') || url.includes('gitlab.com'); }, []); const handleClone = useCallback(async (url?: string) => { const targetUrl = url || repoUrl; if (!targetUrl.trim()) { setError(t('pleaseEnterRepositoryUrl')); return; } if (!validateGitUrl(targetUrl)) { setError(t('pleaseEnterValidGitUrl')); return; } setIsCloning(true); setError(null); try { await projectsManager.init(); // Extract repository name const repoName = extractRepoName(targetUrl); // Clone the repository (Git class handles both regular Git URLs and Nostr URIs) const project = await projectsManager.cloneProject(repoName, targetUrl.trim()); // Determine success message based on URL type const isNostrUri = targetUrl.startsWith('nostr://'); const successTitle = isNostrUri ? t('nostrRepositoryImportedSuccessfully') : t('repositoryImportedSuccessfully'); const successDescription = isNostrUri ? t('repositoryClonedFromNostr', { repoName }) : t('repositoryClonedReady', { repoName }); toast({ title: successTitle, description: successDescription, }); // Navigate to the new project with build parameter navigate(`/project/${project.id}?build`); } catch (error) { console.error('Failed to clone repository:', error); let errorMessage = t('failedToImportRepository'); if (error instanceof Error) { if (error.message.includes('Repository not found on Nostr network')) { errorMessage = t('repositoryNotFoundOnNostr'); } else if (error.message.includes('No clone URLs found')) { errorMessage = t('noCloneUrlsFound'); } else if (error.message.includes('All clone attempts failed')) { errorMessage = t('allCloneAttemptsFailed'); } else if (error.message.includes('404') || error.message.includes('not found')) { errorMessage = t('repositoryNotFound'); } else if (error.message.includes('403') || error.message.includes('forbidden')) { errorMessage = t('accessDenied'); } else if (error.message.includes('network') || error.message.includes('fetch')) { errorMessage = t('networkError'); } else { errorMessage = error.message; } } setError(errorMessage); toast({ title: t('failedToImportRepository'), description: errorMessage, variant: "destructive", }); } finally { setIsCloning(false); } }, [navigate, projectsManager, repoUrl, t, toast, validateGitUrl]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !isCloning) { handleClone(); } }; // Initialize repoUrl from URL parameters and auto-import if URL is provided useEffect(() => { const urlParam = searchParams.get('url'); if (urlParam && !autoCloneInitiatedRef.current) { const decodedUrl = decodeURIComponent(urlParam); setRepoUrl(decodedUrl); autoCloneInitiatedRef.current = true; // Automatically start the clone process with the URL directly handleClone(decodedUrl); } }, [handleClone, searchParams]); const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { try { // Import project from zip file const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); // Show success toast toast({ title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, }); // Navigate to the imported project navigate(`/project/${project.id}`); } catch (error) { console.error('Failed to import project:', error); throw error; // Re-throw to let the dialog handle the error display } }; return (

{t('importRepository')}

{t('cloneGitRepository')}

{ setRepoUrl(e.target.value); setError(null); // Clear error when user types }} onKeyDown={handleKeyDown} disabled={isCloning} /> {error && (

{error}

)}
{/* Import ZIP File Link */}
setIsZipDialogOpen(true)} > Import ZIP File
{/* ZIP Import Dialog */} {/* NIP-34 Repositories with Tabs */} {user && (
setActiveTab(value as 'my-projects' | 'follows')}> My Projects Follows {isLoadingRepos ? (
{Array.from({ length: 3 }).map((_, i) => (
))}
) : repositories.length > 0 ? (
{repositories.map((repo) => ( ))}
) : (

No repositories found. Publish your first repository to Nostr to see it here.

)}
{isLoadingFollowedRepos ? (
{Array.from({ length: 6 }).map((_, i) => (
))}
) : followedRepositories.length > 0 ? (
{followedRepositories.map((repo) => ( ))}
) : contacts.length > 0 ? (

None of the people you follow have published repositories yet.

) : (

You're not following anyone yet. Follow people on Nostr to see their repositories here.

)}
)}
); }