To display your chat folders and chats as a tree structure, you can leverage Material-UI's TreeView and TreeItem components. This will allow you to nest chats under their respective folders, providing a hierarchical view that's intuitive for users.
Here's a step-by-step guide to implementing this:
- Update the Data Structure (If Necessary)
- Implement the TreeView Component
- Modify the Main
ChatComponent
- Update Styles and Functionality
- Provide Complete Code Examples
Let's go through each step in detail.
1. Update the Data Structure (If Necessary)
Ensure that your folder and chat data structure is compatible with a tree structure. Your current structure seems suitable, but here's a slightly refined version to make it more extensible:
// types.ts
export interface Message {
position: 'left' | 'right';
type: 'text' | 'image' | 'audio' | 'video' | 'file';
content: string;
text?: string;
fileName?: string;
}
export interface Chat {
name: string;
messages: Message[];
}
export interface Folder {
name: string;
chats: Chat[];
}
Explanation:
- Each
Folder contains an array of Chat objects.
- Each
Chat contains an array of Message objects.
This structure will help in rendering TreeItem components more effectively.
2. Implement the TreeView Component
Instead of having separate FolderList and ChatList components, we'll create a unified FolderChatTree component using TreeView and TreeItem.
Create FolderChatTree.tsx
// FolderChatTree.tsx
import React, { useState } from 'react';
import {
TreeView,
TreeItem,
} from '@mui/lab';
import {
ExpandMore,
ChevronRight,
Folder as FolderIcon,
Chat as ChatIcon,
Edit as EditIcon,
Delete as DeleteIcon,
Add as AddIcon,
} from '@mui/icons-material';
import { Folder } from './types';
import { IconButton, Box, Input } from '@mui/material';
interface FolderChatTreeProps {
folders: Folder[];
selectedFolder: string;
selectedChat: string;
onFolderSelect: (folderName: string) => void;
onChatSelect: (chatName: string) => void;
onCreateChat: (folderName: string, chatName: string) => void;
onCreateFolder: (folderName: string) => void;
onRenameFolder: (oldName: string, newName: string) => void;
onRenameChat: (folderName: string, oldName: string, newName: string) => void;
onDeleteFolder: (folderName: string) => void;
onDeleteChat: (folderName: string, chatName: string) => void;
}
const FolderChatTree: React.FC<FolderChatTreeProps> = ({
folders,
selectedFolder,
selectedChat,
onFolderSelect,
onChatSelect,
onCreateChat,
onCreateFolder,
onRenameFolder,
onRenameChat,
onDeleteFolder,
onDeleteChat
}) => {
const [editingNode, setEditingNode] = useState<{ type: 'folder' | 'chat'; name: string } | null>(null);
const [newName, setNewName] = useState<string>('');
const [addingChat, setAddingChat] = useState<string | null>(null);
const [newChatName, setNewChatName] = useState<string>('');
const [addingFolder, setAddingFolder] = useState<boolean>(false);
const [newFolderName, setNewFolderName] = useState<string>('');
const handleRename = () => {
if (editingNode) {
const { type, name } = editingNode;
if (type === 'folder') {
onRenameFolder(name, newName);
} else if (type === 'chat') {
// Find the folder that contains this chat
const folder = folders.find(f => f.chats.some(c => c.name === name));
if (folder) {
onRenameChat(folder.name, name, newName);
}
}
setEditingNode(null);
setNewName('');
}
};
const handleAddChat = (folderName: string) => {
if (newChatName.trim()) {
onCreateChat(folderName, newChatName.trim());
setNewChatName('');
setAddingChat(null);
}
};
const handleAddFolder = () => {
if (newFolderName.trim()) {
onCreateFolder(newFolderName.trim());
setNewFolderName('');
setAddingFolder(false);
}
};
return (
<Box>
<TreeView
defaultCollapseIcon={<ExpandMore />}
defaultExpandIcon={<ChevronRight />}
sx={{ flexGrow: 1, overflowY: 'auto' }}
>
{folders.map((folder) => (
<TreeItem
key={folder.name}
nodeId={`folder-${folder.name}`}
label={
<Box display="flex" alignItems="center">
<FolderIcon sx={{ marginRight: 1 }} />
{editingNode?.type === 'folder' && editingNode.name === folder.name ? (
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
onBlur={handleRename}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleRename();
}
}}
autoFocus
/>
) : (
<span
onClick={() => onFolderSelect(folder.name)}
style={{ flexGrow: 1, cursor: 'pointer' }}
>
{folder.name}
</span>
)}
<IconButton size="small" onClick={() => { setEditingNode({ type: 'folder', name: folder.name }); setNewName(folder.name); }}>
<EditIcon fontSize="small" />
</IconButton>
<IconButton size="small" onClick={() => onDeleteFolder(folder.name)}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
}
>
{folder.chats.map((chat) => (
<TreeItem
key={chat.name}
nodeId={`chat-${chat.name}`}
label={
<Box display="flex" alignItems="center">
<ChatIcon sx={{ marginRight: 1 }} />
{editingNode?.type === 'chat' && editingNode.name === chat.name ? (
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
onBlur={handleRename}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleRename();
}
}}
autoFocus
/>
) : (
<span
onClick={() => onChatSelect(chat.name)}
style={{ flexGrow: 1, cursor: 'pointer' }}
>
{chat.name}
</span>
)}
<IconButton size="small" onClick={() => { setEditingNode({ type: 'chat', name: chat.name }); setNewName(chat.name); }}>
<EditIcon fontSize="small" />
</IconButton>
<IconButton size="small" onClick={() => onDeleteChat(folder.name, chat.name)}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
}
/>
))}
{addingChat === folder.name ? (
<Box display="flex" alignItems="center" pl={4} mt={1}>
<Input
placeholder="New chat name"
value={newChatName}
onChange={(e) => setNewChatName(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleAddChat(folder.name);
}
}}
autoFocus
/>
<IconButton size="small" color="primary" onClick={() => handleAddChat(folder.name)}>
<AddIcon fontSize="small" />
</IconButton>
<IconButton size="small" color="secondary" onClick={() => { setAddingChat(null); setNewChatName(''); }}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
) : (
<Box display="flex" alignItems="center" pl={4} mt={1}>
<IconButton size="small" onClick={() => setAddingChat(folder.name)}>
<AddIcon fontSize="small" />
</IconButton>
<span>Add Chat</span>
</Box>
)}
</TreeItem>
))}
</TreeView>
{addingFolder ? (
<Box display="flex" alignItems="center" mt={1}>
<Input
placeholder="New folder name"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleAddFolder();
}
}}
autoFocus
/>
<IconButton size="small" color="primary" onClick={handleAddFolder}>
<AddIcon fontSize="small" />
</IconButton>
<IconButton size="small" color="secondary" onClick={() => { setAddingFolder(false); setNewFolderName(''); }}>
<DeleteIcon fontSize="small" />
</IconButton>
</Box>
) : (
<Box display="flex" alignItems="center" mt={1}>
<IconButton size="small" onClick={() => setAddingFolder(true)}>
<AddIcon fontSize="small" />
</IconButton>
<span>Add Folder</span>
</Box>
)}
</Box>
);
};
export default FolderChatTree;
Explanation:
- TreeView & TreeItem: Hierarchical components from Material-UI Lab that allow nested views.
- Folder and Chat Nodes: Folders contain
TreeItem components for each chat.
- Editing & Adding: Provides inline editing and adding functionality for folders and chats.
- Icons: Uses appropriate icons for folders and chats for better visual distinction.
3. Modify the Main ChatComponent
Replace the separate FolderList and ChatList with the new FolderChatTree component.
Update chat.tsx
// chat.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 FolderChatTree from './FolderChatTree';
import MessageList from './MessageList';
import MessageInput from './MessageInput';
import RightPanel from './RightPanel';
const ChatComponent: React.FC = () => {
const [folders, setFolders] = useState<Folder[]>([{ name: 'Folder 1', chats: [{ name: 'Chat 1', messages: [] }] }]);
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(() => {
// Initialize with default folder and chat
setFolders([{ name: 'Folder 1', chats: [{ name: 'Chat 1', messages: [] }] }]);
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 folderIndex = folders.findIndex(f => f.name === selectedFolder);
if (folderIndex === -1) return;
const chatIndex = folders[folderIndex].chats.findIndex(c => c.name === selectedChat);
if (chatIndex === -1) return;
const updatedMessages = [...folders[folderIndex].chats[chatIndex].messages, newMessage];
const updatedFolders = [...folders];
updatedFolders[folderIndex].chats[chatIndex].messages = updatedMessages;
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 finalMessages = [...updatedMessages, aiResponse];
updatedFolders[folderIndex].chats[chatIndex].messages = finalMessages;
setFolders([...updatedFolders]);
} 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 handleFolderSelect = (folderName: string) => {
setSelectedFolder(folderName);
const folder = folders.find(f => f.name === folderName);
if (folder && folder.chats.length > 0) {
setSelectedChat(folder.chats[0].name);
} else {
setSelectedChat('');
}
};
const handleChatSelect = (chatName: string) => {
setSelectedChat(chatName);
};
const handleCreateChat = (folderName: string, chatName: string) => {
setFolders(prevFolders =>
prevFolders.map(folder =>
folder.name === folderName
? { ...folder, chats: [...folder.chats, { name: chatName, messages: [] }] }
: folder
)
);
setSelectedFolder(folderName);
setSelectedChat(chatName);
};
const handleCreateFolder = (folderName: string) => {
setFolders(prevFolders => [...prevFolders, { name: folderName, chats: [] }]);
};
const handleRenameChat = (folderName: string, oldName: string, newName: string) => {
setFolders(prevFolders =>
prevFolders.map(folder =>
folder.name === folderName
? {
...folder,
chats: folder.chats.map(chat =>
chat.name === oldName ? { ...chat, name: newName } : chat
),
}
: folder
)
);
if (selectedChat === oldName) {
setSelectedChat(newName);
}
};
const handleRenameFolder = (oldName: string, newName: string) => {
setFolders(prevFolders =>
prevFolders.map(folder =>
folder.name === oldName ? { ...folder, name: newName } : folder
)
);
if (selectedFolder === oldName) {
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;
setFolders(prevFolders =>
prevFolders.map(folder =>
folder.name === folderName
? {
...folder,
chats: folder.chats.filter(chat => chat.name !== chatName),
}
: folder
)
);
setSelectedChat('');
setChatToDelete(null);
} else if (folderToDelete) {
setFolders(prevFolders => prevFolders.filter(folder => folder.name !== folderToDelete));
setSelectedFolder('');
setSelectedChat('');
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' }}>
<FolderChatTree
folders={folders}
selectedFolder={selectedFolder}
selectedChat={selectedChat}
onFolderSelect={handleFolderSelect}
onChatSelect={handleChatSelect}
onCreateChat={handleCreateChat}
onCreateFolder={handleCreateFolder}
onRenameFolder={handleRenameFolder}
onRenameChat={handleRenameChat}
onDeleteFolder={handleDeleteFolder}
onDeleteChat={handleDeleteChat}
/>
</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.find(c => c.name === selectedChat)?.messages || []
} />
</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;
Explanation:
- FolderChatTree Integration: Replaces the old
FolderList and ChatList with the FolderChatTree component.
- State Management: Adjusted to handle nested structures, ensuring that folder and chat selections are synchronized.
- Handlers: Updated creation, renaming, and deletion handlers to support the new data structure.
4. Update Styles and Functionality
Ensure that the styles and interactions are smooth. You might need to adjust padding, margins, or other CSS properties to fit the new tree structure.
Optional Enhancements:
- Persist State: Consider storing folders and chats in a backend or using
localStorage to persist user data.
- Drag and Drop: Implement drag-and-drop functionality for reorganizing folders and chats.
- Icons & Visuals: Enhance the UI with more icons or badges to represent unread messages, favorites, etc.
5. Provide Complete Code Examples
For completeness, here's the updated and new files you need.
Updated types.ts
// types.ts
export interface Message {
position: 'left' | 'right';
type: 'text' | 'image' | 'audio' | 'video' | 'file';
content: string;
text?: string;
fileName?: string;
}
export interface Chat {
name: string;
messages: Message[];
}
export interface Folder {
name: string;
chats: Chat[];
}
New FolderChatTree.tsx
(As provided above)
Updated chat.tsx
(As provided above)
Ensure Dependencies are Installed
Since we're using Material-UI's TreeView and TreeItem, ensure you have the @mui/lab package installed.
npm install @mui/lab
# or
yarn add @mui/lab
Ensure Proper Imports in Other Components
If any other components like MessageList, MessageInput, or RightPanel need adjustments, ensure they correctly handle the updated data structure. For example, MessageList.tsx should receive the messages prop as an array of Message objects.
Final Thoughts
By integrating TreeView and TreeItem, your chat application will offer a more organized and intuitive navigation structure. This hierarchical view not only improves user experience but also makes it easier to manage multiple folders and chats.
Feel free to further customize the tree components to better fit your application's needs, such as adding search functionality, icons, or additional metadata.
If you encounter any issues or need further customization, feel free to ask!