mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Init zip bulk import
This commit is contained in:
1 parent
247919a24b
commit
3253b198c7
5 files changed
+1209
-2
No files matched your search
@@ -101,7 +101,7 @@ export function AppLayout({
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<div className="relative left-0 top-0 h-full w-64 max-w-[75vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={(project) => {
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { BulkProjectImportDialog } from './BulkProjectImportDialog';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the useProjects hook
|
||||
const mockProjects = [
|
||||
{ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() }
|
||||
];
|
||||
|
||||
vi.mock('@/hooks/useProjects', () => ({
|
||||
useProjects: () => ({
|
||||
data: mockProjects,
|
||||
isLoading: false,
|
||||
error: null
|
||||
})
|
||||
}));
|
||||
|
||||
// Mock JSZip
|
||||
const mockZipFiles = {
|
||||
'projects/project1/package.json': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||
},
|
||||
'projects/project1/src/index.ts': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
'projects/existing-project/package.json': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||
},
|
||||
'projects/existing-project/README.md': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([10, 11, 12]))
|
||||
}
|
||||
};
|
||||
|
||||
vi.mock('jszip', () => ({
|
||||
default: class MockJSZip {
|
||||
files = mockZipFiles;
|
||||
|
||||
static async loadAsync() {
|
||||
const instance = new MockJSZip();
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
describe('BulkProjectImportDialog', () => {
|
||||
const mockOnImport = vi.fn();
|
||||
const defaultProps = {
|
||||
onImport: mockOnImport,
|
||||
disabled: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnImport.mockClear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders dialog trigger button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Import Projects')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when trigger is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Import Multiple Projects')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('analyzes ZIP file and discovers projects', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Find the hidden file input
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for analysis to complete
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Check that projects are listed
|
||||
expect(screen.getByText('project1')).toBeInTheDocument();
|
||||
expect(screen.getByText('existing-project')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows conflict warning for existing projects', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog and select file
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for analysis to complete
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Check for conflict indicator
|
||||
expect(screen.getByText('Conflict')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/Will overwrite existing project/)).toHaveLength(2); // One for mobile, one for desktop
|
||||
});
|
||||
|
||||
it('allows selecting and deselecting projects', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog and analyze file
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Find checkboxes for projects
|
||||
const project1Checkbox = document.getElementById('project-project1') as HTMLInputElement;
|
||||
const existingProjectCheckbox = document.getElementById('project-existing-project') as HTMLInputElement;
|
||||
|
||||
// project1 should be selected by default (no conflict)
|
||||
expect(project1Checkbox).toBeChecked();
|
||||
// existing-project should not be selected by default (conflict)
|
||||
expect(existingProjectCheckbox).not.toBeChecked();
|
||||
|
||||
// Toggle existing project selection
|
||||
fireEvent.click(existingProjectCheckbox);
|
||||
expect(existingProjectCheckbox).toBeChecked();
|
||||
});
|
||||
|
||||
it('handles select all and deselect all buttons', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Setup and analyze file
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Test deselect all
|
||||
const deselectAllButton = screen.getByText('Deselect All');
|
||||
fireEvent.click(deselectAllButton);
|
||||
|
||||
const project1Checkbox = document.getElementById('project-project1') as HTMLInputElement;
|
||||
const existingProjectCheckbox = document.getElementById('project-existing-project') as HTMLInputElement;
|
||||
|
||||
expect(project1Checkbox).not.toBeChecked();
|
||||
expect(existingProjectCheckbox).not.toBeChecked();
|
||||
|
||||
// Test select all
|
||||
const selectAllButton = screen.getByText('Select All');
|
||||
fireEvent.click(selectAllButton);
|
||||
|
||||
expect(project1Checkbox).toBeChecked();
|
||||
expect(existingProjectCheckbox).toBeChecked();
|
||||
});
|
||||
|
||||
it('shows overwrite confirmation when importing conflicting projects', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Setup and analyze file
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Select the conflicting project
|
||||
const existingProjectCheckbox = document.getElementById('project-existing-project') as HTMLInputElement;
|
||||
fireEvent.click(existingProjectCheckbox);
|
||||
|
||||
// Click import button
|
||||
const importButton = screen.getByText('Import & Overwrite (2)');
|
||||
fireEvent.click(importButton);
|
||||
|
||||
// Should show overwrite confirmation dialog
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Existing Projects')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Overwrite Existing Projects')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onImport with correct project data', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<BulkProjectImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Setup and analyze file
|
||||
const triggerButton = screen.getByText('Import Projects');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
const file = new File(['test content'], 'projects-export.zip', { type: 'application/zip' });
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Found 2 projects')).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Click import button (only project1 should be selected by default)
|
||||
const importButton = screen.getByText('Import Projects (1)');
|
||||
fireEvent.click(importButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockOnImport).toHaveBeenCalledWith(
|
||||
[
|
||||
{
|
||||
id: 'project1',
|
||||
files: {
|
||||
'package.json': expect.any(Uint8Array),
|
||||
'src/index.ts': expect.any(Uint8Array)
|
||||
}
|
||||
}
|
||||
],
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,613 @@
|
||||
import React, { useState, useRef, useCallback } 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 { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
files: string[];
|
||||
isConflict: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
interface BulkProjectImportDialogProps {
|
||||
onImport: (projects: { id: string; files: { [path: string]: Uint8Array } }[], overwrite: boolean) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function BulkProjectImportDialog({ onImport, disabled = false, className, open, onOpenChange }: BulkProjectImportDialogProps) {
|
||||
// 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 [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 analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
|
||||
const projects: ProjectInfo[] = [];
|
||||
const projectPaths = new Set<string>();
|
||||
|
||||
// Find all potential project directories
|
||||
// Look for directories that contain package.json, index.html, or other project indicators
|
||||
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)) {
|
||||
// Determine the project directory path
|
||||
let projectPath: string;
|
||||
|
||||
// If the 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) {
|
||||
// Remove the project path prefix to get relative file path
|
||||
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/')) {
|
||||
// Extract just the project name from projects/project-name
|
||||
const projectName = projectPath.substring('projects/'.length);
|
||||
id = projectName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectName;
|
||||
} else {
|
||||
// Use the full path as both ID and name
|
||||
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]);
|
||||
|
||||
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);
|
||||
setIsAnalyzing(true);
|
||||
setDiscoveredProjects([]);
|
||||
|
||||
try {
|
||||
// Read and analyze the ZIP file
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
setZipData(zip);
|
||||
|
||||
// Discover projects in the ZIP file
|
||||
const projects = await analyzeZipForProjects(zip);
|
||||
setDiscoveredProjects(projects);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
|
||||
} finally {
|
||||
setIsAnalyzing(false);
|
||||
}
|
||||
}, [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));
|
||||
};
|
||||
|
||||
// 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);
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
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 (!zipData || selectedProjects.length === 0) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Prepare project data for import
|
||||
const projectsToImport = await Promise.all(
|
||||
selectedProjects.map(async (project) => {
|
||||
const files: { [path: string]: Uint8Array } = {};
|
||||
|
||||
// Extract files for this project
|
||||
for (const filePath of project.files) {
|
||||
const zipPath = `${project.path}/${filePath}`;
|
||||
const zipEntry = zipData.files[zipPath];
|
||||
|
||||
if (zipEntry && !zipEntry.dir) {
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[filePath] = content;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: project.id,
|
||||
files,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Simulate progress for better UX
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 5, 90));
|
||||
}, 100);
|
||||
|
||||
await onImport(projectsToImport, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setImportProgress(0);
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import projects');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
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);
|
||||
setSelectedFile(null);
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
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 Projects
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent className="sm:max-w-xl h-auto max-h-[90vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Multiple Projects
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
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">
|
||||
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-destructive mb-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project List */}
|
||||
{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>
|
||||
{/* Show conflict indicator inline on larger screens */}
|
||||
{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>
|
||||
|
||||
{/* Mobile conflict indicator on its own line */}
|
||||
{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' : ''}
|
||||
{/* Only show overwrite text on desktop when conflict exists */}
|
||||
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
{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={selectedProjects.length === 0 || isImporting}
|
||||
className={conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{conflictingProjects.length > 0 ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Import & Overwrite ({selectedProjects.length})
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Projects ({selectedProjects.length})
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Analysis Progress */}
|
||||
{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>
|
||||
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>
|
||||
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" />
|
||||
Overwrite Existing Projects
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-3">
|
||||
<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, Overwrite Projects
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+174
@@ -254,6 +254,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
|
||||
failedToRequestPersistentStorage: 'Failed to request persistent storage',
|
||||
|
||||
// Project Import
|
||||
importProjects: 'Import Projects',
|
||||
importProjectsDescription: 'Import multiple projects from a ZIP file exported from Shakespeare. You can choose which projects to import and handle conflicts with existing projects.',
|
||||
importMultipleProjects: 'Import Multiple Projects',
|
||||
foundProjects: 'Found {{count}} project | Found {{count}} projects',
|
||||
selectAll: 'Select All',
|
||||
deselectAll: 'Deselect All',
|
||||
conflict: 'Conflict',
|
||||
willOverwriteExisting: 'Will overwrite existing project',
|
||||
analyzingZipFile: 'Analyzing ZIP file...',
|
||||
discoveringProjects: 'Discovering projects and checking for conflicts...',
|
||||
importingProjects: 'Importing {{count}} project | Importing {{count}} projects',
|
||||
extractingFiles: 'Extracting files and setting up projects...',
|
||||
projectsImportedSuccessfully: 'Projects imported successfully!',
|
||||
overwriteExistingProjects: 'Overwrite Existing Projects',
|
||||
selectedProjectsExist: 'You have selected {{count}} project that already exists: | You have selected {{count}} projects that already exist:',
|
||||
overwriteWillDelete: 'Delete all existing files in these projects',
|
||||
overwriteWillReplace: 'Replace them with files from the ZIP archive',
|
||||
overwriteWillPreserveGit: 'Preserve Git history if it exists',
|
||||
overwriteWillKeepAI: 'Keep AI chat history and session data',
|
||||
yesOverwriteProjects: 'Yes, Overwrite Projects',
|
||||
importAndOverwrite: 'Import & Overwrite ({{count}})',
|
||||
projectsImported: '{{count}} Project Imported Successfully | {{count}} Projects Imported Successfully',
|
||||
someProjectsFailed: '{{count}} project failed to import | {{count}} projects failed to import',
|
||||
allProjectsReadyToUse: 'All projects have been imported and are ready to use.',
|
||||
importFailed: 'Import Failed',
|
||||
failedToImportProjects: 'Failed to import projects',
|
||||
bulkImportFailed: 'Bulk import failed',
|
||||
|
||||
// 404 Page
|
||||
pageNotFound: 'Oops! Page not found',
|
||||
returnToHome: 'Return to Home',
|
||||
@@ -557,6 +586,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
|
||||
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
|
||||
|
||||
// Project Import
|
||||
importProjects: 'Importar Projetos',
|
||||
importProjectsDescription: 'Importe múltiplos projetos de um arquivo ZIP exportado do Shakespeare. Você pode escolher quais projetos importar e lidar com conflitos com projetos existentes.',
|
||||
importMultipleProjects: 'Importar Múltiplos Projetos',
|
||||
foundProjects: '{{count}} projeto encontrado | {{count}} projetos encontrados',
|
||||
selectAll: 'Selecionar Todos',
|
||||
deselectAll: 'Desmarcar Todos',
|
||||
conflict: 'Conflito',
|
||||
willOverwriteExisting: 'Substituirá projeto existente',
|
||||
analyzingZipFile: 'Analisando arquivo ZIP...',
|
||||
discoveringProjects: 'Descobrindo projetos e verificando conflitos...',
|
||||
importingProjects: 'Importando {{count}} projeto | Importando {{count}} projetos',
|
||||
extractingFiles: 'Extraindo arquivos e configurando projetos...',
|
||||
projectsImportedSuccessfully: 'Projetos importados com sucesso!',
|
||||
overwriteExistingProjects: 'Substituir Projetos Existentes',
|
||||
selectedProjectsExist: 'Você selecionou {{count}} projeto que já existe: | Você selecionou {{count}} projetos que já existem:',
|
||||
overwriteWillDelete: 'Excluir todos os arquivos existentes nestes projetos',
|
||||
overwriteWillReplace: 'Substituí-los por arquivos do arquivo ZIP',
|
||||
overwriteWillPreserveGit: 'Preservar histórico Git se existir',
|
||||
overwriteWillKeepAI: 'Manter histórico de chat IA e dados de sessão',
|
||||
yesOverwriteProjects: 'Sim, Substituir Projetos',
|
||||
importAndOverwrite: 'Importar e Substituir ({{count}})',
|
||||
projectsImported: '{{count}} Projeto Importado com Sucesso | {{count}} Projetos Importados com Sucesso',
|
||||
someProjectsFailed: '{{count}} projeto falhou ao importar | {{count}} projetos falharam ao importar',
|
||||
allProjectsReadyToUse: 'Todos os projetos foram importados e estão prontos para uso.',
|
||||
importFailed: 'Importação Falhou',
|
||||
failedToImportProjects: 'Falha ao importar projetos',
|
||||
bulkImportFailed: 'Importação em lote falhou',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
|
||||
@@ -870,6 +928,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
|
||||
failedToRequestPersistentStorage: '请求持久存储失败',
|
||||
|
||||
// Project Import
|
||||
importProjects: '导入项目',
|
||||
importProjectsDescription: '从Shakespeare导出的ZIP文件导入多个项目。您可以选择要导入的项目并处理与现有项目的冲突。',
|
||||
importMultipleProjects: '导入多个项目',
|
||||
foundProjects: '找到{{count}}个项目',
|
||||
selectAll: '全选',
|
||||
deselectAll: '取消全选',
|
||||
conflict: '冲突',
|
||||
willOverwriteExisting: '将覆盖现有项目',
|
||||
analyzingZipFile: '正在分析ZIP文件...',
|
||||
discoveringProjects: '正在发现项目并检查冲突...',
|
||||
importingProjects: '正在导入{{count}}个项目',
|
||||
extractingFiles: '正在提取文件并设置项目...',
|
||||
projectsImportedSuccessfully: '项目导入成功!',
|
||||
overwriteExistingProjects: '覆盖现有项目',
|
||||
selectedProjectsExist: '您已选择{{count}}个已存在的项目:',
|
||||
overwriteWillDelete: '删除这些项目中的所有现有文件',
|
||||
overwriteWillReplace: '用ZIP存档中的文件替换它们',
|
||||
overwriteWillPreserveGit: '如果存在,保留Git历史',
|
||||
overwriteWillKeepAI: '保留AI聊天历史和会话数据',
|
||||
yesOverwriteProjects: '是的,覆盖项目',
|
||||
importAndOverwrite: '导入并覆盖({{count}})',
|
||||
projectsImported: '{{count}}个项目导入成功',
|
||||
someProjectsFailed: '{{count}}个项目导入失败',
|
||||
allProjectsReadyToUse: '所有项目已导入并准备使用。',
|
||||
importFailed: '导入失败',
|
||||
failedToImportProjects: '导入项目失败',
|
||||
bulkImportFailed: '批量导入失败',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
aboutShakespeareDescription: '关于Shakespeare的信息。',
|
||||
@@ -1183,6 +1270,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
|
||||
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
|
||||
|
||||
// Project Import
|
||||
importProjects: 'Shigo da Ayyuka',
|
||||
importProjectsDescription: 'Shigo da ayyuka da yawa daga fayil ɗin ZIP da aka fitar daga Shakespeare. Kuna iya zaɓar waɗanne ayyukan da za ku shigo da su da kuma magance rikice-rikice da ayyukan da ke akwai.',
|
||||
importMultipleProjects: 'Shigo da Ayyuka da Yawa',
|
||||
foundProjects: 'An samo aikin {{count}} | An samo ayyuka {{count}}',
|
||||
selectAll: 'Zaɓa Duk',
|
||||
deselectAll: 'Cire Zaɓin Duk',
|
||||
conflict: 'Rikici',
|
||||
willOverwriteExisting: 'Zai sake rubuta aikin da ke akwai',
|
||||
analyzingZipFile: 'Ana nazarin fayil ɗin ZIP...',
|
||||
discoveringProjects: 'Ana gano ayyuka da bincika rikice-rikice...',
|
||||
importingProjects: 'Ana shigo da aikin {{count}} | Ana shigo da ayyuka {{count}}',
|
||||
extractingFiles: 'Ana cire fayiloli da saita ayyuka...',
|
||||
projectsImportedSuccessfully: 'An shigo da ayyuka cikin nasara!',
|
||||
overwriteExistingProjects: 'Sake Rubuta Ayyukan da ke Akwai',
|
||||
selectedProjectsExist: 'Kun zaɓi aikin {{count}} wanda ya riga ya kasance: | Kun zaɓi ayyuka {{count}} waɗanda suka riga sun kasance:',
|
||||
overwriteWillDelete: 'Share duk fayilolin da ke akwai a cikin waɗannan ayyuka',
|
||||
overwriteWillReplace: 'Maye gurbinsu da fayiloli daga ZIP archive',
|
||||
overwriteWillPreserveGit: 'Kiyaye tarihin Git idan ya kasance',
|
||||
overwriteWillKeepAI: 'Ajiye tarihin hira na AI da bayanan zama',
|
||||
yesOverwriteProjects: 'Eh, Sake Rubuta Ayyuka',
|
||||
importAndOverwrite: 'Shigo da kuma Sake Rubuta ({{count}})',
|
||||
projectsImported: 'An Shigo da Aikin {{count}} cikin Nasara | An Shigo da Ayyuka {{count}} cikin Nasara',
|
||||
someProjectsFailed: 'Aikin {{count}} ya gaza shigowa | Ayyuka {{count}} sun gaza shigowa',
|
||||
allProjectsReadyToUse: 'An shigo da duk ayyuka kuma suna shirye don amfani.',
|
||||
importFailed: 'Shigowa Ya Gaza',
|
||||
failedToImportProjects: 'Ya gaza shigo da ayyuka',
|
||||
bulkImportFailed: 'Shigowa da yawa ya gaza',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
aboutShakespeareDescription: 'Bayani game da Shakespeare.',
|
||||
@@ -1496,6 +1612,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
|
||||
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
|
||||
|
||||
// Project Import
|
||||
importProjects: 'Gbe Awọn Iṣẹ Akanṣe Wọle',
|
||||
importProjectsDescription: 'Gbe awọn iṣẹ akanṣe pupọ wọle lati faili ZIP ti a ṣe export lati Shakespeare. O le yan awọn iṣẹ akanṣe wo ni lati gbe wọle ati koju awọn ija pẹlu awọn iṣẹ akanṣe ti o wa tẹlẹ.',
|
||||
importMultipleProjects: 'Gbe Awọn Iṣẹ Akanṣe Pupọ Wọle',
|
||||
foundProjects: 'Ri iṣẹ akanṣe {{count}} | Ri awọn iṣẹ akanṣe {{count}}',
|
||||
selectAll: 'Yan Gbogbo',
|
||||
deselectAll: 'Yọ Gbogbo Yiyan',
|
||||
conflict: 'Ija',
|
||||
willOverwriteExisting: 'Yoo tun kọ iṣẹ akanṣe ti o wa tẹlẹ',
|
||||
analyzingZipFile: 'N ṣe itupalẹ faili ZIP...',
|
||||
discoveringProjects: 'N ṣe awari awọn iṣẹ akanṣe ati ṣayẹwo awọn ija...',
|
||||
importingProjects: 'N gbe iṣẹ akanṣe {{count}} wọle | N gbe awọn iṣẹ akanṣe {{count}} wọle',
|
||||
extractingFiles: 'N yọ awọn faili ati ṣeto awọn iṣẹ akanṣe...',
|
||||
projectsImportedSuccessfully: 'A ti gbe awọn iṣẹ akanṣe wọle ni aṣeyọri!',
|
||||
overwriteExistingProjects: 'Tun Kọ Awọn Iṣẹ Akanṣe Ti O Wa Tẹlẹ',
|
||||
selectedProjectsExist: 'O ti yan iṣẹ akanṣe {{count}} ti o wa tẹlẹ: | O ti yan awọn iṣẹ akanṣe {{count}} ti o wa tẹlẹ:',
|
||||
overwriteWillDelete: 'Pa gbogbo awọn faili ti o wa tẹlẹ ninu awọn iṣẹ akanṣe wọnyi',
|
||||
overwriteWillReplace: 'Rọpọ wọn pẹlu awọn faili lati ZIP archive',
|
||||
overwriteWillPreserveGit: 'Tọju itan Git ti o ba wa',
|
||||
overwriteWillKeepAI: 'Tọju itan ibaraẹnisọrọ AI ati data igba',
|
||||
yesOverwriteProjects: 'Bẹẹni, Tun Kọ Awọn Iṣẹ Akanṣe',
|
||||
importAndOverwrite: 'Gbe Wọle ati Tun Kọ ({{count}})',
|
||||
projectsImported: 'A Ti Gbe Iṣẹ Akanṣe {{count}} Wọle Ni Aṣeyọri | A Ti Gbe Awọn Iṣẹ Akanṣe {{count}} Wọle Ni Aṣeyọri',
|
||||
someProjectsFailed: 'Iṣẹ akanṣe {{count}} kuna lati gbe wọle | Awọn iṣẹ akanṣe {{count}} kuna lati gbe wọle',
|
||||
allProjectsReadyToUse: 'A ti gbe gbogbo awọn iṣẹ akanṣe wọle ati pe wọn ti ṣetan fun lilo.',
|
||||
importFailed: 'Gbigbe Wọle Kuna',
|
||||
failedToImportProjects: 'O kuna lati gbe awọn iṣẹ akanṣe wọle',
|
||||
bulkImportFailed: 'Gbigbe wọle pupọ kuna',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
aboutShakespeareDescription: 'Alaye nipa Shakespeare.',
|
||||
@@ -1804,6 +1949,35 @@ const resources = {
|
||||
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
|
||||
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
|
||||
|
||||
// Project Import
|
||||
importProjects: 'Bubata Ọrụ',
|
||||
importProjectsDescription: 'Bubata ọtụtụ ọrụ site na faịlụ ZIP e wepụtara na Shakespeare. Ị nwere ike ịhọrọ ọrụ ndị ị ga-ebubata ma dozie esemokwu na ọrụ ndị dị adị.',
|
||||
importMultipleProjects: 'Bubata Ọtụtụ Ọrụ',
|
||||
foundProjects: 'Achọtara ọrụ {{count}} | Achọtara ọrụ {{count}}',
|
||||
selectAll: 'Họrọ Niile',
|
||||
deselectAll: 'Wepụ Nhọrọ Niile',
|
||||
conflict: 'Esemokwu',
|
||||
willOverwriteExisting: 'Ga-edegharị ọrụ dị adị',
|
||||
analyzingZipFile: 'Na-enyocha faịlụ ZIP...',
|
||||
discoveringProjects: 'Na-achọpụta ọrụ ma na-enyocha esemokwu...',
|
||||
importingProjects: 'Na-ebubata ọrụ {{count}} | Na-ebubata ọrụ {{count}}',
|
||||
extractingFiles: 'Na-ewepụta faịlụ ma na-ahazi ọrụ...',
|
||||
projectsImportedSuccessfully: 'E bubatara ọrụ nke ọma!',
|
||||
overwriteExistingProjects: 'Degharịa Ọrụ Ndị Dị Adị',
|
||||
selectedProjectsExist: 'Ị ahọrọla ọrụ {{count}} nke dị adị: | Ị ahọrọla ọrụ {{count}} ndị dị adị:',
|
||||
overwriteWillDelete: 'Hichapụ faịlụ niile dị adị na ọrụ ndị a',
|
||||
overwriteWillReplace: 'Dochie ha na faịlụ sitere na ZIP archive',
|
||||
overwriteWillPreserveGit: 'Chekwaa akụkọ Git ma ọ bụrụ na ọ dị',
|
||||
overwriteWillKeepAI: 'Chekwaa akụkọ mkparịta ụka AI na data oge',
|
||||
yesOverwriteProjects: 'Ee, Degharịa Ọrụ',
|
||||
importAndOverwrite: 'Bubata ma Degharịa ({{count}})',
|
||||
projectsImported: 'E Bubatara Ọrụ {{count}} Nke Ọma | E Bubatara Ọrụ {{count}} Nke Ọma',
|
||||
someProjectsFailed: 'Ọrụ {{count}} dara ịbubata | Ọrụ {{count}} dara ịbubata',
|
||||
allProjectsReadyToUse: 'E bubatala ọrụ niile ma ha dị njikere maka iji.',
|
||||
importFailed: 'Mbubata Dara',
|
||||
failedToImportProjects: 'O dara ịbubata ọrụ',
|
||||
bulkImportFailed: 'Mbubata ọtụtụ dara',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
aboutShakespeareDescription: 'Ozi gbasara Shakespeare.',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
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';
|
||||
@@ -10,6 +10,8 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { BulkProjectImportDialog } from '@/components/BulkProjectImportDialog';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
@@ -39,10 +41,12 @@ export function DataSettings() {
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -217,6 +221,66 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkImport = async (
|
||||
projects: { id: string; files: { [path: string]: Uint8Array } }[],
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
let successCount = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const project of projects) {
|
||||
try {
|
||||
// Create a temporary zip file for each project to use existing import logic
|
||||
const zip = new JSZip();
|
||||
|
||||
// Add all files to the zip at the root level (not nested under project name)
|
||||
for (const [filePath, content] of Object.entries(project.files)) {
|
||||
zip.file(filePath, content);
|
||||
}
|
||||
|
||||
// Generate zip blob
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
const zipFile = new File([zipBlob], `${project.id}.zip`, { type: 'application/zip' });
|
||||
|
||||
// Import the project using existing logic
|
||||
await projectsManager.importProjectFromZip(zipFile, project.id, overwrite);
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.error(`Failed to import project ${project.id}:`, error);
|
||||
errors.push(`${project.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Show success/error toast
|
||||
if (successCount > 0) {
|
||||
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 () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -391,6 +455,28 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</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 */}
|
||||
<Card className="border-destructive/20">
|
||||
<CardHeader>
|
||||
@@ -459,6 +545,13 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Bulk Project Import Dialog */}
|
||||
<BulkProjectImportDialog
|
||||
onImport={handleBulkImport}
|
||||
open={isBulkImportOpen}
|
||||
onOpenChange={setIsBulkImportOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user