add: add file renaming and delete functionality

This commit is contained in:
KevIsDev
2025-03-03 16:14:31 +00:00
parent 8c83c3c9aa
commit b079a56788
2 changed files with 186 additions and 8 deletions

View File

@@ -595,6 +595,104 @@ export class WorkbenchStore {
return false;
}
}
async deleteFile(filePath: string) {
try {
const wc = await webcontainer;
const relativePath = extractRelativePath(filePath);
await wc.fs.rm(relativePath);
// If the deleted file was selected, clear the selection
if (this.selectedFile.get() === filePath) {
this.setSelectedFile(undefined);
}
return true;
} catch (error) {
console.error('Error deleting file:', error);
return false;
}
}
async deleteFolder(folderPath: string) {
try {
const wc = await webcontainer;
const relativePath = extractRelativePath(folderPath);
await wc.fs.rm(relativePath, { recursive: true });
const selectedFile = this.selectedFile.get();
if (selectedFile && selectedFile.startsWith(folderPath)) {
this.setSelectedFile(undefined);
}
return true;
} catch (error) {
console.error('Error deleting folder:', error);
return false;
}
}
async renameFile(oldPath: string, newPath: string) {
try {
const wc = await webcontainer;
const oldRelativePath = extractRelativePath(oldPath);
const newRelativePath = extractRelativePath(newPath);
const fileContent = await wc.fs.readFile(oldRelativePath, 'utf-8');
await this.createNewFile(newPath, fileContent);
await this.deleteFile(oldPath);
if (this.selectedFile.get() === oldPath) {
const fullNewPath = path.join(wc.workdir, newRelativePath);
this.setSelectedFile(fullNewPath);
}
return true;
} catch (error) {
console.error('Error renaming file:', error);
return false;
}
}
async renameFolder(oldPath: string, newPath: string) {
try {
await this.createNewFolder(newPath);
const files = this.files.get();
const filesToMove = Object.entries(files)
.filter(([filePath]) => filePath.startsWith(oldPath))
.map(([filePath, dirent]) => ({ path: filePath, dirent }));
for (const { path: filePath, dirent } of filesToMove) {
if (dirent?.type === 'file') {
const relativePath = filePath.substring(oldPath.length);
const newFilePath = path.join(newPath, relativePath);
await this.createNewFile(newFilePath, dirent.content);
}
}
await this.deleteFolder(oldPath);
const selectedFile = this.selectedFile.get();
if (selectedFile && selectedFile.startsWith(oldPath)) {
const relativePath = selectedFile.substring(oldPath.length);
const newSelectedPath = path.join(newPath, relativePath);
this.setSelectedFile(newSelectedPath);
}
return true;
} catch (error) {
console.error('Error renaming folder:', error);
return false;
}
}
}
export const workbenchStore = new WorkbenchStore();