import { useState, useEffect, useCallback, useRef, useMemo } 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, Search } 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'; import type { Repository } from '@/hooks/useUserRepositories'; import { useNostr } from '@nostrify/react'; import { useQuery } from '@tanstack/react-query'; import { nip19 } from 'nostr-tools'; import { NSchema as n } from '@nostrify/nostrify'; import type { NostrMetadata } from '@nostrify/nostrify'; import { NostrURI } from '@/lib/NostrURI'; import { useGitSettings } from '@/hooks/useGitSettings'; import { detectFork } from '@/lib/detectFork'; 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 { settings: gitSettings } = useGitSettings(); 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'); const [searchQuery, setSearchQuery] = useState(''); // Get unique pubkeys from all repositories const allRepos = useMemo(() => [...repositories, ...followedRepositories], [repositories, followedRepositories]); const uniquePubkeys = useMemo(() => { const pubkeys = new Set(); allRepos.forEach(repo => pubkeys.add(repo.pubkey)); return Array.from(pubkeys); }, [allRepos]); // Fetch author metadata for all unique pubkeys const { nostr } = useNostr(); const { data: authorMetadataMap = new Map() } = useQuery({ queryKey: ['repository-authors', uniquePubkeys.sort().join(',')], queryFn: async () => { if (uniquePubkeys.length === 0) return new Map(); const events = await nostr.query( [{ kinds: [0], authors: uniquePubkeys, limit: uniquePubkeys.length }], { signal: AbortSignal.timeout(3000) } ); const metadataMap = new Map(); for (const event of events) { try { const metadata = n.json().pipe(n.metadata()).parse(event.content); metadataMap.set(event.pubkey, metadata); } catch { // If parsing fails, continue without metadata for this pubkey } } return metadataMap; }, enabled: uniquePubkeys.length > 0, staleTime: 60000, // 1 minute }); useSeoMeta({ title: `${t('importRepository')} - Shakespeare`, description: t('cloneGitRepository'), }); const extractRepoName = async (url: string): Promise => { try { const cleanUrl = url.trim(); // Handle Nostr clone URIs if (cleanUrl.startsWith('nostr://')) { try { const nostrURI = await NostrURI.parse(cleanUrl); return nostrURI.identifier || 'nostr-repo'; } catch { 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 = await extractRepoName(targetUrl); // Determine if this is a fork const fork = await detectFork(targetUrl, user?.pubkey, gitSettings.credentials); // Clone the repository (Git class handles both regular Git URLs and Nostr URIs) const project = await projectsManager.cloneProject({ name: repoName, repoUrl: targetUrl.trim(), fork, }); // 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, user, gitSettings.credentials]); 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 } }; // Filter repositories based on search query const filterRepositories = useCallback((repos: Repository[], query: string): Repository[] => { if (!query.trim()) { return repos; } const lowerQuery = query.toLowerCase(); return repos.filter((repo) => { // Filter by repository name if (repo.name.toLowerCase().includes(lowerQuery)) { return true; } // Filter by description if (repo.description?.toLowerCase().includes(lowerQuery)) { return true; } // Filter by tags (hashtags) if (repo.repoTags.some(tag => tag.toLowerCase().includes(lowerQuery))) { return true; } // Filter by hex pubkey if (repo.pubkey.toLowerCase().includes(lowerQuery)) { return true; } // Filter by npub (bech32 encoded pubkey) try { const npub = nip19.npubEncode(repo.pubkey); if (npub.toLowerCase().includes(lowerQuery)) { return true; } } catch { // If encoding fails, skip npub search } // Filter by author name const authorMetadata = authorMetadataMap.get(repo.pubkey); if (authorMetadata?.name?.toLowerCase().includes(lowerQuery)) { return true; } return false; }); }, [authorMetadataMap]); // Filtered repositories for "My Projects" tab const filteredMyRepositories = useMemo(() => { return filterRepositories(repositories, searchQuery); }, [repositories, searchQuery, filterRepositories]); // Filtered repositories for "Follows" tab const filteredFollowedRepositories = useMemo(() => { return filterRepositories(followedRepositories, searchQuery); }, [followedRepositories, searchQuery, filterRepositories]); 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 {/* Search Input */} {(repositories.length > 0 || followedRepositories.length > 0) && (
setSearchQuery(e.target.value)} className="pl-9 h-10 text-sm" />
)}
{isLoadingRepos ? (
{Array.from({ length: 3 }).map((_, i) => (
))}
) : filteredMyRepositories.length > 0 ? (
{filteredMyRepositories.map((repo) => ( ))}
) : searchQuery.trim() ? (

No repositories found matching "{searchQuery}".

) : (

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

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

No repositories found matching "{searchQuery}".

) : 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.

)}
)}
); }