From 1dacc1371b182f87641dddd3a8bf6c196cac7895 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 30 Jul 2025 22:04:08 -0500 Subject: [PATCH] Add unified useRepos hook --- src/components/NostrRepos.tsx | 246 ------------------------ src/components/RepoCard.tsx | 272 +++++++++++++++++++++++++++ src/hooks/useNostrEnabledProjects.ts | 40 ---- src/hooks/useRepos.ts | 135 +++++++++++++ src/pages/Index.tsx | 118 +++++------- 5 files changed, 451 insertions(+), 360 deletions(-) delete mode 100644 src/components/NostrRepos.tsx create mode 100644 src/components/RepoCard.tsx delete mode 100644 src/hooks/useNostrEnabledProjects.ts create mode 100644 src/hooks/useRepos.ts diff --git a/src/components/NostrRepos.tsx b/src/components/NostrRepos.tsx deleted file mode 100644 index c23a982c..00000000 --- a/src/components/NostrRepos.tsx +++ /dev/null @@ -1,246 +0,0 @@ -import { useState } from 'react'; -import { useNostrRepos, type NostrRepo } from '@/hooks/useNostrRepos'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useToast } from '@/hooks/useToast'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Button } from '@/components/ui/button'; -import { Badge } from '@/components/ui/badge'; -import { Skeleton } from '@/components/ui/skeleton'; -import { GitBranch, Download, ExternalLink, Users, Globe } from 'lucide-react'; -import { cn } from '@/lib/utils'; -import { nip19 } from 'nostr-tools'; -import git from 'isomorphic-git'; -import http from 'isomorphic-git/http/web'; - -interface NostrReposProps { - className?: string; - excludeProjectIds?: string[]; // Project IDs that are already "nostr enabled" - onProjectCloned?: () => void; // Callback when a project is successfully cloned -} - -export function NostrRepos({ className, excludeProjectIds = [], onProjectCloned }: NostrReposProps) { - const { data: repos, isLoading, error } = useNostrRepos(); - const projectsManager = useProjectsManager(); - const { toast } = useToast(); - const [cloningRepos, setCloningRepos] = useState>(new Set()); - - // Filter out repos that are already represented as projects - const availableRepos = repos?.filter(repo => !excludeProjectIds.includes(repo.id)) || []; - - const handleCloneRepo = async (repo: NostrRepo) => { - if (!repo.cloneUrls.length) { - toast({ - title: "No clone URL", - description: "This repository doesn't have any clone URLs configured.", - variant: "destructive", - }); - return; - } - - setCloningRepos(prev => new Set(prev).add(repo.id)); - - try { - await projectsManager.init(); - - // Create project directory - const projectPath = `/projects/${repo.id}`; - - // Clone the repository - const cloneUrl = repo.cloneUrls[0]; // Use the first clone URL - await git.clone({ - fs: projectsManager.fs, - http, - dir: projectPath, - url: cloneUrl, - singleBranch: true, - depth: 1, - }); - - // Set git config to mark this as a nostr-enabled project - const naddr = nip19.naddrEncode({ - identifier: repo.id, - pubkey: repo.event.pubkey, - kind: 30617, - relays: repo.relays.length > 0 ? repo.relays : undefined, - }); - - await git.setConfig({ - fs: projectsManager.fs, - dir: projectPath, - path: 'nostr.repo', - value: naddr, - }); - - // No need to create project metadata - using filesystem stats and basename - - toast({ - title: "Repository cloned", - description: `${repo.name} has been cloned to your projects.`, - }); - - // Call the callback to refresh the projects list, or fall back to page reload - if (onProjectCloned) { - onProjectCloned(); - } else { - window.location.reload(); - } - } catch (error) { - console.error('Failed to clone repository:', error); - toast({ - title: "Clone failed", - description: `Failed to clone ${repo.name}. Please try again.`, - variant: "destructive", - }); - } finally { - setCloningRepos(prev => { - const newSet = new Set(prev); - newSet.delete(repo.id); - return newSet; - }); - } - }; - - if (isLoading) { - return ( -
-

Your Nostr Repositories

-
- {[...Array(3)].map((_, i) => ( - - - - - - - - - - - ))} -
-
- ); - } - - if (error) { - return ( -
-

Your Nostr Repositories

- - -

Failed to load repositories

-
-
-
- ); - } - - if (!availableRepos.length) { - return null; // Don't show the section if there are no repos to display - } - - return ( -
-

Your Nostr Repositories

-

- Clone your NIP-34 repositories to start working on them locally. -

- -
- {availableRepos.map((repo) => { - const isCloning = cloningRepos.has(repo.id); - - return ( - - -
-
- - - {repo.name} - - {repo.description && ( - - {repo.description} - - )} -
-
-
- - - {/* Tags */} - {repo.tags.length > 0 && ( -
- {repo.tags.slice(0, 3).map((tag) => ( - - {tag} - - ))} - {repo.tags.length > 3 && ( - - +{repo.tags.length - 3} - - )} -
- )} - - {/* Repository info */} -
- {repo.maintainers.length > 0 && ( -
- - {repo.maintainers.length} maintainer{repo.maintainers.length !== 1 ? 's' : ''} -
- )} - {repo.webUrls.length > 0 && ( -
- - Web -
- )} -
- - {/* Actions */} -
- - - {repo.webUrls.length > 0 && ( - - )} -
-
-
- ); - })} -
-
- ); -} \ No newline at end of file diff --git a/src/components/RepoCard.tsx b/src/components/RepoCard.tsx new file mode 100644 index 00000000..d19fd140 --- /dev/null +++ b/src/components/RepoCard.tsx @@ -0,0 +1,272 @@ +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useToast } from '@/hooks/useToast'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { + Folder, + GitBranch, + Download, + ExternalLink, + Users, + Globe, + Cloud, + HardDrive, + RefreshCw, + Upload +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { nip19 } from 'nostr-tools'; +import git from 'isomorphic-git'; +import http from 'isomorphic-git/http/web'; +import type { UnifiedRepo } from '@/hooks/useRepos'; + +interface RepoCardProps { + repo: UnifiedRepo; + onRepoCloned?: () => void; + className?: string; +} + +export function RepoCard({ repo, onRepoCloned, className }: RepoCardProps) { + const navigate = useNavigate(); + const projectsManager = useProjectsManager(); + const { toast } = useToast(); + const [isCloning, setIsCloning] = useState(false); + + const getStatusIcon = () => { + switch (repo.status) { + case 'local-only': + return ; + case 'published': + return ; + case 'remote-only': + return ; + case 'synced': + return ; + } + }; + + const getStatusText = () => { + switch (repo.status) { + case 'local-only': + return 'Local only'; + case 'published': + return 'Published'; + case 'remote-only': + return 'Remote only'; + case 'synced': + return 'Synced'; + } + }; + + const getStatusColor = () => { + switch (repo.status) { + case 'local-only': + return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'; + case 'published': + return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'; + case 'remote-only': + return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'; + case 'synced': + return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200'; + } + }; + + const handleCardClick = () => { + if (repo.localProject) { + navigate(`/project/${repo.localProject.id}`); + } + }; + + const handleCloneRepo = async () => { + if (!repo.nostrRepo || !repo.cloneUrls.length) { + toast({ + title: "No clone URL", + description: "This repository doesn't have any clone URLs configured.", + variant: "destructive", + }); + return; + } + + setIsCloning(true); + + try { + await projectsManager.init(); + + // Create project directory + const projectPath = `/projects/${repo.id}`; + + // Clone the repository + const cloneUrl = repo.cloneUrls[0]; // Use the first clone URL + await git.clone({ + fs: projectsManager.fs, + http, + dir: projectPath, + url: cloneUrl, + singleBranch: true, + depth: 1, + }); + + // Set git config to mark this as a nostr-enabled project + const naddr = nip19.naddrEncode({ + identifier: repo.id, + pubkey: repo.nostrRepo.event.pubkey, + kind: 30617, + relays: repo.relays.length > 0 ? repo.relays : undefined, + }); + + await git.setConfig({ + fs: projectsManager.fs, + dir: projectPath, + path: 'nostr.repo', + value: naddr, + }); + + toast({ + title: "Repository cloned", + description: `${repo.name} has been cloned to your projects.`, + }); + + // Call the callback to refresh the repos list + if (onRepoCloned) { + onRepoCloned(); + } + } catch (error) { + console.error('Failed to clone repository:', error); + toast({ + title: "Clone failed", + description: `Failed to clone ${repo.name}. Please try again.`, + variant: "destructive", + }); + } finally { + setIsCloning(false); + } + }; + + const canOpen = repo.status === 'local-only' || repo.status === 'published' || repo.status === 'synced'; + const canClone = repo.status === 'remote-only' && repo.cloneUrls.length > 0; + + return ( + { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + handleCardClick(); + } + } : undefined} + > + +
+
+ + {repo.status === 'remote-only' ? ( + + ) : ( + + )} + {repo.name} + + {repo.description && ( + + {repo.description} + + )} +
+
+ + + {getStatusIcon()} + {getStatusText()} + + +
+
+ + Modified {repo.lastModified.toLocaleDateString()} + +
+ + + {/* Tags */} + {repo.tags.length > 0 && ( +
+ {repo.tags.slice(0, 3).map((tag) => ( + + {tag} + + ))} + {repo.tags.length > 3 && ( + + +{repo.tags.length - 3} + + )} +
+ )} + + {/* Repository info */} + {(repo.maintainers.length > 0 || repo.webUrls.length > 0) && ( +
+ {repo.maintainers.length > 0 && ( +
+ + {repo.maintainers.length} maintainer{repo.maintainers.length !== 1 ? 's' : ''} +
+ )} + {repo.webUrls.length > 0 && ( +
+ + Web +
+ )} +
+ )} + + {/* Actions */} + {(canClone || repo.webUrls.length > 0) && ( +
e.stopPropagation()}> + {canClone && ( + + )} + + {repo.webUrls.length > 0 && ( + + )} +
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/src/hooks/useNostrEnabledProjects.ts b/src/hooks/useNostrEnabledProjects.ts deleted file mode 100644 index 2dc65363..00000000 --- a/src/hooks/useNostrEnabledProjects.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useProjectsManager } from './useProjectsManager'; -import { nip19 } from 'nostr-tools'; - -export function useNostrEnabledProjects() { - const projectsManager = useProjectsManager(); - - return useQuery({ - queryKey: ['nostr-enabled-projects'], - queryFn: async () => { - try { - await projectsManager.init(); - const projects = await projectsManager.getProjects(); - - const nostrEnabledProjects: string[] = []; - - for (const project of projects) { - try { - const naddr = await projectsManager.getNostrRepoAddress(project.id); - if (naddr) { - // Extract the d tag (identifier) from the naddr - const decoded = nip19.decode(naddr); - if (decoded.type === 'naddr') { - nostrEnabledProjects.push(decoded.data.identifier); - } - } - } catch { - // Skip projects that can't be checked - } - } - - return nostrEnabledProjects; - } catch { - return []; - } - }, - staleTime: 30 * 1000, // 30 seconds - gcTime: 60 * 1000, // 1 minute - }); -} \ No newline at end of file diff --git a/src/hooks/useRepos.ts b/src/hooks/useRepos.ts new file mode 100644 index 00000000..5b76b6fb --- /dev/null +++ b/src/hooks/useRepos.ts @@ -0,0 +1,135 @@ +import { useQuery } from '@tanstack/react-query'; +import { useProjectsManager } from './useProjectsManager'; +import { useNostrRepos, type NostrRepo } from './useNostrRepos'; +import { useCurrentUser } from './useCurrentUser'; +import { nip19 } from 'nostr-tools'; +import type { Project } from '@/lib/ProjectsManager'; + +export type RepoStatus = + | 'local-only' // Exists only locally, not published to Nostr + | 'published' // Local project that's also published to Nostr + | 'remote-only' // Exists on Nostr but not cloned locally + | 'synced'; // Local and remote are in sync + +export interface UnifiedRepo { + id: string; + name: string; + description?: string; + status: RepoStatus; + lastModified: Date; + + // Local project data (if exists locally) + localProject?: Project; + + // Nostr repo data (if exists on Nostr) + nostrRepo?: NostrRepo; + + // Additional metadata + tags: string[]; + webUrls: string[]; + cloneUrls: string[]; + maintainers: string[]; + relays: string[]; +} + +export function useRepos() { + const projectsManager = useProjectsManager(); + const { user } = useCurrentUser(); + const { data: nostrRepos = [] } = useNostrRepos(); + + return useQuery({ + queryKey: ['unified-repos', user?.pubkey], + queryFn: async () => { + try { + await projectsManager.init(); + const localProjects = await projectsManager.getProjects(); + + // Create a map to track repos by their identifier + const repoMap = new Map(); + + // First, add all local projects + for (const project of localProjects) { + const naddr = await projectsManager.getNostrRepoAddress(project.id); + let repoId = project.id; + let status: RepoStatus = 'local-only'; + + // If this project has a Nostr address, extract the repo ID + if (naddr) { + try { + const decoded = nip19.decode(naddr); + if (decoded.type === 'naddr') { + repoId = decoded.data.identifier; + status = 'published'; + } + } catch { + // If we can't decode the naddr, treat as local-only + } + } + + repoMap.set(repoId, { + id: repoId, + name: project.name, + description: undefined, + status, + lastModified: project.lastModified, + localProject: project, + tags: [], + webUrls: [], + cloneUrls: [], + maintainers: [], + relays: [], + }); + } + + // Then, add or update with Nostr repos + for (const nostrRepo of nostrRepos) { + const existingRepo = repoMap.get(nostrRepo.id); + + if (existingRepo) { + // Update existing repo with Nostr data + existingRepo.nostrRepo = nostrRepo; + existingRepo.description = nostrRepo.description; + existingRepo.tags = nostrRepo.tags; + existingRepo.webUrls = nostrRepo.webUrls; + existingRepo.cloneUrls = nostrRepo.cloneUrls; + existingRepo.maintainers = nostrRepo.maintainers; + existingRepo.relays = nostrRepo.relays; + + // Update status based on local presence + if (existingRepo.localProject) { + existingRepo.status = 'synced'; + } + } else { + // Add new remote-only repo + repoMap.set(nostrRepo.id, { + id: nostrRepo.id, + name: nostrRepo.name, + description: nostrRepo.description, + status: 'remote-only', + lastModified: new Date(nostrRepo.event.created_at * 1000), + nostrRepo, + tags: nostrRepo.tags, + webUrls: nostrRepo.webUrls, + cloneUrls: nostrRepo.cloneUrls, + maintainers: nostrRepo.maintainers, + relays: nostrRepo.relays, + }); + } + } + + // Convert map to array and sort by last modified + const repos = Array.from(repoMap.values()).sort((a, b) => + b.lastModified.getTime() - a.lastModified.getTime() + ); + + return repos; + } catch (error) { + console.error('Failed to load unified repos:', error); + return []; + } + }, + enabled: !!user?.pubkey, + staleTime: 30 * 1000, // 30 seconds + gcTime: 60 * 1000, // 1 minute + }); +} \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index f8cbc6e6..5e8481d0 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -5,10 +5,10 @@ import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useOnboarding } from '@/hooks/useOnboarding'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useNostrEnabledProjects } from '@/hooks/useNostrEnabledProjects'; +import { useRepos } from '@/hooks/useRepos'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { OnboardingDialog } from '@/components/onboarding'; -import { NostrRepos } from '@/components/NostrRepos'; +import { RepoCard } from '@/components/RepoCard'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; @@ -22,14 +22,13 @@ import { cn } from '@/lib/utils'; export default function Index() { const [prompt, setPrompt] = useState(''); const [projects, setProjects] = useState([]); - const [isLoading, setIsLoading] = useState(true); const [isCreating, setIsCreating] = useState(false); const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); const navigate = useNavigate(); const projectsManager = useProjectsManager(); const isMobile = useIsMobile(); - const { user } = useCurrentUser(); - const { data: nostrEnabledProjectIds = [] } = useNostrEnabledProjects(); + const { user: _user } = useCurrentUser(); + const { data: repos = [], isLoading, error, refetch } = useRepos(); const { hasCompletedOnboarding, currentStep, @@ -60,8 +59,6 @@ export default function Index() { setProjects(projectList); } catch (error) { console.error('Failed to load projects:', error); - } finally { - setIsLoading(false); } }, [projectsManager]); @@ -92,6 +89,8 @@ export default function Index() { setIsCreating(true); try { const project = await projectsManager.createProject(prompt.trim()); + // Refresh repos after creating a new project + refetch(); navigate(`/project/${project.id}`); } catch (error) { console.error('Failed to create project:', error); @@ -100,8 +99,9 @@ export default function Index() { } }; - const handleProjectClick = (projectId: string) => { - navigate(`/project/${projectId}`); + const handleRepoRefresh = () => { + refetch(); + loadProjects(); }; const handleProjectSelect = (project: Project | null) => { @@ -133,7 +133,7 @@ export default function Index() {
{/* Spacer */} - {/* Mobile Sidebar Overlay - only show if user has projects */} + {/* Mobile Sidebar Overlay - only show if user has local projects */} {projects.length > 0 && isSidebarVisible && (
{/* Backdrop - only covers the area not occupied by the sidebar */} @@ -228,7 +228,7 @@ export default function Index() {
-

Your Projects

+

Your Repositories

{isLoading ? (
@@ -241,49 +241,33 @@ export default function Index() { ))}
- ) : projects.length === 0 ? ( + ) : error ? ( + + +

Failed to load repositories

+
+
+ ) : repos.length === 0 ? (
-

No projects yet. Create your first project above!

+

No repositories yet. Create your first project above!

) : (
- {projects.map((project) => ( - handleProjectClick(project.id)} - tabIndex={0} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - handleProjectClick(project.id); - } - }} - > - - {project.name} - - Modified {project.lastModified.toLocaleDateString()} - - - - + {repos.map((repo) => ( + ))}
)}
- - {/* Nostr Repositories Section - Mobile */} - {user && ( -
- -
- )}
@@ -298,6 +282,7 @@ export default function Index() { onProjectCreated={(projectId) => { console.log('Project created during onboarding:', projectId); setStoredPrompt(''); + handleRepoRefresh(); }} /> @@ -318,10 +303,11 @@ export default function Index() { // Handle project creation during onboarding console.log('Project created during onboarding:', projectId); setStoredPrompt(''); // Clear stored prompt after project creation + handleRepoRefresh(); }} />
- {/* Fixed Sidebar - only show if user has created projects */} + {/* Fixed Sidebar - only show if user has created local projects */} {projects.length > 0 && (
- {/* Header - only show toggle button if user has projects */} + {/* Header - only show toggle button if user has local projects */} {!isSidebarVisible && projects.length > 0 && (