To add a rename chat feature to your AI assistant interface, you'll need to enhance the Sidebar.js component to allow users to edit the names of their chats. Here's a step-by-step guide to implementing this feature:
-
Update ChatContext (Already Handled)
You've already defined an updateChat function in your ChatContext, which allows updating chat properties. This function will be utilized to update the chat names.
-
Modify Sidebar.js
The main changes will occur in the Sidebar.js component. We'll add an edit (rename) functionality by introducing an edit icon next to each chat and allowing in-line editing of the chat name.
Step-by-Step Implementation
1. Import Necessary Modules and Icons
First, import the useState hook from React and the PencilAltIcon from @heroicons/react/solid. The PencilAltIcon will serve as the edit (rename) button.
// src/components/Sidebar.js
import React, { useContext, useState } from 'react';
import { ChatContext } from '../context/ChatContext';
import { PlusIcon, TrashIcon, PencilAltIcon } from '@heroicons/react/solid'; // Imported PencilAltIcon
import { ThemeContext } from '../context/ThemeContext';
2. Add State for Editing
Introduce two new state variables:
editingChatId: To keep track of which chat is currently being edited.
newChatName: To store the new name input by the user.
function Sidebar() {
const {
chats,
currentChatId,
setCurrentChatId,
addChat,
deleteChat,
updateChat, // Destructure updateChat from ChatContext
} = useContext(ChatContext);
const { theme, toggleTheme } = useContext(ThemeContext);
const [editingChatId, setEditingChatId] = useState(null); // New state for editing
const [newChatName, setNewChatName] = useState(''); // New state for the new chat name
3. Handle Edit Actions
Add functions to handle initiating the edit, saving the new name, and handling key events like Enter and Escape.
// Function to initiate editing
const handleEditChat = (id, currentName) => {
setEditingChatId(id);
setNewChatName(currentName);
};
// Function to handle saving the new name on blur or Enter key
const handleRename = () => {
if (editingChatId && newChatName.trim() !== '') {
updateChat(editingChatId, { name: newChatName });
setEditingChatId(null);
setNewChatName('');
} else {
// If the input is empty or only spaces, cancel editing
setEditingChatId(null);
setNewChatName('');
}
};
// Function to handle key events in the input field
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
handleRename();
} else if (e.key === 'Escape') {
setEditingChatId(null);
setNewChatName('');
}
};
4. Update the Chat List Rendering
Modify the rendering of each chat in the list to conditionally show either the chat name or an input field for editing. Also, include the edit (pencil) icon next to the delete (trash) icon.
return (
<div className="w-64 bg-gray-100 dark:bg-zinc-900 border-r dark:border-gray-700 p-4 flex flex-col">
{/* Chatbot Name "Echo" at the top */}
<div
className="mb-6 text-2xl font-bold text-gray-800 dark:text-gray-200 cursor-pointer"
onClick={handleGoHome}
>
Echo
</div>
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-200">Past Chats</h2>
<button
onClick={handleNewChat}
className="p-2 bg-blue-500 text-white rounded hover:bg-blue-600"
title="Start New Chat"
>
<PlusIcon className="h-5 w-5" />
</button>
</div>
<ul className="flex-1 overflow-y-auto">
{chats.length === 0 && (
<li className="text-gray-500 dark:text-gray-400">No past chats.</li>
)}
{chats.map((chat) => (
<li
key={chat.id}
className={`mb-2 cursor-pointer p-2 rounded flex justify-between items-center ${
chat.id === currentChatId
? 'bg-blue-100 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={() => handleSelectChat(chat.id)}
>
{/* Conditional rendering for editing */}
{editingChatId === chat.id ? (
<input
type="text"
value={newChatName}
onChange={(e) => setNewChatName(e.target.value)}
onBlur={handleRename}
onKeyDown={handleKeyDown}
autoFocus
className="bg-transparent border-b border-gray-300 dark:border-gray-600 focus:outline-none focus:border-blue-500 text-black dark:text-white"
onClick={(e) => e.stopPropagation()} // Prevent triggering select chat
/>
) : (
<span className='text-black dark:text-white'>{chat.name}</span>
)}
<div className="flex items-center">
{/* Show edit button only if not currently editing this chat */}
{editingChatId !== chat.id && (
<button
onClick={(e) => {
e.stopPropagation();
handleEditChat(chat.id, chat.name);
}}
className="text-gray-500 hover:text-gray-700 mr-2"
title="Rename Chat"
>
<PencilAltIcon className="h-5 w-5" />
</button>
)}
<button
onClick={(e) => handleDeleteChat(e, chat.id)}
className="text-red-500 hover:text-red-700"
title="Delete Chat"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</li>
))}
</ul>
{/* Dark Mode Toggle at the bottom */}
<div className="mt-4">
<DarkModeToggle theme={theme} toggleTheme={toggleTheme} />
</div>
</div>
);
}
5. Complete Sidebar.js with All Changes
Here's the complete updated Sidebar.js with all the changes integrated:
// src/components/Sidebar.js
import React, { useContext, useState } from 'react';
import { ChatContext } from '../context/ChatContext';
import { PlusIcon, TrashIcon, PencilAltIcon } from '@heroicons/react/solid';
import { ThemeContext } from '../context/ThemeContext';
function Sidebar() {
const {
chats,
currentChatId,
setCurrentChatId,
addChat,
deleteChat,
updateChat, // Destructure updateChat from ChatContext
} = useContext(ChatContext);
const { theme, toggleTheme } = useContext(ThemeContext);
const [editingChatId, setEditingChatId] = useState(null); // State for editing
const [newChatName, setNewChatName] = useState(''); // State for new chat name
const handleSelectChat = (id) => {
setCurrentChatId(id);
};
const handleNewChat = () => {
addChat('New Chat');
};
const handleDeleteChat = (e, id) => {
e.stopPropagation(); // Prevent triggering the chat selection
deleteChat(id);
};
const handleGoHome = () => {
setCurrentChatId(null);
};
// Function to initiate editing
const handleEditChat = (id, currentName) => {
setEditingChatId(id);
setNewChatName(currentName);
};
// Function to handle saving the new name on blur or Enter key
const handleRename = () => {
if (editingChatId && newChatName.trim() !== '') {
updateChat(editingChatId, { name: newChatName });
setEditingChatId(null);
setNewChatName('');
} else {
// If the input is empty or only spaces, cancel editing
setEditingChatId(null);
setNewChatName('');
}
};
// Function to handle key events in the input field
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
handleRename();
} else if (e.key === 'Escape') {
setEditingChatId(null);
setNewChatName('');
}
};
return (
<div className="w-64 bg-gray-100 dark:bg-zinc-900 border-r dark:border-gray-700 p-4 flex flex-col">
{/* Chatbot Name "Echo" at the top */}
<div
className="mb-6 text-2xl font-bold text-gray-800 dark:text-gray-200 cursor-pointer"
onClick={handleGoHome}
>
Echo
</div>
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-200">Past Chats</h2>
<button
onClick={handleNewChat}
className="p-2 bg-blue-500 text-white rounded hover:bg-blue-600"
title="Start New Chat"
>
<PlusIcon className="h-5 w-5" />
</button>
</div>
<ul className="flex-1 overflow-y-auto">
{chats.length === 0 && (
<li className="text-gray-500 dark:text-gray-400">No past chats.</li>
)}
{chats.map((chat) => (
<li
key={chat.id}
className={`mb-2 cursor-pointer p-2 rounded flex justify-between items-center ${
chat.id === currentChatId
? 'bg-blue-100 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={() => handleSelectChat(chat.id)}
>
{/* Conditional rendering for editing */}
{editingChatId === chat.id ? (
<input
type="text"
value={newChatName}
onChange={(e) => setNewChatName(e.target.value)}
onBlur={handleRename}
onKeyDown={handleKeyDown}
autoFocus
className="bg-transparent border-b border-gray-300 dark:border-gray-600 focus:outline-none focus:border-blue-500 text-black dark:text-white"
onClick={(e) => e.stopPropagation()} // Prevent triggering select chat
/>
) : (
<span className='text-black dark:text-white'>{chat.name}</span>
)}
<div className="flex items-center">
{/* Show edit button only if not currently editing this chat */}
{editingChatId !== chat.id && (
<button
onClick={(e) => {
e.stopPropagation();
handleEditChat(chat.id, chat.name);
}}
className="text-gray-500 hover:text-gray-700 mr-2"
title="Rename Chat"
>
<PencilAltIcon className="h-5 w-5" />
</button>
)}
<button
onClick={(e) => handleDeleteChat(e, chat.id)}
className="text-red-500 hover:text-red-700"
title="Delete Chat"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</li>
))}
</ul>
{/* Dark Mode Toggle at the bottom */}
<div className="mt-4">
<DarkModeToggle theme={theme} toggleTheme={toggleTheme} />
</div>
</div>
);
}
function DarkModeToggle({ theme, toggleTheme }) {
return (
<div className="flex items-center justify-center">
<span className="text-gray-800 dark:text-gray-200 mr-2">Dark Mode</span>
<button
onClick={toggleTheme}
className={`relative inline-flex items-center h-6 rounded-full w-11 focus:outline-none transition-colors duration-200 ${
theme === 'dark' ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'
}`}
>
<span className="sr-only">Toggle Dark Mode</span>
<span
className={`${
theme === 'dark' ? 'translate-x-6' : 'translate-x-1'
} inline-block w-4 h-4 transform bg-white rounded-full transition-transform duration-200`}
/>
</button>
</div>
);
}
export default Sidebar;
6. Styling Considerations
The above implementation uses Tailwind CSS classes for styling. Here's what each part does:
7. Ensure Icons Are Available
Make sure that @heroicons/react is installed in your project. If not, you can install it using:
npm install @heroicons/react
or
yarn add @heroicons/react
8. Testing the Feature
After implementing the changes:
-
Start Editing:
- Click on the pencil icon next to a chat.
- The chat name should transform into an input field with the current name pre-filled.
-
Rename the Chat:
- Modify the name in the input field.
- Press Enter or click outside the input field to save the new name.
- The chat name should update accordingly.
-
Cancel Editing:
- While editing, press Escape to cancel the renaming.
- The chat name should revert to its original name.
-
Edge Cases:
- Attempting to rename a chat to an empty string or only spaces should cancel the edit without changing the name.
Final Thoughts
By following the above steps, you've successfully added a rename chat feature to your AI assistant interface. This enhancement improves user experience by allowing users to personalize and manage their chat history more effectively.
If you encounter any issues or have further customizations in mind, feel free to ask!