To display the chat folders as a tree structure, we'll modify your FolderList.tsx to include the chats under each folder. We'll use the Collapse component from MUI to handle the expand/collapse functionality for each folder. Additionally, we'll integrate the NewChatForm within each folder so that users can add new chats directly under a folder.
Here's how you can make the necessary changes:
-
Update ChatComponent.tsx: Adjust the props and structure to integrate the chats within the folders.
-
Modify FolderList.tsx: Include the chats under each folder and handle the expand/collapse functionality.
-
Adjust NewChatForm.tsx: Pass the folder name when creating a new chat.
Below are the updated files with the necessary changes:
ChatComponent.tsx
import React, { useState, useEffect, useRef } from 'react';
import {
Box,
Paper,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Button,
} from '@mui/material';
import axios from 'axios';
import { Folder, Message } from './types';
import FolderList from './FolderList';
import MessageList from './MessageList';
import NewFolderForm from './NewFolderForm';
import MessageInput from './MessageInput';
import RightPanel from './RightPanel';
const ChatComponent: React.FC = () => {
const [folders, setFolders] = useState<Folder[]>([{ name: 'Folder 1', chats: { 'Chat 1': [] } }]);
const [selectedFolder, setSelectedFolder] = useState<string>('Folder 1');
const [selectedChat, setSelectedChat] = useState<string>('Chat 1');
const [isRightPanelOpen, setIsRightPanelOpen] = useState(false);
const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);
const [chatToDelete, setChatToDelete] = useState<{ folderName: string; chatName: string } | null>(null);
const [folderToDelete, setFolderToDelete] = useState<string | null>(null);
const chatContainerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setFolders([{ name: 'Folder 1', chats: { 'Chat 1': [] } }]);
setSelectedFolder('Folder 1');
setSelectedChat('Chat 1');
}, []);
useEffect(() => {
// Scroll to the bottom of the chat container when new messages are added
if (chatContainerRef.current) {
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
}
}, [folders, selectedFolder, selectedChat]);
const sendMessage = async (text: string, file?: File) => {
const newMessage: Message = {
position: 'right',
type: file ? getFileType(file) : 'text',
content: file ? URL.createObjectURL(file) : text,
text: text,
fileName: file ? file.name : undefined,
};
const newMessages = [
...(folders.find((f) => f.name === selectedFolder)?.chats[selectedChat] || []),
newMessage,
];
const updatedFolders = folders.map((f) =>
f.name === selectedFolder
? { ...f, chats: { ...f.chats, [selectedChat]: newMessages } }
: f
);
setFolders(updatedFolders);
try {
const formData = new FormData();
formData.append('text', text);
if (file) formData.append('file', file);
const response = await axios.post('/api/chat', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
const aiResponse: Message = {
position: 'left',
type: 'text',
content: response.data.text,
};
const updatedMessages = [...newMessages, aiResponse];
const finalFolders = folders.map((f) =>
f.name === selectedFolder
? { ...f, chats: { ...f.chats, [selectedChat]: updatedMessages } }
: f
);
setFolders(finalFolders);
} catch (error) {
console.error('Error sending message:', error);
}
};
const getFileType = (file: File): 'file' | 'image' | 'audio' | 'video' => {
if (file.type.startsWith('image/')) return 'image';
if (file.type.startsWith('audio/')) return 'audio';
if (file.type.startsWith('video/')) return 'video';
return 'file';
};
const handleChatSelect = (folderName: string, chatName: string) => {
setSelectedFolder(folderName);
setSelectedChat(chatName);
};
const handleFolderSelect = (folderName: string) => {
setSelectedFolder(folderName);
setSelectedChat(Object.keys(folders.find((f) => f.name === folderName)?.chats || {})[0]);
};
const handleCreateChat = (folderName: string, chatName: string) => {
const updatedFolders = folders.map((f) =>
f.name === folderName ? { ...f, chats: { ...f.chats, [chatName]: [] } } : f
);
setFolders(updatedFolders);
};
const handleCreateFolder = (folderName: string) => {
setFolders([...folders, { name: folderName, chats: {} }]);
};
const handleRenameChat = (folderName: string, oldName: string, newName: string) => {
const updatedFolders = folders.map((f) => {
if (f.name === folderName) {
const { [oldName]: oldChat, ...restChats } = f.chats;
return { ...f, chats: { ...restChats, [newName]: oldChat } };
}
return f;
});
setFolders(updatedFolders);
setSelectedChat(newName);
};
const handleRenameFolder = (oldName: string, newName: string) => {
const updatedFolders = folders.map((f) =>
f.name === oldName ? { ...f, name: newName } : f
);
setFolders(updatedFolders);
setSelectedFolder(newName);
};
const handleDeleteChat = (folderName: string, chatName: string) => {
setChatToDelete({ folderName, chatName });
setDeleteConfirmationOpen(true);
};
const handleDeleteFolder = (folderName: string) => {
setFolderToDelete(folderName);
setDeleteConfirmationOpen(true);
};
const handleConfirmDelete = () => {
if (chatToDelete) {
const { folderName, chatName } = chatToDelete;
const updatedFolders = folders.map((f) =>
f.name === folderName
? {
...f,
chats: Object.fromEntries(
Object.entries(f.chats).filter(([key]) => key !== chatName)
),
}
: f
);
setFolders(updatedFolders);
setSelectedChat(Object.keys(folders.find((f) => f.name === selectedFolder)?.chats || {})[0]);
setChatToDelete(null);
} else if (folderToDelete) {
const updatedFolders = folders.filter((f) => f.name !== folderToDelete);
setFolders(updatedFolders);
setSelectedFolder(updatedFolders[0]?.name || '');
setSelectedChat(Object.keys(updatedFolders[0]?.chats || {})[0]);
setFolderToDelete(null);
}
setDeleteConfirmationOpen(false);
};
const handleCancelDelete = () => {
setChatToDelete(null);
setFolderToDelete(null);
setDeleteConfirmationOpen(false);
};
return (
<Box sx={{ width: '100%', height: '100vh', display: 'flex', flexDirection: 'row' }}>
{/* Left Panel: Folder and Chat Tree */}
<Paper
elevation={3}
sx={{
width: '20%',
height: '100%',
overflowY: 'auto',
padding: '10px',
borderRadius: '10px',
}}
>
<NewFolderForm onCreateFolder={handleCreateFolder} />
<FolderList
folders={folders}
selectedFolder={selectedFolder}
selectedChat={selectedChat}
onFolderSelect={handleFolderSelect}
onChatSelect={handleChatSelect}
onRenameFolder={handleRenameFolder}
onDeleteFolder={handleDeleteFolder}
onRenameChat={handleRenameChat}
onDeleteChat={handleDeleteChat}
onCreateChat={handleCreateChat}
/>
</Paper>
{/* Center Panel: Chat Interface */}
<Box
sx={{
flex: 1,
display: 'flex',
flexDirection: 'column',
marginLeft: '10px',
marginRight: '10px',
}}
>
<Paper
elevation={3}
sx={{
flex: 1,
overflowY: 'auto',
padding: '10px',
borderRadius: '10px',
maxHeight: 'calc(100vh - 200px)',
}}
ref={chatContainerRef}
>
<MessageList
messages={folders.find((f) => f.name === selectedFolder)?.chats[selectedChat] || []}
/>
</Paper>
<MessageInput onSendMessage={sendMessage} />
</Box>
{/* Right Panel: Sliding Column */}
<RightPanel
isOpen={isRightPanelOpen}
onToggle={() => setIsRightPanelOpen(!isRightPanelOpen)}
/>
{/* Delete Confirmation Dialog */}
<Dialog
open={deleteConfirmationOpen}
onClose={handleCancelDelete}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{'Confirm Delete'}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure you want to delete this {chatToDelete ? 'chat' : 'folder'}?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleCancelDelete} color="primary">
No
</Button>
<Button onClick={handleConfirmDelete} color="primary" autoFocus>
Yes
</Button>
</DialogActions>
</Dialog>
</Box>
);
};
export default ChatComponent;
FolderList.tsx
import React, { useState } from 'react';
import {
List,
ListItem,
ListItemText,
IconButton,
Input,
Collapse,
ListItemIcon,
Divider,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import FolderIcon from '@mui/icons-material/Folder';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import NewChatForm from './NewChatForm';
import { Folder } from './types';
interface FolderListProps {
folders: Folder[];
selectedFolder: string;
selectedChat: string;
onFolderSelect: (folderName: string) => void;
onChatSelect: (folderName: string, chatName: string) => void;
onRenameFolder: (oldName: string, newName: string) => void;
onDeleteFolder: (folderName: string) => void;
onRenameChat: (folderName: string, oldName: string, newName: string) => void;
onDeleteChat: (folderName: string, chatName: string) => void;
onCreateChat: (folderName: string, chatName: string) => void;
}
const FolderList: React.FC<FolderListProps> = ({
folders,
selectedFolder,
selectedChat,
onFolderSelect,
onChatSelect,
onRenameFolder,
onDeleteFolder,
onRenameChat,
onDeleteChat,
onCreateChat,
}) => {
const [editingFolder, setEditingFolder] = useState<string | null>(null);
const [editedFolderName, setEditedFolderName] = useState<string>('');
const [editingChat, setEditingChat] = useState<{ folderName: string; chatName: string } | null>(
null
);
const [editedChatName, setEditedChatName] = useState<string>('');
const [openFolders, setOpenFolders] = useState<{ [folderName: string]: boolean }>({});
const handleToggleFolder = (folderName: string) => {
setOpenFolders((prev) => ({ ...prev, [folderName]: !prev[folderName] }));
};
const handleRenameFolderClick = (folderName: string) => {
setEditingFolder(folderName);
setEditedFolderName(folderName);
};
const handleSaveRenameFolder = () => {
if (editingFolder && editedFolderName) {
onRenameFolder(editingFolder, editedFolderName);
setEditingFolder(null);
}
};
const handleRenameChatClick = (folderName: string, chatName: string) => {
setEditingChat({ folderName, chatName });
setEditedChatName(chatName);
};
const handleSaveRenameChat = () => {
if (editingChat && editedChatName) {
onRenameChat(editingChat.folderName, editingChat.chatName, editedChatName);
setEditingChat(null);
}
};
return (
<List>
{folders.map((folder, index) => (
<div key={index}>
<ListItem
button
onClick={() => handleToggleFolder(folder.name)}
sx={{
backgroundColor: selectedFolder === folder.name ? '#1976d2' : 'transparent',
color: selectedFolder === folder.name ? 'white' : 'black',
borderRadius: '10px',
marginBottom: '5px',
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
'&:hover': {
boxShadow: 'inset 0 0 0 2px #1976d2',
},
}}
>
<ListItemIcon>
<FolderIcon color="inherit" />
</ListItemIcon>
{editingFolder === folder.name ? (
<Input
value={editedFolderName}
onChange={(e) => setEditedFolderName(e.target.value)}
onBlur={handleSaveRenameFolder}
autoFocus
fullWidth
/>
) : (
<ListItemText primary={folder.name} onClick={() => onFolderSelect(folder.name)} />
)}
<IconButton color="inherit" onClick={() => handleRenameFolderClick(folder.name)}>
<EditIcon sx={{ color: selectedFolder === folder.name ? 'white' : 'black' }} />
</IconButton>
<IconButton color="inherit" onClick={() => onDeleteFolder(folder.name)}>
<DeleteIcon sx={{ color: selectedFolder === folder.name ? 'white' : 'black' }} />
</IconButton>
{openFolders[folder.name] ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={openFolders[folder.name]} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{Object.keys(folder.chats).map((chatName, chatIndex) => (
<ListItem
key={chatIndex}
button
onClick={() => onChatSelect(folder.name, chatName)}
sx={{
pl: 4,
backgroundColor:
selectedFolder === folder.name && selectedChat === chatName
? '#2196f3'
: 'transparent',
color:
selectedFolder === folder.name && selectedChat === chatName
? 'white'
: 'black',
borderRadius: '10px',
marginBottom: '5px',
'&:hover': {
boxShadow: 'inset 0 0 0 2px #2196f3',
},
}}
>
<ListItemIcon>
<ChatBubbleOutlineIcon color="inherit" />
</ListItemIcon>
{editingChat &&
editingChat.folderName === folder.name &&
editingChat.chatName === chatName ? (
<Input
value={editedChatName}
onChange={(e) => setEditedChatName(e.target.value)}
onBlur={handleSaveRenameChat}
autoFocus
fullWidth
/>
) : (
<ListItemText primary={chatName} />
)}
<IconButton
color="inherit"
onClick={() => handleRenameChatClick(folder.name, chatName)}
>
<EditIcon
sx={{
color:
selectedFolder === folder.name && selectedChat === chatName
? 'white'
: 'black',
}}
/>
</IconButton>
<IconButton
color="inherit"
onClick={() => onDeleteChat(folder.name, chatName)}
>
<DeleteIcon
sx={{
color:
selectedFolder === folder.name && selectedChat === chatName
? 'white'
: 'black',
}}
/>
</IconButton>
</ListItem>
))}
{/* New Chat Form */}
<NewChatForm
onCreateChat={(chatName) => onCreateChat(folder.name, chatName)}
nested
/>
</List>
</Collapse>
{index < folders.length - 1 && <Divider />}
</div>
))}
</List>
);
};
export default FolderList;
NewChatForm.tsx
import React, { useState } from 'react';
import { ListItem, TextField, IconButton } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
interface NewChatFormProps {
onCreateChat: (chatName: string) => void;
nested?: boolean;
}
const NewChatForm: React.FC<NewChatFormProps> = ({ onCreateChat, nested = false }) => {
const [newChatName, setNewChatName] = useState('');
const handleCreateChat = () => {
if (newChatName) {
onCreateChat(newChatName);
setNewChatName('');
}
};
return (
<ListItem sx={{ pl: nested ? 4 : 0, borderRadius: '10px' }}>
<TextField
placeholder="New chat name"
value={newChatName}
onChange={(e) => setNewChatName(e.target.value)}
fullWidth
sx={{ width: '100%' }}
/>
<IconButton color="primary" onClick={handleCreateChat}>
<AddIcon />
</IconButton>
</ListItem>
);
};
export default NewChatForm;
Explanation:
Note:
This modification eliminates the separate ChatList component, integrating its functionality into the FolderList to create a tree structure. The chats are now displayed under their respective folders, and users can expand or collapse folders to view or hide the chats. All actions like rename, delete, and create are available for both folders and chats within this tree structure.
Remember to update your types.ts if necessary and ensure all components are properly imported and exported.
I hope this helps you achieve the desired tree structure for displaying chat folders and their chats. Let me know if you need further assistance or if you have any questions!