mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
refactors
This commit is contained in:
1 parent
6f4aa264eb
commit
f4ccc2d924
6 files changed
+349
-45
No files matched your search
@@ -123,10 +123,10 @@ export function ProjectSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportZip = async (file: File, customId?: string, overwrite = false) => {
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, customId, overwrite);
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { useProjects } from '@/hooks/useProjects';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ZipImportDialogProps {
|
||||
onImport: (file: File, customId?: string, overwrite?: boolean) => Promise<void>;
|
||||
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
@@ -21,7 +21,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [customId, setCustomId] = useState('');
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -41,24 +41,24 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
|
||||
// Auto-generate custom ID from file name
|
||||
// Auto-generate ID from file name
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const generatedId = baseName
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setCustomId(generatedId);
|
||||
setGeneratedId(id);
|
||||
};
|
||||
|
||||
// Check for existing project when custom ID changes
|
||||
// Check for existing project when generated ID changes
|
||||
useEffect(() => {
|
||||
if (customId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === customId);
|
||||
if (generatedId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === generatedId);
|
||||
setExistingProject(existing || null);
|
||||
} else {
|
||||
setExistingProject(null);
|
||||
}
|
||||
}, [customId, projects]);
|
||||
}, [generatedId, projects]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
@@ -110,7 +110,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setCustomId('');
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
};
|
||||
|
||||
@@ -127,7 +127,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport(selectedFile, customId || undefined, overwrite);
|
||||
await onImport(selectedFile, overwrite, generatedId);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
@@ -136,7 +136,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setCustomId('');
|
||||
setGeneratedId('');
|
||||
setImportProgress(0);
|
||||
setExistingProject(null);
|
||||
}, 1000);
|
||||
@@ -149,7 +149,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (!selectedFile || !customId) return;
|
||||
if (!selectedFile || !generatedId) return;
|
||||
|
||||
// Check if project with this ID already exists
|
||||
try {
|
||||
@@ -175,7 +175,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
if (!isImporting) {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setCustomId('');
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
@@ -290,30 +290,13 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Custom Project ID */}
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="custom-id" className="text-sm font-medium">
|
||||
Project ID
|
||||
</label>
|
||||
<input
|
||||
id="custom-id"
|
||||
type="text"
|
||||
value={customId}
|
||||
onChange={(e) => setCustomId(e.target.value)}
|
||||
placeholder="project-name"
|
||||
className="w-full px-3 py-2 text-sm border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||
disabled={isImporting}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Auto-generated from filename. Only use lowercase letters, numbers, and hyphens.
|
||||
</p>
|
||||
{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>
|
||||
)}
|
||||
</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">
|
||||
@@ -322,7 +305,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!selectedFile || !customId || isImporting}
|
||||
disabled={!selectedFile || !generatedId || isImporting}
|
||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{existingProject ? (
|
||||
@@ -378,7 +361,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
A project with the ID "<strong>{customId}</strong>" already exists.
|
||||
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">
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { ProjectsManager } from './ProjectsManager';
|
||||
|
||||
// Mock JSZip
|
||||
vi.mock('jszip', () => ({
|
||||
default: class MockJSZip {
|
||||
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
|
||||
|
||||
static async loadAsync(buffer: ArrayBuffer) {
|
||||
const instance = new MockJSZip();
|
||||
// Add a mock file entry
|
||||
instance.files['package.json'] = {
|
||||
dir: false,
|
||||
async: () => new Uint8Array(buffer)
|
||||
};
|
||||
return instance;
|
||||
}
|
||||
|
||||
async file(name: string) {
|
||||
return this.files[name];
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS {
|
||||
private files: Map<string, string | Uint8Array> = new Map();
|
||||
@@ -167,4 +188,77 @@ describe('ProjectsManager', () => {
|
||||
expect(project).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('importProjectFromZip', () => {
|
||||
it('should preserve original project name when overwriting', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create an existing project with a specific name
|
||||
await fs.mkdir('/projects/my-project');
|
||||
await fs.mkdir('/projects/my-project/.git');
|
||||
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
|
||||
|
||||
// Mock the git methods to simulate existing project
|
||||
const mockGit = {
|
||||
init: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
add: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
getConfig: vi.fn(),
|
||||
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Create a mock ZIP file with different name
|
||||
const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' });
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Import with overwrite
|
||||
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
|
||||
|
||||
// Should preserve original project name
|
||||
expect(project.name).toBe('my-project');
|
||||
expect(project.id).toBe('my-project');
|
||||
});
|
||||
|
||||
it('should use new project name when not overwriting', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock the git methods
|
||||
const mockGit = {
|
||||
init: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
add: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
getConfig: vi.fn(),
|
||||
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Create a mock ZIP file
|
||||
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Import without overwrite
|
||||
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||
|
||||
// Should use formatted name from ID
|
||||
expect(project.name).toBe('new-project');
|
||||
expect(project.id).toBe('new-project');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -95,7 +95,20 @@ export class ProjectsManager {
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
// Generate a project ID based on the zip file name or use custom ID
|
||||
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||
const id = customId || await this.generateUniqueProjectId(baseName);
|
||||
const generatedId = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
// Determine the project ID to use
|
||||
let id: string;
|
||||
if (customId) {
|
||||
// Use the provided custom ID (for overwrite scenarios)
|
||||
id = customId;
|
||||
} else {
|
||||
// If no custom ID, generate a unique ID (for new projects)
|
||||
id = await this.generateUniqueProjectId(generatedId);
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
const projectExists = await this.projectExists(id);
|
||||
@@ -105,6 +118,15 @@ export class ProjectsManager {
|
||||
throw new Error(`Project with ID "${id}" already exists`);
|
||||
}
|
||||
|
||||
// Get original project name if overwriting, otherwise use formatted name
|
||||
let projectName: string;
|
||||
if (overwrite && projectExists) {
|
||||
const existingProject = await this.getProject(id);
|
||||
projectName = existingProject?.name || this.formatProjectName(id);
|
||||
} else {
|
||||
projectName = this.formatProjectName(id);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
@@ -230,7 +252,7 @@ export class ProjectsManager {
|
||||
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id),
|
||||
name: projectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
@@ -27,6 +28,7 @@ export default function Index() {
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
|
||||
Reference in new issue
Block a user