Allow duplicating a project

This commit is contained in:
Alex Gleason committed 2025-12-04 19:47:12 -06:00
1 parent acadf07a68
commit 9a288c38c7
11 files changed
+381 -10

No files matched your search

+21
View File
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -13,10 +14,12 @@ import {
History,
Folder,
Rocket,
Copy,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog';
interface ActionsMenuProps {
projectId: string;
@@ -39,9 +42,11 @@ export function ActionsMenu({
disabled = false,
onFirstInteraction: _onFirstInteraction,
}: ActionsMenuProps) {
const { t } = useTranslation();
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
@@ -98,6 +103,15 @@ export function ActionsMenu({
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDuplicateDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Copy className="h-4 w-4" />
{t('duplicateProject')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
@@ -131,6 +145,13 @@ export function ActionsMenu({
onOpenChange={setDeployDialogOpen}
/>
<DuplicateProjectDialog
projectId={projectId}
projectName={projectName}
open={duplicateDialogOpen}
onOpenChange={setDuplicateDialogOpen}
/>
</>
);
}
@@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DuplicateProjectDialog } from './DuplicateProjectDialog';
import { TestApp } from '@/test/TestApp';
// Mock the navigate function
const mockNavigate = vi.fn();
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: () => mockNavigate,
};
});
describe('DuplicateProjectDialog', () => {
beforeEach(() => {
mockNavigate.mockClear();
});
it('renders dialog when open', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Duplicate Project' })).toBeInTheDocument();
expect(screen.getByText('Create a copy of this project with a new name')).toBeInTheDocument();
});
it('does not render dialog when closed', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={false}
onOpenChange={() => {}}
/>
</TestApp>
);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('shows default project name with -copy suffix', () => {
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
expect(input).toHaveValue('Test Project-copy');
});
it('allows changing the project name', async () => {
const user = userEvent.setup();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
await user.clear(input);
await user.type(input, 'My New Project');
expect(input).toHaveValue('My New Project');
});
it('disables duplicate button when name is empty', async () => {
const user = userEvent.setup();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={() => {}}
/>
</TestApp>
);
const input = screen.getByLabelText('New Project Name');
const duplicateButton = screen.getByRole('button', { name: /Duplicate Project/i });
// Clear the input
await user.clear(input);
// Button should be disabled when input is empty
expect(duplicateButton).toBeDisabled();
});
it('closes dialog when cancel button is clicked', async () => {
const user = userEvent.setup();
const onOpenChange = vi.fn();
render(
<TestApp>
<DuplicateProjectDialog
projectId="test-project"
projectName="Test Project"
open={true}
onOpenChange={onOpenChange}
/>
</TestApp>
);
const cancelButton = screen.getByRole('button', { name: /Cancel/i });
await user.click(cancelButton);
await waitFor(() => {
expect(onOpenChange).toHaveBeenCalledWith(false);
});
});
});
+119
View File
@@ -0,0 +1,119 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
interface DuplicateProjectDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function DuplicateProjectDialog({
projectId,
projectName,
open,
onOpenChange,
}: DuplicateProjectDialogProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const { toast } = useToast();
const projectsManager = useProjectsManager();
const queryClient = useQueryClient();
const [newName, setNewName] = useState(`${projectName}-copy`);
const [isLoading, setIsLoading] = useState(false);
const handleDuplicate = async () => {
if (!newName.trim()) {
return;
}
setIsLoading(true);
try {
const duplicatedProject = await projectsManager.duplicateProject(projectId, newName);
// Invalidate projects query to refresh the list
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: t('projectDuplicated'),
description: t('projectDuplicatedDescription'),
});
// Close dialog
onOpenChange(false);
// Navigate to the new project
navigate(`/project/${duplicatedProject.id}`);
} catch (error) {
console.error('Failed to duplicate project:', error);
toast({
title: t('failedToDuplicateProject'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{t('duplicateProject')}</DialogTitle>
<DialogDescription>
{t('duplicateProjectDescription')}
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="new-name">{t('newProjectName')}</Label>
<Input
id="new-name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder={`${projectName}-copy`}
disabled={isLoading}
onKeyDown={(e) => {
if (e.key === 'Enter' && newName.trim()) {
handleDuplicate();
}
}}
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
{t('cancel')}
</Button>
<Button
onClick={handleDuplicate}
disabled={isLoading || !newName.trim()}
>
{isLoading ? t('duplicatingProject') : t('duplicateProject')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -708,6 +708,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="flex-1">
{hasBuiltProject ? (
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
+55 -4
View File
@@ -193,16 +193,17 @@ export class ProjectsManager {
/**
* Copy a directory recursively from source to destination
* @param skipGit - Whether to skip the .git directory (default: true)
*/
private async copyDirectory(sourcePath: string, destPath: string): Promise<void> {
private async copyDirectory(sourcePath: string, destPath: string, skipGit = true): Promise<void> {
// Ensure destination directory exists
await this.fs.mkdir(destPath, { recursive: true });
const entries = await this.fs.readdir(sourcePath);
for (const entry of entries) {
// Skip .git directory
if (entry === '.git') continue;
// Skip .git directory if skipGit is true
if (skipGit && entry === '.git') continue;
const sourceFullPath = `${sourcePath}/${entry}`;
const destFullPath = `${destPath}/${entry}`;
@@ -212,7 +213,7 @@ export class ProjectsManager {
if (stat.isDirectory()) {
// Recursively copy subdirectories
await this.copyDirectory(sourceFullPath, destFullPath);
await this.copyDirectory(sourceFullPath, destFullPath, skipGit);
} else if (stat.isFile()) {
// Copy file
const content = await this.fs.readFile(sourceFullPath);
@@ -726,6 +727,56 @@ export class ProjectsManager {
};
}
async duplicateProject(sourceId: string, newName?: string): Promise<Project> {
// Validate that the source project exists
const sourceProject = await this.getProject(sourceId);
if (!sourceProject) {
throw new Error(`Project with ID "${sourceId}" does not exist`);
}
// Generate a unique ID for the new project
const baseName = newName || `${sourceId}-copy`;
const newId = await this.generateUniqueProjectId(baseName);
const sourcePath = `${this.dir}/${sourceId}`;
const destPath = `${this.dir}/${newId}`;
try {
// Create the destination directory
await this.fs.mkdir(destPath, { recursive: true });
// Copy all files from source to destination (including .git)
await this.copyDirectory(sourcePath, destPath, false);
// Get filesystem stats for timestamps
const stats = await this.fs.stat(destPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project duplication
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project duplication if persistent storage request fails
console.warn('Failed to request persistent storage after project duplication:', error);
}
return {
id: newId,
name: this.formatProjectName(newId),
path: destPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up on error
try {
await this.deleteDirectory(destPath);
} catch (cleanupError) {
console.warn('Failed to clean up directory after duplication failure:', cleanupError);
}
throw error;
}
}
private async deleteDirectory(dirPath: string): Promise<void> {
const files = await this.fs.readdir(dirPath);
+8 -1
View File
@@ -543,5 +543,12 @@
"templateDeleted": "Template Deleted",
"templateDeletedDescription": "Project template '{{name}}' has been deleted.",
"noTemplatesConfigured": "No project templates configured yet. Add a template to get started.",
"atLeastOneTemplateRequired": "At least one template is required"
"atLeastOneTemplateRequired": "At least one template is required",
"duplicateProject": "Duplicate Project",
"duplicatingProject": "Duplicating project...",
"projectDuplicated": "Project duplicated",
"projectDuplicatedDescription": "Project has been duplicated successfully.",
"failedToDuplicateProject": "Failed to duplicate project",
"newProjectName": "New Project Name",
"duplicateProjectDescription": "Create a copy of this project with a new name"
}
+8 -1
View File
@@ -450,5 +450,12 @@
"loginToDiscoverPlugins": "Shiga tare da Nostr don gano plugins daga mutanen da kuke bi.",
"noPluginsFromNetwork": "Ba a Sami Plugin ba",
"noPluginsFromNetworkDescription": "Ba a sami plugins daga mutanen da kuke bi ba. Bi masu haɓaka plugins akan Nostr don ganin plugins nasu a nan.",
"tryDifferentSearch": "Gwada kalmar bincike daban."
"tryDifferentSearch": "Gwada kalmar bincike daban.",
"duplicateProject": "Kwafin Aikin",
"duplicatingProject": "Ana kwafin aikin...",
"projectDuplicated": "An kwafi aikin",
"projectDuplicatedDescription": "An kwafi aikin cikin nasara.",
"failedToDuplicateProject": "An kasa kwafin aikin",
"newProjectName": "Sunan Sabon Aikin",
"duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna"
}
+8 -1
View File
@@ -447,5 +447,12 @@
"loginToDiscoverPlugins": "Banye na Nostr iji chọpụta plugins sitere na ndị ị na-eso.",
"noPluginsFromNetwork": "Achọtaghị Plugins",
"noPluginsFromNetworkDescription": "Achọtaghị plugins sitere na ndị ị na-eso. Soro ndị mmepe plugin na Nostr iji hụ plugins ha ebe a.",
"tryDifferentSearch": "Gbalịa okwu nchọgharị dị iche."
"tryDifferentSearch": "Gbalịa okwu nchọgharị dị iche.",
"duplicateProject": "Mepụta Ọrụ",
"duplicatingProject": "Na-emepụta ọrụ...",
"projectDuplicated": "Emepụtara ọrụ",
"projectDuplicatedDescription": "Emepụtara ọrụ nke ọma.",
"failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
"newProjectName": "Aha Ọrụ Ọhụrụ",
"duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ"
}
+8 -1
View File
@@ -459,5 +459,12 @@
"loginToDiscoverPlugins": "Faça login com Nostr para descobrir plugins de pessoas que você segue.",
"noPluginsFromNetwork": "Nenhum Plugin Encontrado",
"noPluginsFromNetworkDescription": "Nenhum plugin encontrado de pessoas que você segue. Siga desenvolvedores de plugins no Nostr para ver seus plugins aqui.",
"tryDifferentSearch": "Tente um termo de busca diferente."
"tryDifferentSearch": "Tente um termo de busca diferente.",
"duplicateProject": "Duplicar Projeto",
"duplicatingProject": "Duplicando projeto...",
"projectDuplicated": "Projeto duplicado",
"projectDuplicatedDescription": "O projeto foi duplicado com sucesso.",
"failedToDuplicateProject": "Falha ao duplicar projeto",
"newProjectName": "Nome do Novo Projeto",
"duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome"
}
+8 -1
View File
@@ -447,5 +447,12 @@
"loginToDiscoverPlugins": "Wọle pẹlu Nostr lati ṣawari awọn plugins lati ọdọ awọn eniyan ti o ntẹle.",
"noPluginsFromNetwork": "Ko Ri Plugins",
"noPluginsFromNetworkDescription": "Ko ri awọn plugins lati ọdọ awọn eniyan ti o ntẹle. Tẹle awọn olupilẹṣẹ plugin lori Nostr lati rii awọn plugins wọn nibi.",
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran."
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran.",
"duplicateProject": "Ṣe Ẹda Iṣẹ Akanṣe",
"duplicatingProject": "N ṣe ẹda iṣẹ akanṣe...",
"projectDuplicated": "Iṣẹ akanṣe ti ṣe ẹda",
"projectDuplicatedDescription": "Iṣẹ akanṣe ti ṣe ẹda ni aṣeyọri.",
"failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
"newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
"duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun"
}
+8 -1
View File
@@ -459,5 +459,12 @@
"loginToDiscoverPlugins": "使用 Nostr 登录以发现您关注的人的插件。",
"noPluginsFromNetwork": "未找到插件",
"noPluginsFromNetworkDescription": "未找到您关注的人的插件。在 Nostr 上关注插件开发者以在此处查看他们的插件。",
"tryDifferentSearch": "尝试不同的搜索词。"
"tryDifferentSearch": "尝试不同的搜索词。",
"duplicateProject": "复制项目",
"duplicatingProject": "正在复制项目...",
"projectDuplicated": "项目已复制",
"projectDuplicatedDescription": "项目已成功复制。",
"failedToDuplicateProject": "复制项目失败",
"newProjectName": "新项目名称",
"duplicateProjectDescription": "使用新名称创建此项目的副本"
}