mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Compare commits
10
Commits
v9.16.3
...
zipBulkImport
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898c6a8286 | ||
|
|
7f14194ae4 | ||
|
|
2ea05addcc | ||
|
|
9507177aaa | ||
|
|
669bbb8a1f | ||
|
|
15567ee4cf | ||
|
|
2d163e8fed | ||
|
|
f6f9a0038b | ||
|
|
c26f447072 | ||
|
|
3253b198c7 |
No files matched your search
@@ -0,0 +1,685 @@
|
|||||||
|
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 { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react';
|
||||||
|
import { useProjects } from '@/hooks/useProjects';
|
||||||
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import JSZip from 'jszip';
|
||||||
|
|
||||||
|
interface ProjectInfo {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
path: string;
|
||||||
|
files: string[];
|
||||||
|
isConflict: boolean;
|
||||||
|
selected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProjectImportDialogProps {
|
||||||
|
mode?: 'single' | 'bulk';
|
||||||
|
onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise<void>;
|
||||||
|
disabled?: boolean;
|
||||||
|
className?: string;
|
||||||
|
open?: boolean;
|
||||||
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectImportDialog({
|
||||||
|
mode = 'single',
|
||||||
|
onImport,
|
||||||
|
disabled = false,
|
||||||
|
className,
|
||||||
|
open,
|
||||||
|
onOpenChange
|
||||||
|
}: ProjectImportDialogProps) {
|
||||||
|
// 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<File | null>(null);
|
||||||
|
const [generatedId, setGeneratedId] = useState('');
|
||||||
|
const [discoveredProjects, setDiscoveredProjects] = useState<ProjectInfo[]>([]);
|
||||||
|
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||||
|
const [isImporting, setIsImporting] = useState(false);
|
||||||
|
const [importProgress, setImportProgress] = useState(0);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||||
|
const [zipData, setZipData] = useState<JSZip | null>(null);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const { data: existingProjects = [] } = useProjects();
|
||||||
|
const projectsManager = useProjectsManager();
|
||||||
|
|
||||||
|
// Analyze ZIP for bulk import
|
||||||
|
const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
|
||||||
|
const projects: ProjectInfo[] = [];
|
||||||
|
const projectPaths = new Set<string>();
|
||||||
|
|
||||||
|
// Find all potential project directories
|
||||||
|
for (const [path] of Object.entries(zip.files)) {
|
||||||
|
const pathParts = path.split('/').filter(part => part !== '');
|
||||||
|
|
||||||
|
// Skip files in root directory - we're looking for project directories
|
||||||
|
if (pathParts.length < 2) continue;
|
||||||
|
|
||||||
|
// Check if this looks like a project indicator file
|
||||||
|
if (isProjectIndicator(path)) {
|
||||||
|
let projectPath: string;
|
||||||
|
|
||||||
|
// If structure is projects/project-name/file, extract project-name
|
||||||
|
if (pathParts[0] === 'projects' && pathParts.length >= 3) {
|
||||||
|
projectPath = `projects/${pathParts[1]}`;
|
||||||
|
} else {
|
||||||
|
// Otherwise, assume first directory is the project
|
||||||
|
projectPath = pathParts[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
projectPaths.add(projectPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For each discovered project path, gather information
|
||||||
|
for (const projectPath of projectPaths) {
|
||||||
|
const files: string[] = [];
|
||||||
|
|
||||||
|
// Collect all files in this project directory
|
||||||
|
for (const [path, zipEntry] of Object.entries(zip.files)) {
|
||||||
|
if (path.startsWith(projectPath + '/') && !zipEntry.dir) {
|
||||||
|
const relativePath = path.substring(projectPath.length + 1);
|
||||||
|
files.push(relativePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate project ID and name from directory path
|
||||||
|
let id: string;
|
||||||
|
let name: string;
|
||||||
|
|
||||||
|
if (projectPath.startsWith('projects/')) {
|
||||||
|
const projectName = projectPath.substring('projects/'.length);
|
||||||
|
id = projectName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
name = projectName;
|
||||||
|
} else {
|
||||||
|
id = projectPath
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
name = projectPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip if no files found (empty directory)
|
||||||
|
if (files.length === 0) continue;
|
||||||
|
|
||||||
|
// Check if this project conflicts with existing projects
|
||||||
|
const isConflict = existingProjects.some(existing => existing.id === id);
|
||||||
|
|
||||||
|
projects.push({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
path: projectPath,
|
||||||
|
files,
|
||||||
|
isConflict,
|
||||||
|
selected: !isConflict, // Auto-select non-conflicting projects
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return projects;
|
||||||
|
}, [existingProjects]);
|
||||||
|
|
||||||
|
// Handle file selection
|
||||||
|
const handleFileSelect = useCallback(async (file: File) => {
|
||||||
|
// Only accept zip files
|
||||||
|
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||||
|
setError('Please select a ZIP file');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelectedFile(file);
|
||||||
|
setError(null);
|
||||||
|
setGeneratedId('');
|
||||||
|
|
||||||
|
// Auto-generate ID from file name for single mode
|
||||||
|
if (mode === 'single') {
|
||||||
|
const baseName = file.name.replace(/\.zip$/i, '');
|
||||||
|
const id = baseName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
setGeneratedId(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For bulk mode, analyze the ZIP to discover projects
|
||||||
|
if (mode === 'bulk') {
|
||||||
|
setIsAnalyzing(true);
|
||||||
|
setDiscoveredProjects([]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const arrayBuffer = await file.arrayBuffer();
|
||||||
|
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||||
|
setZipData(zip);
|
||||||
|
|
||||||
|
const projects = await analyzeZipForProjects(zip);
|
||||||
|
setDiscoveredProjects(projects);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
|
||||||
|
} finally {
|
||||||
|
setIsAnalyzing(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [mode, analyzeZipForProjects]);
|
||||||
|
|
||||||
|
|
||||||
|
const isProjectIndicator = (path: string): boolean => {
|
||||||
|
const indicators = [
|
||||||
|
'package.json',
|
||||||
|
'index.html',
|
||||||
|
'src/',
|
||||||
|
'public/',
|
||||||
|
'tsconfig.json',
|
||||||
|
'vite.config.',
|
||||||
|
'webpack.config.',
|
||||||
|
'README.md',
|
||||||
|
'.git/',
|
||||||
|
];
|
||||||
|
|
||||||
|
return indicators.some(indicator => path.includes('/' + indicator));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check for existing project when generated ID changes (single mode)
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode === 'single' && generatedId && existingProjects.length > 0) {
|
||||||
|
const existing = existingProjects.find(project => project.id === generatedId);
|
||||||
|
if (existing) {
|
||||||
|
setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`);
|
||||||
|
} else {
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [generatedId, existingProjects, mode]);
|
||||||
|
|
||||||
|
// 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]);
|
||||||
|
}
|
||||||
|
}, [handleFileSelect]);
|
||||||
|
|
||||||
|
const handleClickUpload = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileRemove = () => {
|
||||||
|
setSelectedFile(null);
|
||||||
|
setGeneratedId('');
|
||||||
|
setDiscoveredProjects([]);
|
||||||
|
setZipData(null);
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bulk import project selection handlers
|
||||||
|
const handleProjectToggle = (projectId: string, checked: boolean) => {
|
||||||
|
setDiscoveredProjects(prev =>
|
||||||
|
prev.map(project =>
|
||||||
|
project.id === projectId ? { ...project, selected: checked } : project
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSelectAll = () => {
|
||||||
|
setDiscoveredProjects(prev =>
|
||||||
|
prev.map(project => ({ ...project, selected: true }))
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeselectAll = () => {
|
||||||
|
setDiscoveredProjects(prev =>
|
||||||
|
prev.map(project => ({ ...project, selected: false }))
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectedProjects = discoveredProjects.filter(project => project.selected);
|
||||||
|
const conflictingProjects = selectedProjects.filter(project => project.isConflict);
|
||||||
|
|
||||||
|
const handleImport = async (overwrite = false) => {
|
||||||
|
if (!selectedFile) return;
|
||||||
|
|
||||||
|
setIsImporting(true);
|
||||||
|
setImportProgress(0);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (mode === 'single') {
|
||||||
|
// Single project import
|
||||||
|
const progressInterval = setInterval(() => {
|
||||||
|
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||||
|
}, 200);
|
||||||
|
|
||||||
|
await onImport({ file: selectedFile, projectId: generatedId }, overwrite);
|
||||||
|
|
||||||
|
clearInterval(progressInterval);
|
||||||
|
setImportProgress(100);
|
||||||
|
} else {
|
||||||
|
// Bulk project import
|
||||||
|
const projectsToImport = await Promise.all(
|
||||||
|
selectedProjects.map(async (project) => {
|
||||||
|
const files = await projectsManager.extractFilesFromZip(zipData!, project.path);
|
||||||
|
return {
|
||||||
|
id: project.id,
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const progressInterval = setInterval(() => {
|
||||||
|
setImportProgress(prev => Math.min(prev + 5, 90));
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
await onImport({ projects: projectsToImport }, overwrite);
|
||||||
|
|
||||||
|
clearInterval(progressInterval);
|
||||||
|
setImportProgress(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close dialog and reset state immediately
|
||||||
|
setIsOpen(false);
|
||||||
|
handleFileRemove();
|
||||||
|
setImportProgress(0);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to import projects');
|
||||||
|
setImportProgress(0);
|
||||||
|
} finally {
|
||||||
|
setIsImporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportWithOverwriteCheck = async () => {
|
||||||
|
if (mode === 'single') {
|
||||||
|
// For single mode, check if project exists
|
||||||
|
const existingProject = existingProjects.find(project => project.id === generatedId);
|
||||||
|
if (existingProject) {
|
||||||
|
setShowOverwriteDialog(true);
|
||||||
|
} else {
|
||||||
|
await handleImport(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For bulk mode, check for conflicts
|
||||||
|
if (conflictingProjects.length > 0) {
|
||||||
|
setShowOverwriteDialog(true);
|
||||||
|
} else {
|
||||||
|
await handleImport(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmOverwrite = async () => {
|
||||||
|
setShowOverwriteDialog(false);
|
||||||
|
await handleImport(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
if (!isImporting && !isAnalyzing) {
|
||||||
|
setIsOpen(false);
|
||||||
|
handleFileRemove();
|
||||||
|
setImportProgress(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||||
|
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||||
|
|
||||||
|
const canImport = mode === 'single'
|
||||||
|
? selectedFile && generatedId
|
||||||
|
: selectedProjects.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||||
|
{!isControlled && (
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={disabled}
|
||||||
|
className={cn("gap-2", className)}
|
||||||
|
>
|
||||||
|
<FileArchive className="h-4 w-4" />
|
||||||
|
{mode === 'single' ? 'Import ZIP' : 'Import Projects'}
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DialogContent className={cn(
|
||||||
|
"h-auto max-h-[90vh] flex flex-col",
|
||||||
|
mode === 'single' ? "sm:max-w-md" : "sm:max-w-xl"
|
||||||
|
)}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<Upload className="h-5 w-5" />
|
||||||
|
{mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{mode === 'single'
|
||||||
|
? 'Upload a ZIP file containing your project source code to import it into Shakespeare.'
|
||||||
|
: 'Upload a ZIP file containing multiple projects to import them into Shakespeare.'
|
||||||
|
}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex-1 flex flex-col overflow-hidden min-h-0 space-y-4">
|
||||||
|
{!isImporting && !isAnalyzing && (
|
||||||
|
<>
|
||||||
|
{/* Drag and Drop Area */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer",
|
||||||
|
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||||
|
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||||
|
)}
|
||||||
|
onClick={handleClickUpload}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
onChange={(e) => {
|
||||||
|
const files = e.target.files;
|
||||||
|
if (files && files.length > 0) {
|
||||||
|
handleFileSelect(files[0]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
accept=".zip"
|
||||||
|
className="hidden"
|
||||||
|
disabled={isImporting || isAnalyzing}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
{selectedFile ? (
|
||||||
|
<FileText className="h-6 w-6 text-green-600" />
|
||||||
|
) : (
|
||||||
|
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{selectedFile ? (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-medium text-green-600">
|
||||||
|
{selectedFile.name}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleFileRemove();
|
||||||
|
}}
|
||||||
|
className="text-xs text-destructive hover:underline"
|
||||||
|
>
|
||||||
|
Remove file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
Drop your ZIP file here or click to browse
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{mode === 'single'
|
||||||
|
? 'Supports ZIP files up to 50MB'
|
||||||
|
: 'Supports ZIP files containing exported Shakespeare projects'
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error Display */}
|
||||||
|
{error && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-amber-600 mb-4">
|
||||||
|
<AlertTriangle className="h-4 w-4" />
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Project List (Bulk Mode Only) */}
|
||||||
|
{mode === 'bulk' && discoveredProjects.length > 0 && (
|
||||||
|
<div className="space-y-3 flex-1 flex flex-col min-h-0">
|
||||||
|
<div className="flex items-center justify-between flex-shrink-0">
|
||||||
|
<h3 className="text-sm font-medium">
|
||||||
|
Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}
|
||||||
|
</h3>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleSelectAll}
|
||||||
|
className="h-8 text-xs"
|
||||||
|
>
|
||||||
|
<CheckSquare className="h-3 w-3 mr-1" />
|
||||||
|
Select All
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleDeselectAll}
|
||||||
|
className="h-8 text-xs"
|
||||||
|
>
|
||||||
|
<Square className="h-3 w-3 mr-1" />
|
||||||
|
Deselect All
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border rounded-lg overflow-hidden">
|
||||||
|
<ScrollArea className="h-64">
|
||||||
|
<div className="p-2 space-y-1">
|
||||||
|
{discoveredProjects.map((project) => (
|
||||||
|
<div
|
||||||
|
key={project.id}
|
||||||
|
className={cn(
|
||||||
|
"flex items-start space-x-3 p-2 rounded-lg border transition-colors",
|
||||||
|
project.selected ? "bg-primary/5 border-primary/20" : "bg-background",
|
||||||
|
project.isConflict && "border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Checkbox
|
||||||
|
id={`project-${project.id}`}
|
||||||
|
checked={project.selected}
|
||||||
|
onCheckedChange={(checked) => handleProjectToggle(project.id, checked as boolean)}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
<div className="flex-1 min-w-0 space-y-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<FolderOpen className="h-4 w-4 text-primary flex-shrink-0" />
|
||||||
|
<span className="font-medium text-sm truncate">{project.name}</span>
|
||||||
|
{project.isConflict && (
|
||||||
|
<div className="hidden sm:flex items-center gap-1 text-amber-600 flex-shrink-0">
|
||||||
|
<AlertTriangle className="h-3 w-3" />
|
||||||
|
<span className="text-xs">Conflict</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{project.isConflict && (
|
||||||
|
<div className="sm:hidden flex items-center gap-1 text-amber-600">
|
||||||
|
<AlertTriangle className="h-3 w-3" />
|
||||||
|
<span className="text-xs font-medium">Conflict - Will overwrite existing project</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{project.files.length} file{project.files.length !== 1 ? 's' : ''}
|
||||||
|
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Import Button */}
|
||||||
|
{selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
|
||||||
|
<div className="flex justify-end gap-2 pt-3 border-t flex-shrink-0">
|
||||||
|
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleImportWithOverwriteCheck}
|
||||||
|
disabled={!canImport || isImporting}
|
||||||
|
className={mode === 'single' && error ? "bg-amber-600 hover:bg-amber-700" : conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||||
|
>
|
||||||
|
{mode === 'single' ? (
|
||||||
|
error ? (
|
||||||
|
<>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Overwrite Project
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload className="mr-2 h-4 w-4" />
|
||||||
|
Import Project
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{conflictingProjects.length > 0 ? <Trash2 className="mr-2 h-4 w-4" /> : <Upload className="mr-2 h-4 w-4" />}
|
||||||
|
{conflictingProjects.length > 0 ? 'Import & Overwrite' : 'Import Projects'} ({selectedProjects.length})
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Analysis Progress (Bulk Mode Only) */}
|
||||||
|
{mode === 'bulk' && isAnalyzing && (
|
||||||
|
<div className="space-y-2 py-6">
|
||||||
|
<div className="flex items-center gap-2 text-sm justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||||
|
Analyzing ZIP file...
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
|
Discovering projects and checking for conflicts...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Import Progress */}
|
||||||
|
{isImporting && (
|
||||||
|
<div className="space-y-3 py-6">
|
||||||
|
<div className="flex items-center gap-2 text-sm justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div >
|
||||||
|
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}
|
||||||
|
</div>
|
||||||
|
<Progress value={importProgress} className="w-full" />
|
||||||
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
|
Extracting files and setting up projects...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Success State */}
|
||||||
|
{!isImporting && !isAnalyzing && importProgress === 100 && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-green-600 justify-center py-3">
|
||||||
|
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||||
|
</svg>
|
||||||
|
{mode === 'single' ? 'Project imported successfully!' : 'Projects imported successfully!'}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Overwrite Confirmation Dialog */}
|
||||||
|
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle className="flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||||
|
{mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'}
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription className="space-y-3">
|
||||||
|
{mode === 'single' ? (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
A project with ID "<strong>{generatedId}</strong>" already exists.
|
||||||
|
Overwriting it will:
|
||||||
|
</p>
|
||||||
|
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||||
|
<li><strong>Delete all existing files</strong> in project</li>
|
||||||
|
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||||
|
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||||
|
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
You have selected <strong>{conflictingProjects.length}</strong> project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:
|
||||||
|
</p>
|
||||||
|
<ul className="list-disc list-inside text-sm space-y-1 ml-2 max-h-32 overflow-y-auto">
|
||||||
|
{conflictingProjects.map((project) => (
|
||||||
|
<li key={project.id}>
|
||||||
|
<strong>{project.name}</strong> (ID: {project.id})
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<p>Overwriting will:</p>
|
||||||
|
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||||
|
<li><strong>Delete all existing files</strong> in these projects</li>
|
||||||
|
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||||
|
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||||
|
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<p className="text-amber-600 font-medium">
|
||||||
|
This action cannot be undone. Are you sure you want to continue?
|
||||||
|
</p>
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={confirmOverwrite}
|
||||||
|
className="bg-amber-600 hover:bg-amber-700"
|
||||||
|
>
|
||||||
|
Yes, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -118,8 +118,6 @@ export function ProjectSidebar({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||||
}, [favorites, queryClient]);
|
}, [favorites, queryClient]);
|
||||||
@@ -251,8 +249,6 @@ export function ProjectSidebar({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,203 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
|
||||||
import { ZipImportDialog } from './ZipImportDialog';
|
|
||||||
import { TestApp } from '@/test/TestApp';
|
|
||||||
|
|
||||||
// Mock the useProjects hook
|
|
||||||
const mockProjects = [
|
|
||||||
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
|
|
||||||
];
|
|
||||||
|
|
||||||
vi.mock('@/hooks/useProjects', () => ({
|
|
||||||
useProjects: () => ({
|
|
||||||
data: mockProjects,
|
|
||||||
isLoading: false,
|
|
||||||
error: null
|
|
||||||
})
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('ZipImportDialog', () => {
|
|
||||||
const mockOnImport = vi.fn();
|
|
||||||
const defaultProps = {
|
|
||||||
onImport: mockOnImport,
|
|
||||||
disabled: false
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockOnImport.mockClear();
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renders dialog trigger button', () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('opens dialog when trigger is clicked', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('processes file selection without displaying project ID', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open dialog
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
// Create a mock file
|
|
||||||
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
|
|
||||||
|
|
||||||
// Find the hidden file input by ref
|
|
||||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
|
||||||
|
|
||||||
if (fileInput) {
|
|
||||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
||||||
}
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
// Verify that the file name is displayed (from the file selection area)
|
|
||||||
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
|
|
||||||
// Verify that Project ID label is not displayed
|
|
||||||
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows overwrite warning when project ID already exists', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open dialog
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
// Create a mock file that will generate an existing project ID
|
|
||||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
|
||||||
|
|
||||||
// Find the hidden file input by ref
|
|
||||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
|
||||||
|
|
||||||
if (fileInput) {
|
|
||||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
||||||
}
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
|
|
||||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls onImport with correct parameters when import button is clicked', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open dialog
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
// Create a mock file
|
|
||||||
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
|
||||||
|
|
||||||
// Find the hidden file input by ref
|
|
||||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
|
||||||
|
|
||||||
if (fileInput) {
|
|
||||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for file to be processed
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Click import button
|
|
||||||
const importButton = screen.getByText('Import Project');
|
|
||||||
fireEvent.click(importButton);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open dialog
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
// Create a mock file that will generate an existing project ID
|
|
||||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
|
||||||
|
|
||||||
// Find the hidden file input by ref
|
|
||||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
|
||||||
|
|
||||||
if (fileInput) {
|
|
||||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for overwrite button to appear
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Click overwrite button
|
|
||||||
const overwriteButton = screen.getByText('Overwrite Project');
|
|
||||||
fireEvent.click(overwriteButton);
|
|
||||||
|
|
||||||
// Check for overwrite confirmation dialog
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
|
|
||||||
// Use a more flexible matcher for the text that might be split across elements
|
|
||||||
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
|
|
||||||
if (dialogContent) {
|
|
||||||
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
|
|
||||||
}
|
|
||||||
}, { timeout: 2000 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not show project ID input field (simplified interface)', async () => {
|
|
||||||
render(
|
|
||||||
<TestApp>
|
|
||||||
<ZipImportDialog {...defaultProps} />
|
|
||||||
</TestApp>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open dialog
|
|
||||||
const triggerButton = screen.getByText('Import ZIP');
|
|
||||||
fireEvent.click(triggerButton);
|
|
||||||
|
|
||||||
// Check that there's no input field for project ID
|
|
||||||
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
|
|
||||||
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,397 +0,0 @@
|
|||||||
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, overwrite?: boolean, projectId?: string) => Promise<void>;
|
|
||||||
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<File | null>(null);
|
|
||||||
const [generatedId, setGeneratedId] = useState('');
|
|
||||||
const [isImporting, setIsImporting] = useState(false);
|
|
||||||
const [importProgress, setImportProgress] = useState(0);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [isDragOver, setIsDragOver] = useState(false);
|
|
||||||
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
|
||||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(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 ID from file name
|
|
||||||
const baseName = file.name.replace(/\.zip$/i, '');
|
|
||||||
const id = baseName
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/[^a-z0-9]+/g, '-')
|
|
||||||
.replace(/^-+|-+$/g, '');
|
|
||||||
setGeneratedId(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check for existing project when generated ID changes
|
|
||||||
useEffect(() => {
|
|
||||||
if (generatedId && projects.length > 0) {
|
|
||||||
const existing = projects.find(project => project.id === generatedId);
|
|
||||||
setExistingProject(existing || null);
|
|
||||||
} else {
|
|
||||||
setExistingProject(null);
|
|
||||||
}
|
|
||||||
}, [generatedId, 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);
|
|
||||||
setGeneratedId('');
|
|
||||||
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, overwrite, generatedId);
|
|
||||||
|
|
||||||
clearInterval(progressInterval);
|
|
||||||
setImportProgress(100);
|
|
||||||
|
|
||||||
// Close dialog after a short delay
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsOpen(false);
|
|
||||||
setSelectedFile(null);
|
|
||||||
setGeneratedId('');
|
|
||||||
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 || !generatedId) 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);
|
|
||||||
setGeneratedId('');
|
|
||||||
setError(null);
|
|
||||||
setImportProgress(0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
|
||||||
// (no open/onOpenChange props provided)
|
|
||||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
|
||||||
{!isControlled && (
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
disabled={disabled}
|
|
||||||
className={cn("gap-2", className)}
|
|
||||||
>
|
|
||||||
<FileArchive className="h-4 w-4" />
|
|
||||||
Import ZIP
|
|
||||||
</Button>
|
|
||||||
</DialogTrigger>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DialogContent
|
|
||||||
className="sm:max-w-md"
|
|
||||||
onDragOver={handleDragOverDialog}
|
|
||||||
onDragLeave={handleDragLeaveDialog}
|
|
||||||
onDrop={handleDropDialog}
|
|
||||||
>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle className="flex items-center gap-2">
|
|
||||||
<Upload className="h-5 w-5" />
|
|
||||||
Import Project from ZIP
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
{!isImporting && (
|
|
||||||
<>
|
|
||||||
{/* Drag and Drop Area */}
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
|
||||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
|
||||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
|
||||||
)}
|
|
||||||
onClick={handleClickUpload}
|
|
||||||
onDragOver={handleDragOver}
|
|
||||||
onDragLeave={handleDragLeave}
|
|
||||||
onDrop={handleDrop}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
ref={fileInputRef}
|
|
||||||
type="file"
|
|
||||||
onChange={(e) => {
|
|
||||||
const files = e.target.files;
|
|
||||||
if (files && files.length > 0) {
|
|
||||||
handleFileSelect(files[0]);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
accept=".zip"
|
|
||||||
className="hidden"
|
|
||||||
disabled={isImporting}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex justify-center">
|
|
||||||
{selectedFile ? (
|
|
||||||
<FileText className="h-8 w-8 text-green-600" />
|
|
||||||
) : (
|
|
||||||
<Upload className="h-8 w-8 text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
{selectedFile ? (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<p className="text-sm font-medium text-green-600">
|
|
||||||
{selectedFile.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleFileRemove();
|
|
||||||
}}
|
|
||||||
className="text-xs text-destructive hover:underline"
|
|
||||||
>
|
|
||||||
Remove file
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<p className="text-sm font-medium">
|
|
||||||
Drop your ZIP file here or click to browse
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Supports ZIP files up to 50MB
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Error Display */}
|
|
||||||
{error && (
|
|
||||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
|
||||||
<AlertCircle className="h-4 w-4" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Overwrite Warning */}
|
|
||||||
{existingProject && (
|
|
||||||
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
|
||||||
<AlertCircle className="h-3 w-3" />
|
|
||||||
A project with this ID already exists. You can choose to overwrite it.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Import Button */}
|
|
||||||
<div className="flex justify-end gap-2 pt-4">
|
|
||||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleImportWithOverwriteCheck}
|
|
||||||
disabled={!selectedFile || !generatedId || isImporting}
|
|
||||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
|
||||||
>
|
|
||||||
{existingProject ? (
|
|
||||||
<>
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
|
||||||
Overwrite Project
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Upload className="mr-2 h-4 w-4" />
|
|
||||||
Import Project
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Import Progress */}
|
|
||||||
{isImporting && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center gap-2 text-sm">
|
|
||||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
|
||||||
Importing project...
|
|
||||||
</div>
|
|
||||||
<Progress value={importProgress} className="w-full" />
|
|
||||||
<p className="text-xs text-muted-foreground text-center">
|
|
||||||
Extracting files and setting up project...
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Success State */}
|
|
||||||
{!isImporting && importProgress === 100 && (
|
|
||||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
|
||||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
|
||||||
</svg>
|
|
||||||
Project imported successfully!
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* Overwrite Confirmation Dialog */}
|
|
||||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle className="flex items-center gap-2">
|
|
||||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
|
||||||
Overwrite Existing Project
|
|
||||||
</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription className="space-y-2">
|
|
||||||
<p>
|
|
||||||
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
|
||||||
Overwriting it will:
|
|
||||||
</p>
|
|
||||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
|
||||||
<li><strong>Delete all existing files</strong> in the project</li>
|
|
||||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
|
||||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
|
||||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
|
||||||
</ul>
|
|
||||||
<p className="text-amber-600 font-medium">
|
|
||||||
This action cannot be undone. Are you sure you want to continue?
|
|
||||||
</p>
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
|
||||||
<AlertDialogAction
|
|
||||||
onClick={confirmOverwrite}
|
|
||||||
className="bg-amber-600 hover:bg-amber-700"
|
|
||||||
>
|
|
||||||
Yes, Overwrite Project
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ import { ProjectsManager } from './ProjectsManager';
|
|||||||
import { JSRuntimeFS } from './JSRuntime';
|
import { JSRuntimeFS } from './JSRuntime';
|
||||||
import { Git } from './git';
|
import { Git } from './git';
|
||||||
import type { NPool } from '@nostrify/nostrify';
|
import type { NPool } from '@nostrify/nostrify';
|
||||||
|
import type JSZip from 'jszip';
|
||||||
|
|
||||||
const createMockNostr = (): NPool => ({
|
const createMockNostr = (): NPool => ({
|
||||||
req: vi.fn(),
|
req: vi.fn(),
|
||||||
@@ -438,6 +439,50 @@ describe('ProjectsManager', () => {
|
|||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should prevent zip slip attacks during bulk file extraction', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Create a mock ZIP with malicious paths for bulk import
|
||||||
|
const mockZip = {
|
||||||
|
files: {
|
||||||
|
'projects/project1/../../../etc/passwd': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||||
|
},
|
||||||
|
'projects/project1/../../outside.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||||
|
},
|
||||||
|
'projects/project1/safe-file.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Spy on console.warn to check for security warnings
|
||||||
|
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Extract files from the malicious ZIP for bulk import
|
||||||
|
const files = await projectsManager.extractFilesFromZip(mockZip as unknown as JSZip, 'projects/project1');
|
||||||
|
|
||||||
|
// Should only contain safe files
|
||||||
|
expect(Object.keys(files)).toEqual(['safe-file.txt']);
|
||||||
|
expect(files['safe-file.txt']).toEqual(new Uint8Array([7, 8, 9]));
|
||||||
|
|
||||||
|
// Should have logged a security warning about skipped files
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Skipped 2 files due to resolving to paths outside of project directory:'),
|
||||||
|
['projects/project1/../../../etc/passwd', 'projects/project1/../../outside.txt']
|
||||||
|
);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// Restore mocks
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renameProject', () => {
|
describe('renameProject', () => {
|
||||||
|
|||||||
+398
-102
@@ -46,59 +46,259 @@ export class ProjectsManager {
|
|||||||
async createProject(name: string, customId?: string): Promise<Project> {
|
async createProject(name: string, customId?: string): Promise<Project> {
|
||||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||||
|
|
||||||
// Delete README.md if it exists
|
// Delete README.md if it exists (template-specific cleanup)
|
||||||
try {
|
try {
|
||||||
await this.fs.unlink(`${project.path}/README.md`);
|
await this.fs.unlink(`${project.path}/README.md`);
|
||||||
} catch {
|
} catch {
|
||||||
// README.md might not exist, ignore error
|
// README.md might not exist, ignore error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete .git directory and reinitialize
|
// Setup project infrastructure using unified method
|
||||||
try {
|
await this.setupProjectInfrastructure(project.path, {
|
||||||
await this.deleteDirectory(`${project.path}/.git`);
|
isOverwrite: false,
|
||||||
} catch {
|
commitMessage: 'New project created with Shakespeare',
|
||||||
// .git directory might not exist, ignore error
|
skipPersistentStorage: false,
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize new git repository
|
|
||||||
await this.git.init({
|
|
||||||
dir: project.path,
|
|
||||||
defaultBranch: 'main',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add all files to git
|
|
||||||
const files = await this.getAllFiles(project.path);
|
|
||||||
for (const file of files) {
|
|
||||||
// Skip .git directory
|
|
||||||
if (!file.startsWith('.git/')) {
|
|
||||||
await this.git.add({
|
|
||||||
dir: project.path,
|
|
||||||
filepath: file,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make initial commit
|
|
||||||
await this.git.commit({
|
|
||||||
dir: project.path,
|
|
||||||
message: 'New project created with Shakespeare',
|
|
||||||
author: {
|
|
||||||
name: 'shakespeare.diy',
|
|
||||||
email: '[email protected]',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Automatically request persistent storage after project creation
|
|
||||||
try {
|
|
||||||
await ensurePersistentStorage();
|
|
||||||
} catch (error) {
|
|
||||||
// Don't fail project creation if persistent storage request fails
|
|
||||||
console.warn('Failed to request persistent storage after project creation:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return project;
|
return project;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unified method for setting up project infrastructure.
|
||||||
|
* Handles git initialization/management, .ai directory creation, and persistent storage.
|
||||||
|
*/
|
||||||
|
private async setupProjectInfrastructure(
|
||||||
|
projectPath: string,
|
||||||
|
options: {
|
||||||
|
isOverwrite?: boolean;
|
||||||
|
commitMessage?: string;
|
||||||
|
skipPersistentStorage?: boolean;
|
||||||
|
} = {}
|
||||||
|
): Promise<void> {
|
||||||
|
const { isOverwrite = false, commitMessage = 'Project setup', skipPersistentStorage = false } = options;
|
||||||
|
|
||||||
|
// 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 (isOverwrite) {
|
||||||
|
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: commitMessage,
|
||||||
|
author: {
|
||||||
|
name: 'shakespeare.diy',
|
||||||
|
email: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} 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: commitMessage,
|
||||||
|
author: {
|
||||||
|
name: 'shakespeare.diy',
|
||||||
|
email: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create .ai/history directory
|
||||||
|
try {
|
||||||
|
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||||
|
} catch {
|
||||||
|
// Directory might already exist
|
||||||
|
}
|
||||||
|
|
||||||
|
// Automatically request persistent storage (unless skipped)
|
||||||
|
if (!skipPersistentStorage) {
|
||||||
|
try {
|
||||||
|
await ensurePersistentStorage();
|
||||||
|
} catch (error) {
|
||||||
|
// Don't fail project setup if persistent storage request fails
|
||||||
|
console.warn('Failed to request persistent storage after project setup:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unified project import method that handles both ZIP files and direct file objects
|
||||||
|
*/
|
||||||
|
async importProject(
|
||||||
|
source: File | { files: { [path: string]: Uint8Array } },
|
||||||
|
options: {
|
||||||
|
projectId?: string;
|
||||||
|
overwrite?: boolean;
|
||||||
|
projectName?: string;
|
||||||
|
} = {}
|
||||||
|
): Promise<Project> {
|
||||||
|
const { projectId, overwrite = false, projectName } = options;
|
||||||
|
|
||||||
|
let finalProjectId: string;
|
||||||
|
let finalProjectName: string;
|
||||||
|
let files: { [path: string]: Uint8Array };
|
||||||
|
|
||||||
|
if (source instanceof File) {
|
||||||
|
// Handle ZIP file import
|
||||||
|
finalProjectId = projectId || await this.generateUniqueProjectId(source.name.replace(/\.zip$/i, ''));
|
||||||
|
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||||
|
|
||||||
|
// Extract files from ZIP
|
||||||
|
const arrayBuffer = await source.arrayBuffer();
|
||||||
|
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||||
|
|
||||||
|
files = {};
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||||
|
if (zipEntry.dir) continue;
|
||||||
|
|
||||||
|
// Validate extraction path is within project directory
|
||||||
|
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||||
|
const extractPath = this.join(projectPath, relativePath);
|
||||||
|
|
||||||
|
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||||
|
skippedFiles.push(relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = await zipEntry.async('uint8array');
|
||||||
|
files[relativePath] = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Handle direct files import
|
||||||
|
finalProjectId = projectId || await this.generateUniqueProjectId('imported-project');
|
||||||
|
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||||
|
files = source.files;
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||||
|
const projectExists = await this.projectExists(finalProjectId);
|
||||||
|
|
||||||
|
// Check if project with this ID already exists when not overwriting
|
||||||
|
if (projectExists && !overwrite) {
|
||||||
|
throw new Error(`Project with ID "${finalProjectId}" 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract all files with security validation
|
||||||
|
const extractedFiles: string[] = [];
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, content] of Object.entries(files)) {
|
||||||
|
// Validate extraction path is within project directory
|
||||||
|
const extractPath = this.join(projectPath, relativePath);
|
||||||
|
|
||||||
|
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||||
|
skippedFiles.push(relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure parent directory exists
|
||||||
|
const dirPath = extractPath.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(extractPath, content);
|
||||||
|
extractedFiles.push(relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get filesystem stats for timestamps
|
||||||
|
const stats = await this.fs.stat(projectPath);
|
||||||
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// Setup project infrastructure using unified method
|
||||||
|
await this.setupProjectInfrastructure(projectPath, {
|
||||||
|
isOverwrite: overwrite,
|
||||||
|
commitMessage: source instanceof File
|
||||||
|
? `Import project from ${source.name}`
|
||||||
|
: `Import project from files`,
|
||||||
|
skipPersistentStorage: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: finalProjectId,
|
||||||
|
name: finalProjectName,
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy method for backward compatibility
|
||||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||||
// Generate a project ID based on the zip file name or use custom ID
|
// Generate a project ID based on the zip file name or use custom ID
|
||||||
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||||
@@ -198,66 +398,12 @@ export class ProjectsManager {
|
|||||||
const stats = await this.fs.stat(projectPath);
|
const stats = await this.fs.stat(projectPath);
|
||||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
// Initialize git repository if there's no .git directory
|
// Setup project infrastructure using unified method
|
||||||
try {
|
await this.setupProjectInfrastructure(projectPath, {
|
||||||
await this.fs.stat(`${projectPath}/.git`);
|
isOverwrite: overwrite,
|
||||||
|
commitMessage: `Import project from ${zipFile.name}`,
|
||||||
// If git exists and we're overwriting, stage the new files
|
skipPersistentStorage: false,
|
||||||
if (overwrite) {
|
});
|
||||||
const projectFiles = await this.getAllFiles(projectPath);
|
|
||||||
for (const file of projectFiles) {
|
|
||||||
// Skip .git directory
|
|
||||||
if (!file.startsWith('.git/')) {
|
|
||||||
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: '[email protected]',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// No .git directory found, initialize new repository
|
|
||||||
await this.git.init({
|
|
||||||
dir: projectPath,
|
|
||||||
defaultBranch: 'main',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add all files to git
|
|
||||||
const projectFiles = await this.getAllFiles(projectPath);
|
|
||||||
for (const file of projectFiles) {
|
|
||||||
// Skip .git directory
|
|
||||||
if (!file.startsWith('.git/')) {
|
|
||||||
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: '[email protected]',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -278,6 +424,106 @@ export class ProjectsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import project directly from files object (bypasses ZIP creation)
|
||||||
|
* Used by bulk import to avoid unnecessary ZIP repackaging
|
||||||
|
*/
|
||||||
|
async importProjectFromFiles(
|
||||||
|
projectId: string,
|
||||||
|
files: { [path: string]: Uint8Array },
|
||||||
|
overwrite = false,
|
||||||
|
projectName?: string
|
||||||
|
): Promise<Project> {
|
||||||
|
const projectPath = `${this.dir}/${projectId}`;
|
||||||
|
const projectExists = await this.projectExists(projectId);
|
||||||
|
|
||||||
|
// Check if project with this ID already exists when not overwriting
|
||||||
|
if (projectExists && !overwrite) {
|
||||||
|
throw new Error(`Project with ID "${projectId}" already exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine project name
|
||||||
|
const finalProjectName = projectName || this.formatProjectName(projectId);
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract all files with security validation
|
||||||
|
const extractedFiles: string[] = [];
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, content] of Object.entries(files)) {
|
||||||
|
// Validate the extraction path is within the project directory
|
||||||
|
const extractPath = this.join(projectPath, relativePath);
|
||||||
|
|
||||||
|
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||||
|
skippedFiles.push(relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure parent directory exists
|
||||||
|
const dirPath = extractPath.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(extractPath, content);
|
||||||
|
extractedFiles.push(relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project directory:`, skippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get filesystem stats for timestamps
|
||||||
|
const stats = await this.fs.stat(projectPath);
|
||||||
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// Setup project infrastructure using unified method
|
||||||
|
await this.setupProjectInfrastructure(projectPath, {
|
||||||
|
isOverwrite: overwrite,
|
||||||
|
commitMessage: `Import project from files`,
|
||||||
|
skipPersistentStorage: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: projectId,
|
||||||
|
name: finalProjectName,
|
||||||
|
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<Project> {
|
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||||
const id = customId || await this.generateUniqueProjectId(name);
|
const id = customId || await this.generateUniqueProjectId(name);
|
||||||
|
|
||||||
@@ -646,4 +892,54 @@ export class ProjectsManager {
|
|||||||
|
|
||||||
return '/' + normalized.join('/');
|
return '/' + normalized.join('/');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract files from a ZIP archive for a specific project path
|
||||||
|
* Used by bulk import to extract files from a specific directory within a ZIP
|
||||||
|
*/
|
||||||
|
async extractFilesFromZip(zip: JSZip, projectPath: string): Promise<{ [path: string]: Uint8Array }> {
|
||||||
|
const files: { [path: string]: Uint8Array } = {};
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
const securitySkippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||||
|
if (zipEntry.dir) continue;
|
||||||
|
|
||||||
|
// Check if this file is within the specified project path
|
||||||
|
if (!relativePath.startsWith(projectPath + '/')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the relative path within the project
|
||||||
|
const fileRelativePath = relativePath.substring(projectPath.length + 1);
|
||||||
|
|
||||||
|
// Skip empty paths (shouldn't happen due to the dir check above, but just in case)
|
||||||
|
if (!fileRelativePath) continue;
|
||||||
|
|
||||||
|
// Validate extraction path is safe (zip slip protection)
|
||||||
|
// Check for directory traversal attempts in the original path
|
||||||
|
if (fileRelativePath.includes('../') || fileRelativePath.includes('..\\') || fileRelativePath.startsWith('/') || fileRelativePath.startsWith('\\')) {
|
||||||
|
securitySkippedFiles.push(relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const content = await zipEntry.async('uint8array');
|
||||||
|
files[fileRelativePath] = content;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Failed to extract file ${relativePath}:`, error);
|
||||||
|
skippedFiles.push(relativePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (securitySkippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${securitySkippedFiles.length} files due to resolving to paths outside of project directory:`, securitySkippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${skippedFiles.length} files due to extraction errors:`, skippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
return files;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+9
-5
@@ -7,7 +7,7 @@ import { Input } from '@/components/ui/input';
|
|||||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||||
import { useSeoMeta } from '@unhead/react';
|
import { useSeoMeta } from '@unhead/react';
|
||||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||||
|
|
||||||
@@ -173,10 +173,13 @@ export default function Clone() {
|
|||||||
}
|
}
|
||||||
}, [handleClone, searchParams]);
|
}, [handleClone, searchParams]);
|
||||||
|
|
||||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
const handleImportZip = async (
|
||||||
|
data: { file: File; projectId?: string },
|
||||||
|
overwrite: boolean
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
// Import project from zip file
|
// Single project import from ZIP file
|
||||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
const project = await projectsManager.importProjectFromZip(data.file, data.projectId, overwrite);
|
||||||
|
|
||||||
// Show success toast
|
// Show success toast
|
||||||
toast({
|
toast({
|
||||||
@@ -271,7 +274,8 @@ export default function Clone() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ZIP Import Dialog */}
|
{/* ZIP Import Dialog */}
|
||||||
<ZipImportDialog
|
<ProjectImportDialog
|
||||||
|
mode="single"
|
||||||
onImport={handleImportZip}
|
onImport={handleImportZip}
|
||||||
open={isZipDialogOpen}
|
open={isZipDialogOpen}
|
||||||
onOpenChange={setIsZipDialogOpen}
|
onOpenChange={setIsZipDialogOpen}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, Upload } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||||
@@ -10,6 +11,8 @@ import { Switch } from '@/components/ui/switch';
|
|||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
|
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||||
import {
|
import {
|
||||||
isPersistentStorageSupported,
|
isPersistentStorageSupported,
|
||||||
isPersistentStorageGranted,
|
isPersistentStorageGranted,
|
||||||
@@ -39,10 +42,13 @@ export function DataSettings() {
|
|||||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||||
const [storageError, setStorageError] = useState<string | null>(null);
|
const [storageError, setStorageError] = useState<string | null>(null);
|
||||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||||
|
const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
|
const projectsManager = useProjectsManager();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
// Format bytes to human readable format
|
// Format bytes to human readable format
|
||||||
const formatBytes = (bytes: number): string => {
|
const formatBytes = (bytes: number): string => {
|
||||||
@@ -217,6 +223,67 @@ export function DataSettings() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleBulkImport = async (
|
||||||
|
data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] },
|
||||||
|
overwrite: boolean
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
let successCount = 0;
|
||||||
|
const errors: string[] = [];
|
||||||
|
|
||||||
|
// Handle both single and bulk import data
|
||||||
|
if ('projects' in data) {
|
||||||
|
// Bulk import
|
||||||
|
for (const project of data.projects) {
|
||||||
|
try {
|
||||||
|
// Import the project directly using files (bypasses ZIP creation)
|
||||||
|
await projectsManager.importProject(
|
||||||
|
{ files: project.files },
|
||||||
|
{ projectId: project.id, overwrite, projectName: project.id }
|
||||||
|
);
|
||||||
|
successCount++;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to import project ${project.id}:`, error);
|
||||||
|
errors.push(`${project.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Single import (shouldn't happen in bulk mode, but handle gracefully)
|
||||||
|
throw new Error('Single import not supported in bulk import mode');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show success/error toast and refresh project list
|
||||||
|
if (successCount > 0) {
|
||||||
|
// Refresh projects list to show newly imported projects
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: `${successCount} Project${successCount !== 1 ? 's' : ''} Imported Successfully`,
|
||||||
|
description: errors.length > 0
|
||||||
|
? `${errors.length} project${errors.length !== 1 ? 's' : ''} failed to import.`
|
||||||
|
: `All projects have been imported and are ready to use.`,
|
||||||
|
variant: errors.length > 0 ? "destructive" : "default",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errors.length > 0 && successCount === 0) {
|
||||||
|
toast({
|
||||||
|
title: "Import Failed",
|
||||||
|
description: `Failed to import projects: ${errors.slice(0, 3).join(', ')}${errors.length > 3 ? '...' : ''}`,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Bulk import failed:', error);
|
||||||
|
toast({
|
||||||
|
title: "Import Failed",
|
||||||
|
description: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
throw error; // Re-throw to let the dialog handle the error display
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleClearAllData = async () => {
|
const handleClearAllData = async () => {
|
||||||
setIsClearing(true);
|
setIsClearing(true);
|
||||||
try {
|
try {
|
||||||
@@ -391,6 +458,28 @@ export function DataSettings() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Import Projects */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Upload className="h-5 w-5" />
|
||||||
|
Import Projects
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Import multiple projects from a ZIP file exported from Shakespeare. You can choose which projects to import and handle conflicts with existing projects.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={() => setIsBulkImportOpen(true)}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-2" />
|
||||||
|
Import Projects
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Clear All Data */}
|
{/* Clear All Data */}
|
||||||
<Card className="border-destructive/20">
|
<Card className="border-destructive/20">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@@ -459,6 +548,14 @@ export function DataSettings() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Bulk Project Import Dialog */}
|
||||||
|
<ProjectImportDialog
|
||||||
|
mode="bulk"
|
||||||
|
onImport={handleBulkImport}
|
||||||
|
open={isBulkImportOpen}
|
||||||
|
onOpenChange={setIsBulkImportOpen}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user