Skip to content

create folder nesting BEN-1076 #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 170 additions & 29 deletions components/ui-builder/code-editor.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,115 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import { benchifyFileSchema } from "@/lib/schemas";
import { z } from "zod";
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
ChevronDown,
ChevronRight,
Folder,
FileText,
FileCode,
Settings,
Palette,
Globe,
Package
} from "lucide-react";

interface CodeEditorProps {
files: z.infer<typeof benchifyFileSchema>;
}

interface FileNode {
name: string;
path: string;
type: 'file' | 'folder';
children?: FileNode[];
content?: string;
}

export function CodeEditor({ files = [] }: CodeEditorProps) {
const [selectedFileIndex, setSelectedFileIndex] = useState(0);
const [selectedFilePath, setSelectedFilePath] = useState<string>('');
const [openFolders, setOpenFolders] = useState<Set<string>>(new Set());

// Build file tree structure (pure function, no side effects)
const buildFileTree = (files: Array<{ path: string; content: string }>): { tree: FileNode[], allFolders: string[] } => {
const root: FileNode[] = [];
const folderMap = new Map<string, FileNode>();
const allFolders: string[] = [];

// Sort files to ensure consistent ordering
const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path));

sortedFiles.forEach(file => {
const parts = file.path.split('/');
let currentPath = '';
let currentLevel = root;

for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isLast = i === parts.length - 1;
currentPath = currentPath ? `${currentPath}/${part}` : part;

if (isLast) {
// It's a file
currentLevel.push({
name: part,
path: file.path,
type: 'file',
content: file.content
});
} else {
// It's a folder
let folder = folderMap.get(currentPath);
if (!folder) {
folder = {
name: part,
path: currentPath,
type: 'folder',
children: []
};
folderMap.set(currentPath, folder);
currentLevel.push(folder);
allFolders.push(currentPath);
}
currentLevel = folder.children!;
}
}
});

return { tree: root, allFolders };
};

const { tree: fileTree, allFolders } = buildFileTree(files);
const selectedFile = files.find(f => f.path === selectedFilePath);

// Open all folders by default (only once when files change)
useEffect(() => {
if (allFolders.length > 0) {
setOpenFolders(new Set(allFolders));
}
}, [files.length]); // Only trigger when files array changes

// Selected file data
const selectedFile = files[selectedFileIndex];
// Auto-select first file if none selected (only once when files change)
useEffect(() => {
if (!selectedFilePath && files.length > 0) {
setSelectedFilePath(files[0].path);
}
}, [files.length, selectedFilePath]); // Dependency on selectedFilePath prevents loops

// Get file icon based on extension
const getFileIcon = (path: string) => {
if (path.endsWith('.tsx') || path.endsWith('.jsx')) return <FileCode className="h-4 w-4 text-blue-500" />;
if (path.endsWith('.ts') || path.endsWith('.js')) return <FileCode className="h-4 w-4 text-yellow-500" />;
if (path.endsWith('.css')) return <Palette className="h-4 w-4 text-pink-500" />;
if (path.endsWith('.html')) return <Globe className="h-4 w-4 text-orange-500" />;
if (path.endsWith('.json') || path.includes('config')) return <Settings className="h-4 w-4 text-gray-500" />;
if (path.includes('package.json')) return <Package className="h-4 w-4 text-green-500" />;
return <FileText className="h-4 w-4 text-gray-400" />;
};

