From 56863d5672944d1f9fa17c231fa9082b91c0f1b1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 30 Jul 2025 15:01:59 -0500 Subject: [PATCH] Add Nostr repos list --- package-lock.json | 8 +- package.json | 2 +- src/components/NostrRepos.tsx | 254 +++++++++++++++++++++++++++ src/hooks/useNostrEnabledProjects.ts | 40 +++++ src/hooks/useNostrRepos.ts | 103 +++++++++++ src/lib/ProjectsManager.ts | 19 ++ src/pages/Index.tsx | 27 ++- 7 files changed, 444 insertions(+), 9 deletions(-) create mode 100644 src/components/NostrRepos.tsx create mode 100644 src/hooks/useNostrEnabledProjects.ts create mode 100644 src/hooks/useNostrRepos.ts diff --git a/package-lock.json b/package-lock.json index a60cd994..aaae38e5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -58,7 +58,7 @@ "jszip": "^3.10.1", "lucide-react": "^0.525.0", "next-themes": "^0.3.0", - "nostr-tools": "^2.15.1", + "nostr-tools": "^2.15.2", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", @@ -8204,9 +8204,9 @@ } }, "node_modules/nostr-tools": { - "version": "2.15.1", - "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.1.tgz", - "integrity": "sha512-LpetHDR9ltnkpJDkva/SONgyKBbsoV+5yLB8DWc0/U3lCWGtoWJw6Nbc2vR2Ai67RIQYrBQeZLyMlhwVZRK/9A==", + "version": "2.15.2", + "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.15.2.tgz", + "integrity": "sha512-utmqVVS4HMDiwhIgI6Cr+KqA4aUhF3Sb755iO/qCiqxc5H9JW/9Z3N1RO/jKWpjP6q/Vx0lru7IYuiPvk+2/ng==", "license": "Unlicense", "dependencies": { "@noble/ciphers": "^0.5.1", diff --git a/package.json b/package.json index a7dd851d..eab449cd 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "jszip": "^3.10.1", "lucide-react": "^0.525.0", "next-themes": "^0.3.0", - "nostr-tools": "^2.15.1", + "nostr-tools": "^2.15.2", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", diff --git a/src/components/NostrRepos.tsx b/src/components/NostrRepos.tsx new file mode 100644 index 00000000..630b611a --- /dev/null +++ b/src/components/NostrRepos.tsx @@ -0,0 +1,254 @@ +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" +} + +export function NostrRepos({ className, excludeProjectIds = [] }: 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, + }); + + // Create project metadata + const now = new Date(); + const metadata = { + name: repo.name, + createdAt: now.toISOString(), + lastModified: now.toISOString(), + }; + + // Save project metadata in .git directory + const gitDir = `${projectPath}/.git`; + await projectsManager.fs.writeFile( + `${gitDir}/project.json`, + JSON.stringify(metadata, null, 2) + ); + + toast({ + title: "Repository cloned", + description: `${repo.name} has been cloned to your projects.`, + }); + + // Refresh the page to update the projects list + 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/hooks/useNostrEnabledProjects.ts b/src/hooks/useNostrEnabledProjects.ts new file mode 100644 index 00000000..2dc65363 --- /dev/null +++ b/src/hooks/useNostrEnabledProjects.ts @@ -0,0 +1,40 @@ +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/useNostrRepos.ts b/src/hooks/useNostrRepos.ts new file mode 100644 index 00000000..e12711d5 --- /dev/null +++ b/src/hooks/useNostrRepos.ts @@ -0,0 +1,103 @@ +import { useQuery } from '@tanstack/react-query'; +import { useNostr } from '@nostrify/react'; +import { useCurrentUser } from './useCurrentUser'; +import type { NostrEvent } from '@nostrify/nostrify'; + +export interface NostrRepo { + event: NostrEvent; + id: string; // d tag value + name: string; + description?: string; + webUrls: string[]; + cloneUrls: string[]; + relays: string[]; + maintainers: string[]; + tags: string[]; + earliestCommit?: string; +} + +function parseRepoEvent(event: NostrEvent): NostrRepo | null { + // Validate that this is a repository announcement event + if (event.kind !== 30617) return null; + + const dTag = event.tags.find(([name]) => name === 'd')?.[1]; + if (!dTag) return null; + + const name = event.tags.find(([name]) => name === 'name')?.[1] || dTag; + const description = event.tags.find(([name]) => name === 'description')?.[1]; + + const webUrls = event.tags + .filter(([name]) => name === 'web') + .map(([, url]) => url) + .filter(Boolean); + + const cloneUrls = event.tags + .filter(([name]) => name === 'clone') + .map(([, url]) => url) + .filter(Boolean); + + const relays = event.tags + .filter(([name]) => name === 'relays') + .map(([, relay]) => relay) + .filter(Boolean); + + const maintainers = event.tags + .filter(([name]) => name === 'maintainers') + .map(([, pubkey]) => pubkey) + .filter(Boolean); + + const tags = event.tags + .filter(([name]) => name === 't') + .map(([, tag]) => tag) + .filter(Boolean); + + const earliestCommit = event.tags + .find(([name, , marker]) => name === 'r' && marker === 'euc')?.[1]; + + return { + event, + id: dTag, + name, + description, + webUrls, + cloneUrls, + relays, + maintainers, + tags, + earliestCommit, + }; +} + +export function useNostrRepos() { + const { nostr } = useNostr(); + const { user } = useCurrentUser(); + + return useQuery({ + queryKey: ['nostr-repos', user?.pubkey], + queryFn: async (c) => { + if (!user?.pubkey) return []; + + const signal = AbortSignal.any([c.signal, AbortSignal.timeout(3000)]); + + // Query for repository announcements by the current user + const events = await nostr.query([ + { + kinds: [30617], // Repository announcements + authors: [user.pubkey], + limit: 50, + } + ], { signal }); + + // Parse and validate events + const repos = events + .map(parseRepoEvent) + .filter((repo): repo is NostrRepo => repo !== null) + .sort((a, b) => b.event.created_at - a.event.created_at); + + return repos; + }, + enabled: !!user?.pubkey, + staleTime: 5 * 60 * 1000, // 5 minutes + gcTime: 10 * 60 * 1000, // 10 minutes + }); +} \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index d9086617..2c775626 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -262,6 +262,25 @@ export class ProjectsManager { } } + async getNostrRepoAddress(projectId: string): Promise { + try { + const projectPath = `${this.dir}/${projectId}`; + const config = await git.getConfig({ + fs: this.fs, + dir: projectPath, + path: 'nostr.repo', + }); + return config || null; + } catch { + return null; + } + } + + async isNostrEnabled(projectId: string): Promise { + const naddr = await this.getNostrRepoAddress(projectId); + return naddr !== null; + } + private async updateProjectLastModified(projectId: string): Promise { try { const projectFile = `${this.dir}/${projectId}/.git/project.json`; diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 5c43028a..5538f8e6 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -4,8 +4,11 @@ import { type Project } from '@/lib/ProjectsManager'; 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 { ProjectSidebar } from '@/components/ProjectSidebar'; import { OnboardingDialog } from '@/components/onboarding'; +import { NostrRepos } from '@/components/NostrRepos'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; @@ -25,6 +28,8 @@ export default function Index() { const navigate = useNavigate(); const projectsManager = useProjectsManager(); const isMobile = useIsMobile(); + const { user } = useCurrentUser(); + const { data: nostrEnabledProjectIds = [] } = useNostrEnabledProjects(); const { hasCompletedOnboarding, currentStep, @@ -276,6 +281,13 @@ export default function Index() { )} + + {/* Nostr Repositories Section - Mobile */} + {user && ( +
+ +
+ )} @@ -312,21 +324,21 @@ export default function Index() { setStoredPrompt(''); // Clear stored prompt after project creation }} /> -
+
{/* Fixed Sidebar - only show if user has created projects */} {projects.length > 0 && (
)} {/* Main Content Area */} -
-
+
+
{/* Header - only show toggle button if user has projects */} {!isSidebarVisible && projects.length > 0 && (
@@ -461,6 +473,13 @@ export default function Index() {
)}
+ + {/* Nostr Repositories Section - Desktop */} + {user && ( +
+ +
+ )}