diff --git a/AGENTS.md b/AGENTS.md index 6d787bd4..6b387b7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,6 +160,80 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - **TanStack Query**: For data fetching, caching, and state management - **TypeScript**: For type-safe JavaScript development +## Project Import + +Shakespeare supports importing existing projects from ZIP files through the main interface: + +### ZIP Import Feature + +- **Location**: Available in the sidebar under the "New Project" expand menu, below "Import Repository" +- **Function**: Upload ZIP files containing project source code with drag & drop support +- **Auto-setup**: Automatically extracts files, sets up Git repository, and creates project structure +- **Drag & Drop**: Intuitive drag and drop interface with click-to-browse fallback +- **Custom IDs**: Option to specify custom project ID or auto-generate from filename +- **Project Overwrite**: Allows overwriting existing projects with clear warnings and confirmation +- **Error Handling**: Validates ZIP files and provides clear error messages +- **Progress Tracking**: Shows import progress with visual feedback + +### ZIP Import Process + +1. Click the "New Project" button in the sidebar +2. Click the dropdown arrow (▼) to expand the menu +3. Select "Import ZIP File" from the dropdown options +4. **Upload Methods**: + - **Drag & Drop**: Drag your ZIP file directly onto the drop zone + - **Click to Browse**: Click the drop zone to open file selector +5. Review the selected file (name and size displayed) +6. Optionally specify a custom project ID (auto-generated from filename if empty) +7. **Overwrite Detection**: If project ID already exists, warning appears with option to overwrite +8. **Overwrite Confirmation**: Detailed confirmation dialog explains what will be preserved/deleted +9. Click "Import Project" or "Overwrite Project" to begin the import process +10. Wait for the import to complete (progress bar shows extraction and setup) +11. The imported project will be automatically available in the project list + +### ZIP File Requirements + +- Must be a valid ZIP archive +- Can contain any project structure (React, Node.js, static sites, etc.) +- Directory structure is preserved during import +- Maximum recommended file size: 50MB +- Existing `.git` directories are preserved if present +- New Git repository is initialized if no `.git` directory exists +- `.ai/` directory is automatically created for Shakespeare functionality + +### Project Overwrite Feature + +When importing a project with an ID that already exists: + +**What Gets Preserved:** +- **Git History**: All existing commits and repository history are maintained +- **AI Chat History**: All chat sessions and conversation data are preserved +- **Project Settings**: Configuration and metadata remain intact + +**What Gets Replaced:** +- **All Project Files**: Every file in the project directory is replaced with ZIP contents +- **Directory Structure**: New directory structure from ZIP replaces existing structure +- **Git Commit**: New commit is created documenting the overwrite action + +**Confirmation Process:** +1. Clear warning appears when duplicate project ID is detected +2. Detailed confirmation dialog lists exactly what will happen +3. User must explicitly confirm the overwrite action +4. Process cannot be undone once confirmed + +**Use Cases:** +- **Project Updates**: Import newer version of existing project +- **Template Refresh**: Update project with latest template changes +- **Migration**: Move project from different development environment + +### Integration with Existing Features + +- **Project Management**: Imported projects appear alongside AI-created projects +- **Git Integration**: Preserves existing Git history or initializes new repository +- **AI Chat**: Full AI assistance available for imported projects +- **File Operations**: All file operations work normally with imported projects +- **Build System**: Projects can be built and deployed normally + ## Project Structure - `/src/components/`: UI components including NostrProvider for Nostr integration @@ -168,6 +242,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog) - `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection) - `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane) + - `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options + - `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files - Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration @@ -182,7 +258,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `useSessionManager`: Access session management for AI chat sessions - `useGitStatus`: Real-time Git repository status monitoring - `useProjects`: Project management and CRUD operations - - `useProjectsManager`: Advanced project operations (creation, cloning, building) + - `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import) - `useTheme`: Theme management - `useToast`: Toast notifications - `useLocalStorage`: Persistent local storage diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index a99d2c7d..ba4567fe 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ -import React, { useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -9,6 +9,9 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { ZipImportDialog } from '@/components/ZipImportDialog'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useToast } from '@/hooks/useToast'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; @@ -92,6 +95,9 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); + const projectsManager = useProjectsManager(); + const { toast } = useToast(); + const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -117,6 +123,25 @@ export function ProjectSidebar({ } }; + const handleImportZip = async (file: File, customId?: string, overwrite = false) => { + try { + // Import project from zip file + const project = await projectsManager.importProjectFromZip(file, customId, 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 + } + }; + useEffect(() => { queryClient.invalidateQueries({ queryKey: ['projects'] }); }, [favorites, queryClient]); @@ -186,6 +211,13 @@ export function ProjectSidebar({ {t('importRepository')} + setIsZipDialogOpen(true)} + className="flex items-center gap-2 w-full" + > + + Import ZIP File + @@ -248,6 +280,13 @@ export function ProjectSidebar({ + + {/* ZIP Import Dialog */} + ); } \ No newline at end of file diff --git a/src/components/ZipImportDialog.tsx b/src/components/ZipImportDialog.tsx new file mode 100644 index 00000000..35a8f7ff --- /dev/null +++ b/src/components/ZipImportDialog.tsx @@ -0,0 +1,408 @@ +import React, { useState, useRef, useCallback, useEffect } from 'react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Progress } from '@/components/ui/progress'; +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; +import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react'; +import { useProjects } from '@/hooks/useProjects'; +import { cn } from '@/lib/utils'; + +interface ZipImportDialogProps { + onImport: (file: File, customId?: string, overwrite?: boolean) => Promise; + disabled?: boolean; + className?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) { + // Use controlled state if props are provided, otherwise use internal state + const [internalIsOpen, setInternalIsOpen] = useState(false); + const isOpen = open !== undefined ? open : internalIsOpen; + const setIsOpen = onOpenChange || setInternalIsOpen; + const [selectedFile, setSelectedFile] = useState(null); + const [customId, setCustomId] = useState(''); + const [isImporting, setIsImporting] = useState(false); + const [importProgress, setImportProgress] = useState(0); + const [error, setError] = useState(null); + const [isDragOver, setIsDragOver] = useState(false); + const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null); + const [showOverwriteDialog, setShowOverwriteDialog] = useState(false); + const fileInputRef = useRef(null); + const { data: projects = [] } = useProjects(); + + const handleFileSelect = (file: File) => { + // Only accept zip files + if (!file.name.toLowerCase().endsWith('.zip')) { + setError('Please select a ZIP file'); + return; + } + + setSelectedFile(file); + setError(null); + + // Auto-generate custom ID from file name + const baseName = file.name.replace(/\.zip$/i, ''); + const generatedId = baseName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + setCustomId(generatedId); + }; + + // Check for existing project when custom ID changes + useEffect(() => { + if (customId && projects.length > 0) { + const existing = projects.find(project => project.id === customId); + setExistingProject(existing || null); + } else { + setExistingProject(null); + } + }, [customId, projects]); + + // Drag and drop handlers + const handleDragOver = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(true); + }, []); + + const handleDragLeave = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + }, []); + + const handleDrop = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleDragOverDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(true); + }, []); + + const handleDragLeaveDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + }, []); + + const handleDropDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleClickUpload = () => { + fileInputRef.current?.click(); + }; + + const handleFileRemove = () => { + setSelectedFile(null); + setCustomId(''); + setError(null); + }; + + const handleImport = async (overwrite = false) => { + if (!selectedFile) return; + + setIsImporting(true); + setImportProgress(0); + setError(null); + + try { + // Simulate progress for better UX + const progressInterval = setInterval(() => { + setImportProgress(prev => Math.min(prev + 10, 90)); + }, 200); + + await onImport(selectedFile, customId || undefined, overwrite); + + clearInterval(progressInterval); + setImportProgress(100); + + // Close dialog after a short delay + setTimeout(() => { + setIsOpen(false); + setSelectedFile(null); + setCustomId(''); + setImportProgress(0); + setExistingProject(null); + }, 1000); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to import project'); + setImportProgress(0); + } finally { + setIsImporting(false); + } + }; + + const handleImportWithOverwriteCheck = async () => { + if (!selectedFile || !customId) return; + + // Check if project with this ID already exists + try { + // This would ideally be passed as a prop or through context + // For now, we'll assume the parent will handle the check and pass existing project info + if (existingProject) { + setShowOverwriteDialog(true); + } else { + await handleImport(false); + } + } catch (error) { + console.error('Error checking existing project:', error); + await handleImport(false); + } + }; + + const confirmOverwrite = async () => { + setShowOverwriteDialog(false); + await handleImport(true); + }; + + const handleClose = () => { + if (!isImporting) { + setIsOpen(false); + setSelectedFile(null); + setCustomId(''); + setError(null); + setImportProgress(0); + } + }; + + return ( + <> + + + + + + + + + + Import Project from ZIP + + + Upload a ZIP file containing your project source code to import it into Shakespeare. + + + +
+ {!isImporting && ( + <> + {/* Drag and Drop Area */} +
+ { + const files = e.target.files; + if (files && files.length > 0) { + handleFileSelect(files[0]); + } + }} + accept=".zip" + className="hidden" + disabled={isImporting} + /> + +
+
+ {selectedFile ? ( + + ) : ( + + )} +
+ +
+ {selectedFile ? ( +
+

+ {selectedFile.name} +

+

+ {(selectedFile.size / 1024 / 1024).toFixed(2)} MB +

+ +
+ ) : ( +
+

+ Drop your ZIP file here or click to browse +

+

+ Supports ZIP files up to 50MB +

+
+ )} +
+
+
+ + {/* Error Display */} + {error && ( +
+ + {error} +
+ )} + + {/* Custom Project ID */} +
+ + setCustomId(e.target.value)} + placeholder="project-name" + className="w-full px-3 py-2 text-sm border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" + disabled={isImporting} + /> +