// Determine file language for syntax highlighting
const getLanguage = (path: string) => {
Expand All @@ -30,32 +125,74 @@ export function CodeEditor({ files = [] }: CodeEditorProps) {
return 'text';
};

// Extract filename from path
const getFileName = (path: string) => {
const parts = path.split('/');
return parts[parts.length - 1];
const toggleFolder = (folderPath: string) => {
setOpenFolders(prev => {
const newSet = new Set(prev);
if (newSet.has(folderPath)) {
newSet.delete(folderPath);
} else {
newSet.add(folderPath);
}
return newSet;
});
};

const renderFileTree = (nodes: FileNode[], depth = 0) => {
return nodes.map(node => {
if (node.type === 'folder') {
const isOpen = openFolders.has(node.path);

return (
<Collapsible key={node.path} open={isOpen} onOpenChange={() => toggleFolder(node.path)}>
<CollapsibleTrigger className="flex items-center w-full text-left py-1 px-2 hover:bg-muted/50 text-sm">
<div className="flex items-center gap-2" style={{ paddingLeft: `${depth * 12}px` }}>
{isOpen ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
<Folder className="h-4 w-4 text-blue-400" />
<span className="font-medium">{node.name}</span>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
{node.children && renderFileTree(node.children, depth + 1)}
</CollapsibleContent>
</Collapsible>
);
} else {
const isSelected = selectedFilePath === node.path;

return (
<button
key={node.path}
onClick={() => setSelectedFilePath(node.path)}
className={cn(
"flex items-center w-full text-left py-1.5 px-2 hover:bg-muted/50 text-sm transition-colors",
isSelected && "bg-primary/10 text-primary"
)}
>
<div className="flex items-center gap-2" style={{ paddingLeft: `${depth * 12 + 20}px` }}>
{getFileIcon(node.path)}
<span className="truncate">{node.name}</span>
</div>
</button>
);
}
});
};

return (
<div className="grid grid-cols-[180px_1fr] h-[700px] gap-4">
{/* File sidebar */}
<div className="grid grid-cols-[320px_1fr] h-[700px] gap-4">
{/* File sidebar - now wider */}
<div className="border rounded-md overflow-hidden bg-card min-w-0 h-full">
<div className="p-2 border-b bg-muted/50 font-medium text-sm">Files</div>
<ScrollArea className="h-[calc(100%-33px)]">
<div className="py-1">
{files.map((file, index) => (
<button
key={file.path}
onClick={() => setSelectedFileIndex(index)}
className={cn(
"w-full text-left px-2 py-1.5 text-xs hover:bg-muted/50",
selectedFileIndex === index && "bg-primary/10 text-primary font-medium"
)}
title={file.path}
>
<span className="block truncate">{file.path}</span>
</button>
))}
<div className="p-3 border-b bg-muted/50 font-semibold text-sm flex items-center gap-2">
<Folder className="h-4 w-4" />
Files
</div>
<ScrollArea className="h-[calc(100%-41px)]">
<div className="py-2">
{renderFileTree(fileTree)}
</div>
</ScrollArea>
</div>
Expand All @@ -64,8 +201,9 @@ export function CodeEditor({ files = [] }: CodeEditorProps) {
<div className="border rounded-md overflow-hidden h-full min-w-0 flex-1">
{selectedFile ? (
<div className="flex flex-col h-full">
<div className="p-2 border-b bg-muted/50 font-medium flex items-center">
<span className="text-sm truncate">{getFileName(selectedFile.path)}</span>
<div className="p-3 border-b bg-muted/50 font-medium flex items-center gap-2">
{getFileIcon(selectedFile.path)}
<span className="text-sm truncate">{selectedFile.path}</span>
</div>
<SyntaxHighlighter
language={getLanguage(selectedFile.path)}
Expand Down Expand Up @@ -104,7 +242,10 @@ export function CodeEditor({ files = [] }: CodeEditorProps) {
</div>
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
No file selected
<div className="text-center">
<FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p>Select a file to view its contents</p>
</div>
</div>
)}
</div>
Expand Down
33 changes: 33 additions & 0 deletions components/ui/collapsible.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use client"

import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"

function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}

function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
)
}

function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
)
}

export { Collapsible, CollapsibleTrigger, CollapsibleContent }
72 changes: 72 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@e2b/code-interpreter": "^1.5.0",
"@e2b/sdk": "^0.12.5",
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-label": "^2.1.6",
"@radix-ui/react-scroll-area": "^1.2.8",
"@radix-ui/react-slot": "^1.2.2",
Expand Down