import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import type { FileMap } from '~/lib/stores/files'; import { classNames } from '~/utils/classNames'; import { createScopedLogger, renderLogger } from '~/utils/logger'; import * as ContextMenu from '@radix-ui/react-context-menu'; import type { FileHistory } from '~/types/actions'; import { diffLines, type Change } from 'diff'; import { workbenchStore } from '~/lib/stores/workbench'; import { toast } from 'react-toastify'; import { path } from '~/utils/path'; const logger = createScopedLogger('FileTree'); const NODE_PADDING_LEFT = 8; const DEFAULT_HIDDEN_FILES = [/\/node_modules\//, /\/\.next/, /\/\.astro/]; interface Props { files?: FileMap; selectedFile?: string; onFileSelect?: (filePath: string) => void; rootFolder?: string; hideRoot?: boolean; collapsed?: boolean; allowFolderSelection?: boolean; hiddenFiles?: Array; unsavedFiles?: Set; fileHistory?: Record; className?: string; } interface InlineInputProps { depth: number; placeholder: string; initialValue?: string; onSubmit: (value: string) => void; onCancel: () => void; } export const FileTree = memo( ({ files = {}, onFileSelect, selectedFile, rootFolder, hideRoot = false, collapsed = false, allowFolderSelection = false, hiddenFiles, className, unsavedFiles, fileHistory = {}, }: Props) => { renderLogger.trace('FileTree'); const computedHiddenFiles = useMemo(() => [...DEFAULT_HIDDEN_FILES, ...(hiddenFiles ?? [])], [hiddenFiles]); const fileList = useMemo(() => { return buildFileList(files, rootFolder, hideRoot, computedHiddenFiles); }, [files, rootFolder, hideRoot, computedHiddenFiles]); const [collapsedFolders, setCollapsedFolders] = useState(() => { return collapsed ? new Set(fileList.filter((item) => item.kind === 'folder').map((item) => item.fullPath)) : new Set(); }); useEffect(() => { if (collapsed) { setCollapsedFolders(new Set(fileList.filter((item) => item.kind === 'folder').map((item) => item.fullPath))); return; } setCollapsedFolders((prevCollapsed) => { const newCollapsed = new Set(); for (const folder of fileList) { if (folder.kind === 'folder' && prevCollapsed.has(folder.fullPath)) { newCollapsed.add(folder.fullPath); } } return newCollapsed; }); }, [fileList, collapsed]); const filteredFileList = useMemo(() => { const list = []; let lastDepth = Number.MAX_SAFE_INTEGER; for (const fileOrFolder of fileList) { const depth = fileOrFolder.depth; // if the depth is equal we reached the end of the collaped group if (lastDepth === depth) { lastDepth = Number.MAX_SAFE_INTEGER; } // ignore collapsed folders if (collapsedFolders.has(fileOrFolder.fullPath)) { lastDepth = Math.min(lastDepth, depth); } // ignore files and folders below the last collapsed folder if (lastDepth < depth) { continue; } list.push(fileOrFolder); } return list; }, [fileList, collapsedFolders]); const toggleCollapseState = (fullPath: string) => { setCollapsedFolders((prevSet) => { const newSet = new Set(prevSet); if (newSet.has(fullPath)) { newSet.delete(fullPath); } else { newSet.add(fullPath); } return newSet; }); }; const onCopyPath = (fileOrFolder: FileNode | FolderNode) => { try { navigator.clipboard.writeText(fileOrFolder.fullPath); } catch (error) { logger.error(error); } }; const onCopyRelativePath = (fileOrFolder: FileNode | FolderNode) => { try { navigator.clipboard.writeText(fileOrFolder.fullPath.substring((rootFolder || '').length)); } catch (error) { logger.error(error); } }; return (
{filteredFileList.map((fileOrFolder) => { switch (fileOrFolder.kind) { case 'file': { return ( { onCopyPath(fileOrFolder); }} onCopyRelativePath={() => { onCopyRelativePath(fileOrFolder); }} onClick={() => { onFileSelect?.(fileOrFolder.fullPath); }} /> ); } case 'folder': { return ( { onCopyPath(fileOrFolder); }} onCopyRelativePath={() => { onCopyRelativePath(fileOrFolder); }} onClick={() => { toggleCollapseState(fileOrFolder.fullPath); }} /> ); } default: { return undefined; } } })}
); }, ); export default FileTree; interface FolderProps { folder: FolderNode; collapsed: boolean; selected?: boolean; onCopyPath: () => void; onCopyRelativePath: () => void; onClick: () => void; } interface FolderContextMenuProps { onCopyPath?: () => void; onCopyRelativePath?: () => void; children: ReactNode; } function ContextMenuItem({ onSelect, children }: { onSelect?: () => void; children: ReactNode }) { return ( {children} ); } function InlineInput({ depth, placeholder, initialValue = '', onSubmit, onCancel }: InlineInputProps) { const inputRef = useRef(null); useEffect(() => { const timer = setTimeout(() => { if (inputRef.current) { inputRef.current.focus(); if (initialValue) { inputRef.current.value = initialValue; inputRef.current.select(); } } }, 50); return () => clearTimeout(timer); }, [initialValue]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { const value = inputRef.current?.value.trim(); if (value) { onSubmit(value); } } else if (e.key === 'Escape') { onCancel(); } }; return (
{ setTimeout(() => { if (document.activeElement !== inputRef.current) { onCancel(); } }, 100); }} />
); } function FileContextMenu({ onCopyPath, onCopyRelativePath, fullPath, children, }: FolderContextMenuProps & { fullPath: string }) { const [isCreatingFile, setIsCreatingFile] = useState(false); const [isCreatingFolder, setIsCreatingFolder] = useState(false); const [isDragging, setIsDragging] = useState(false); const depth = useMemo(() => fullPath.split('/').length, [fullPath]); const fileName = useMemo(() => path.basename(fullPath), [fullPath]); // Add this to determine if the path is a file or folder const isFolder = useMemo(() => { const files = workbenchStore.files.get(); const fileEntry = files[fullPath]; return !fileEntry || fileEntry.type === 'folder'; }, [fullPath]); // Get the parent directory for files const targetPath = useMemo(() => { return isFolder ? fullPath : path.dirname(fullPath); }, [fullPath, isFolder]); const handleDragOver = useCallback((e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); }, []); const handleDragLeave = useCallback((e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); }, []); const handleDrop = useCallback( async (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); const items = Array.from(e.dataTransfer.items); const files = items.filter((item) => item.kind === 'file'); for (const item of files) { const file = item.getAsFile(); if (file) { try { const filePath = path.join(fullPath, file.name); // Convert file to binary data (Uint8Array) const arrayBuffer = await file.arrayBuffer(); const binaryContent = new Uint8Array(arrayBuffer); const success = await workbenchStore.createFile(filePath, binaryContent); if (success) { toast.success(`File ${file.name} uploaded successfully`); } else { toast.error(`Failed to upload file ${file.name}`); } } catch (error) { toast.error(`Error uploading ${file.name}`); logger.error(error); } } } setIsDragging(false); }, [fullPath], ); const handleCreateFile = async (fileName: string) => { // Use targetPath instead of fullPath const newFilePath = path.join(targetPath, fileName); // Change from createNewFile to createFile const success = await workbenchStore.createFile(newFilePath, ''); if (success) { toast.success('File created successfully'); } else { toast.error('Failed to create file'); } setIsCreatingFile(false); }; const handleCreateFolder = async (folderName: string) => { // Use targetPath instead of fullPath const newFolderPath = path.join(targetPath, folderName); // Change from createNewFolder to createFolder const success = await workbenchStore.createFolder(newFolderPath); if (success) { toast.success('Folder created successfully'); } else { toast.error('Failed to create folder'); } setIsCreatingFolder(false); }; // Add delete handler function const handleDelete = async () => { try { // Confirm deletion with the user if (!confirm(`Are you sure you want to delete ${isFolder ? 'folder' : 'file'}: ${fileName}?`)) { return; } let success; if (isFolder) { success = await workbenchStore.deleteFolder(fullPath); } else { success = await workbenchStore.deleteFile(fullPath); } if (success) { toast.success(`${isFolder ? 'Folder' : 'File'} deleted successfully`); } else { toast.error(`Failed to delete ${isFolder ? 'folder' : 'file'}`); } } catch (error) { toast.error(`Error deleting ${isFolder ? 'folder' : 'file'}`); logger.error(error); } }; return ( <>
{children}
setIsCreatingFile(true)}>
New File
setIsCreatingFolder(true)}>
New Folder
Copy path Copy relative path {/* Add delete option in a new group */}
Delete {isFolder ? 'Folder' : 'File'}
{isCreatingFile && ( setIsCreatingFile(false)} /> )} {isCreatingFolder && ( setIsCreatingFolder(false)} /> )} ); } function Folder({ folder, collapsed, selected = false, onCopyPath, onCopyRelativePath, onClick }: FolderProps) { return ( {folder.name} ); } interface FileProps { file: FileNode; selected: boolean; unsavedChanges?: boolean; fileHistory?: Record; onCopyPath: () => void; onCopyRelativePath: () => void; onClick: () => void; } function File({ file, onClick, onCopyPath, onCopyRelativePath, selected, unsavedChanges = false, fileHistory = {}, }: FileProps) { const { depth, name, fullPath } = file; const fileModifications = fileHistory[fullPath]; const { additions, deletions } = useMemo(() => { if (!fileModifications?.originalContent) { return { additions: 0, deletions: 0 }; } const normalizedOriginal = fileModifications.originalContent.replace(/\r\n/g, '\n'); const normalizedCurrent = fileModifications.versions[fileModifications.versions.length - 1]?.content.replace(/\r\n/g, '\n') || ''; if (normalizedOriginal === normalizedCurrent) { return { additions: 0, deletions: 0 }; } const changes = diffLines(normalizedOriginal, normalizedCurrent, { newlineIsToken: false, ignoreWhitespace: true, ignoreCase: false, }); return changes.reduce( (acc: { additions: number; deletions: number }, change: Change) => { if (change.added) { acc.additions += change.value.split('\n').length; } if (change.removed) { acc.deletions += change.value.split('\n').length; } return acc; }, { additions: 0, deletions: 0 }, ); }, [fileModifications]); const showStats = additions > 0 || deletions > 0; return (
{name}
{showStats && (
{additions > 0 && +{additions}} {deletions > 0 && -{deletions}}
)} {unsavedChanges && }
); } interface ButtonProps { depth: number; iconClasses: string; children: ReactNode; className?: string; onClick?: () => void; } function NodeButton({ depth, iconClasses, onClick, className, children }: ButtonProps) { return ( ); } type Node = FileNode | FolderNode; interface BaseNode { id: number; depth: number; name: string; fullPath: string; } interface FileNode extends BaseNode { kind: 'file'; } interface FolderNode extends BaseNode { kind: 'folder'; } function buildFileList( files: FileMap, rootFolder = '/', hideRoot: boolean, hiddenFiles: Array, ): Node[] { const folderPaths = new Set(); const fileList: Node[] = []; let defaultDepth = 0; if (rootFolder === '/' && !hideRoot) { defaultDepth = 1; fileList.push({ kind: 'folder', name: '/', depth: 0, id: 0, fullPath: '/' }); } for (const [filePath, dirent] of Object.entries(files)) { const segments = filePath.split('/').filter((segment) => segment); const fileName = segments.at(-1); if (!fileName || isHiddenFile(filePath, fileName, hiddenFiles)) { continue; } let currentPath = ''; let i = 0; let depth = 0; while (i < segments.length) { const name = segments[i]; const fullPath = (currentPath += `/${name}`); if (!fullPath.startsWith(rootFolder) || (hideRoot && fullPath === rootFolder)) { i++; continue; } if (i === segments.length - 1 && dirent?.type === 'file') { fileList.push({ kind: 'file', id: fileList.length, name, fullPath, depth: depth + defaultDepth, }); } else if (!folderPaths.has(fullPath)) { folderPaths.add(fullPath); fileList.push({ kind: 'folder', id: fileList.length, name, fullPath, depth: depth + defaultDepth, }); } i++; depth++; } } return sortFileList(rootFolder, fileList, hideRoot); } function isHiddenFile(filePath: string, fileName: string, hiddenFiles: Array) { return hiddenFiles.some((pathOrRegex) => { if (typeof pathOrRegex === 'string') { return fileName === pathOrRegex; } return pathOrRegex.test(filePath); }); } /** * Sorts the given list of nodes into a tree structure (still a flat list). * * This function organizes the nodes into a hierarchical structure based on their paths, * with folders appearing before files and all items sorted alphabetically within their level. * * @note This function mutates the given `nodeList` array for performance reasons. * * @param rootFolder - The path of the root folder to start the sorting from. * @param nodeList - The list of nodes to be sorted. * * @returns A new array of nodes sorted in depth-first order. */ function sortFileList(rootFolder: string, nodeList: Node[], hideRoot: boolean): Node[] { logger.trace('sortFileList'); const nodeMap = new Map(); const childrenMap = new Map(); // pre-sort nodes by name and type nodeList.sort((a, b) => compareNodes(a, b)); for (const node of nodeList) { nodeMap.set(node.fullPath, node); const parentPath = node.fullPath.slice(0, node.fullPath.lastIndexOf('/')); if (parentPath !== rootFolder.slice(0, rootFolder.lastIndexOf('/'))) { if (!childrenMap.has(parentPath)) { childrenMap.set(parentPath, []); } childrenMap.get(parentPath)?.push(node); } } const sortedList: Node[] = []; const depthFirstTraversal = (path: string): void => { const node = nodeMap.get(path); if (node) { sortedList.push(node); } const children = childrenMap.get(path); if (children) { for (const child of children) { if (child.kind === 'folder') { depthFirstTraversal(child.fullPath); } else { sortedList.push(child); } } } }; if (hideRoot) { // if root is hidden, start traversal from its immediate children const rootChildren = childrenMap.get(rootFolder) || []; for (const child of rootChildren) { depthFirstTraversal(child.fullPath); } } else { depthFirstTraversal(rootFolder); } return sortedList; } function compareNodes(a: Node, b: Node): number { if (a.kind !== b.kind) { return a.kind === 'folder' ? -1 : 1; } return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }); }