+ Auto-generated from filename. Only use lowercase letters, numbers, and hyphens. +

+ {existingProject && ( +
+ + A project with this ID already exists. You can choose to overwrite it. +
+ )} +
+ + {/* Import Button */} +
+ + +
+ + )} + + {/* Import Progress */} + {isImporting && ( +
+
+
+ Importing project... +
+ +

+ Extracting files and setting up project... +

+
+ )} + + {/* Success State */} + {!isImporting && importProgress === 100 && ( +
+ + + + Project imported successfully! +
+ )} +
+
+
+ + {/* Overwrite Confirmation Dialog */} + + + + + + Overwrite Existing Project + + +

+ A project with the ID "{customId}" already exists. + Overwriting it will: +

+
    +
  • Delete all existing files in the project
  • +
  • Replace them with files from the ZIP archive
  • +
  • Preserve Git history if it exists
  • +
  • Keep AI chat history and session data
  • +
+

+ This action cannot be undone. Are you sure you want to continue? +

+
+
+ + Cancel + + Yes, Overwrite Project + + +
+
+ + ); +} \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 91af47ab..817abd2a 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -1,4 +1,5 @@ import { Buffer } from 'buffer'; +import JSZip from 'jszip'; import { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -91,6 +92,161 @@ export class ProjectsManager { return project; } + async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { + // Generate a project ID based on the zip file name or use custom ID + const baseName = zipFile.name.replace(/\.zip$/i, ''); + const id = customId || await this.generateUniqueProjectId(baseName); + + const projectPath = `${this.dir}/${id}`; + const projectExists = await this.projectExists(id); + + // Check if project with this ID already exists when not overwriting + if (projectExists && !overwrite) { + throw new Error(`Project with ID "${id}" already exists`); + } + + try { + // Create project directory (or ensure it exists for overwrite) + await this.fs.mkdir(projectPath, { recursive: true }); + + // If overwriting, delete existing files except .ai directory and .git directory + if (projectExists && overwrite) { + const existingFiles = await this.getAllFiles(projectPath); + for (const file of existingFiles) { + // Preserve .ai directory and .git directory + if (!file.startsWith('.ai/') && !file.startsWith('.git/')) { + try { + await this.fs.unlink(`${projectPath}/${file}`); + } catch { + // Ignore deletion errors + } + } + } + } + + // Read the zip file + const arrayBuffer = await zipFile.arrayBuffer(); + const zip = await JSZip.loadAsync(arrayBuffer); + + // Extract all files from the zip + const files = Object.keys(zip.files); + + for (const filePath of files) { + const zipEntry = zip.files[filePath]; + + // Skip directories (they end with / in JSZip) + if (zipEntry.dir) { + // Create the directory structure + const dirPath = `${projectPath}/${filePath}`; + await this.fs.mkdir(dirPath, { recursive: true }); + continue; + } + + // Extract file content + const content = await zipEntry.async('uint8array'); + const fullPath = `${projectPath}/${filePath}`; + + // Ensure parent directory exists + const dirPath = fullPath.split('/').slice(0, -1).join('/'); + if (dirPath) { + await this.fs.mkdir(dirPath, { recursive: true }); + } + + // Write the file (this will overwrite existing files) + await this.fs.writeFile(fullPath, content); + } + + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Initialize git repository if there's no .git directory + try { + await this.fs.stat(`${projectPath}/.git`); + + // If git exists and we're overwriting, stage the new files + if (overwrite) { + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + try { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } catch { + // Ignore git add errors for files that might be gitignored + } + } + } + + // Make commit for the overwrite + await this.git.commit({ + dir: projectPath, + message: `Overwrite project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + } catch { + // No .git directory found, initialize new repository + await this.git.init({ + dir: projectPath, + defaultBranch: 'main', + }); + + // Add all files to git (excluding .ai directory) + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } + } + + // Make initial commit + await this.git.commit({ + dir: projectPath, + message: `Import project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + + // Create .ai/history directory + try { + await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true }); + } catch { + // Directory might already exist + } + + return { + id, + name: this.formatProjectName(id), + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up on error (only if this was a new project creation) + if (!projectExists) { + try { + await this.deleteDirectory(projectPath); + } catch { + // Ignore cleanup errors + } + } + throw error; + } + } + async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise { const id = customId || await this.generateUniqueProjectId(name); diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index d8f3b6d6..430c1228 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -115,11 +115,18 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); + toast({ + title: "Project Creation Failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); } finally { setIsCreating(false); } }; + + const headerContent = null; return (