Add Nostr repos list

This commit is contained in:
Alex Gleason committed 2025-07-30 15:01:59 -05:00
1 parent 2ff99b7116
commit 56863d5672
7 files changed
+444 -9

No files matched your search

+254
View File
@@ -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<Set<string>>(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 (
<div className={cn("space-y-4", className)}>
<h2 className="text-xl md:text-2xl font-semibold">Your Nostr Repositories</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(3)].map((_, i) => (
<Card key={i}>
<CardHeader className="pb-2">
<Skeleton className="h-5 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3" />
</CardContent>
</Card>
))}
</div>
</div>
);
}
if (error) {
return (
<div className={cn("space-y-4", className)}>
<h2 className="text-xl md:text-2xl font-semibold">Your Nostr Repositories</h2>
<Card className="border-destructive/20">
<CardContent className="py-6 text-center">
<p className="text-destructive">Failed to load repositories</p>
</CardContent>
</Card>
</div>
);
}
if (!availableRepos.length) {
return null; // Don't show the section if there are no repos to display
}
return (
<div className={cn("space-y-4", className)}>
<h2 className="text-xl md:text-2xl font-semibold">Your Nostr Repositories</h2>
<p className="text-muted-foreground text-sm">
Clone your NIP-34 repositories to start working on them locally.
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{availableRepos.map((repo) => {
const isCloning = cloningRepos.has(repo.id);
return (
<Card
key={repo.id}
className="bg-gradient-to-br from-card to-card/80 border-primary/10 hover:border-primary/20 transition-all duration-300"
>
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<CardTitle className="text-base md:text-lg flex items-center gap-2 truncate">
<GitBranch className="h-4 w-4 text-primary flex-shrink-0" />
<span className="truncate">{repo.name}</span>
</CardTitle>
{repo.description && (
<CardDescription className="text-sm mt-1 line-clamp-2">
{repo.description}
</CardDescription>
)}
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{/* Tags */}
{repo.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{repo.tags.slice(0, 3).map((tag) => (
<Badge key={tag} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.tags.length > 3 && (
<Badge variant="outline" className="text-xs">
+{repo.tags.length - 3}
</Badge>
)}
</div>
)}
{/* Repository info */}
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{repo.maintainers.length > 0 && (
<div className="flex items-center gap-1">
<Users className="h-3 w-3" />
<span>{repo.maintainers.length} maintainer{repo.maintainers.length !== 1 ? 's' : ''}</span>
</div>
)}
{repo.webUrls.length > 0 && (
<div className="flex items-center gap-1">
<Globe className="h-3 w-3" />
<span>Web</span>
</div>
)}
</div>
{/* Actions */}
<div className="flex gap-2">
<Button
onClick={() => handleCloneRepo(repo)}
disabled={isCloning || !repo.cloneUrls.length}
className="flex-1"
size="sm"
>
{isCloning ? (
<>
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-2"></div>
Cloning...
</>
) : (
<>
<Download className="h-3 w-3 mr-2" />
Clone
</>
)}
</Button>
{repo.webUrls.length > 0 && (
<Button
variant="outline"
size="sm"
onClick={() => window.open(repo.webUrls[0], '_blank')}
className="px-3"
>
<ExternalLink className="h-3 w-3" />
</Button>
)}
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}
+40
View File
@@ -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
});
}
+103
View File
@@ -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
});
}
+19
View File
@@ -262,6 +262,25 @@ export class ProjectsManager {
}
}
async getNostrRepoAddress(projectId: string): Promise<string | null> {
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<boolean> {
const naddr = await this.getNostrRepoAddress(projectId);
return naddr !== null;
}
private async updateProjectLastModified(projectId: string): Promise<void> {
try {
const projectFile = `${this.dir}/${projectId}/.git/project.json`;
+23 -4
View File
@@ -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() {
</div>
)}
</div>
{/* Nostr Repositories Section - Mobile */}
{user && (
<div className="mt-8">
<NostrRepos excludeProjectIds={nostrEnabledProjectIds} />
</div>
)}
</div>
</div>
@@ -312,21 +324,21 @@ export default function Index() {
setStoredPrompt(''); // Clear stored prompt after project creation
}}
/>
<div className="h-screen flex bg-background">
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - only show if user has created projects */}
{projects.length > 0 && (
<div className={cn("w-80 border-r bg-sidebar transition-all duration-300", isSidebarVisible ? "block" : "hidden")}>
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
className="h-full"
className="h-screen sticky top-0"
/>
</div>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col overflow-hidden bg-background">
<div className="min-h-full bg-gradient-to-br from-primary/5 to-accent/5">
<div className="flex-1 flex flex-col bg-background">
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5">
{/* Header - only show toggle button if user has projects */}
{!isSidebarVisible && projects.length > 0 && (
<header className="border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center">
@@ -461,6 +473,13 @@ export default function Index() {
</div>
)}
</div>
{/* Nostr Repositories Section - Desktop */}
{user && (
<div className="mt-8">
<NostrRepos excludeProjectIds={nostrEnabledProjectIds} />
</div>
)}
</div>
</div>
</div>