To enhance your chatbot interface to resemble a blend of Claude AI and ChatGPT, we'll restructure the App.js and introduce additional components to handle the various features you've specified. We'll use Tailwind CSS for styling, as it aligns with your current setup, and manage the layout using Flexbox for responsiveness.
Below is a comprehensive guide to achieve the desired interface:
-
Project Structure:
src/
├── components/
│ ├── Sidebar.js
│ ├── Header.js
│ ├── ChatWindow.js
│ └── CodeSidebar.js
├── App.js
└── index.css
-
Prerequisites:
-
Tailwind CSS: Ensure that Tailwind CSS is properly set up in your React project. If not, follow the Tailwind CSS installation guide for Create React App.
-
Icons: We'll use React Icons for AI icons and other UI elements. Install it using:
npm install react-icons
-
State Management: We'll use React's useState and useEffect hooks to manage state and side effects.
-
Components Overview:
- Sidebar: Contains options to start a new chat and list of old chats.
- Header: Displays the greeting based on the time of day and the AI icon.
- ChatWindow: Displays the conversation between the user and the AI.
- CodeSidebar: Shows code snippets in a sidebar when a code message is clicked.
-
Implementation Details:
Let's create each component step-by-step.
1. Sidebar Component (components/Sidebar.js)
This component will handle navigation between new chats and old chats.
// src/components/Sidebar.js
import React from "react";
import { FaPlus, FaHistory } from "react-icons/fa";
function Sidebar({ chats, setActiveChat, activeChat, onNewChat }) {
return (
<div className="w-64 bg-white shadow-md h-screen flex flex-col">
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-xl font-semibold">Chats</h2>
<button
onClick={onNewChat}
className="text-blue-500 hover:text-blue-700"
title="New Chat"
>
<FaPlus size={20} />
</button>
</div>
<div className="flex-1 overflow-y-auto">
{chats.length === 0 ? (
<p className="p-4 text-gray-500">No chats yet. Start a new chat!</p>
) : (
chats.map((chat, index) => (
<div
key={index}
onClick={() => setActiveChat(index)}
className={`p-4 cursor-pointer hover:bg-gray-100 ${
activeChat === index ? "bg-gray-200" : ""
} flex items-center justify-between`}
>
<span>Chat {index + 1}</span>
<FaHistory size={14} className="text-gray-500" />
</div>
))
)}
</div>
</div>
);
}
export default Sidebar;
2. Header Component (components/Header.js)
This component displays a dynamic greeting based on the time of day and includes the AI icon.
// src/components/Header.js
import React from "react";
import { FaRobot } from "react-icons/fa";
function Header() {
const getGreeting = () => {
const hour = new Date().getHours();
if (hour < 12) return "Good Morning";
if (hour < 18) return "Good Afternoon";
return "Good Evening";
};
return (
<div className="flex items-center justify-between p-4 bg-white shadow-md">
<div className="flex items-center">
<FaRobot size={30} className="text-blue-500 mr-2" />
<h1 className="text-2xl font-bold">{getGreeting()}</h1>
</div>
{/* Additional header items can be added here */}
</div>
);
}
export default Header;
3. ChatWindow Component (components/ChatWindow.js)
This component manages the display of messages between the user and the AI. It also handles embedding code snippets.
// src/components/ChatWindow.js
import React, { useRef, useEffect } from "react";
import { FaCopy } from "react-icons/fa";
function ChatWindow({ messages, onSend, input, setInput, onCodeClick }) {
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [messages]);
return (
<div className="flex flex-col flex-1">
<div className="flex-1 overflow-y-auto p-4 bg-gray-50">
{messages.map((msg, index) => (
<div
key={index}
className={`mb-4 flex ${
msg.sender === "user" ? "justify-end" : "justify-start"
}`}
>
<div
className={`px-4 py-2 rounded-lg max-w-xs ${
msg.sender === "user"
? "bg-blue-500 text-white"
: "bg-white text-gray-800 shadow"
}`}
onClick={() => {
if (msg.isCode && onCodeClick) onCodeClick(msg.code);
}}
>
{msg.isCode ? (
<pre className="whitespace-pre-wrap cursor-pointer">
{msg.code.length > 100
? `${msg.code.substring(0, 100)}...`
: msg.code}
{msg.code.length > 100 && (
<span className="text-blue-300"> Click to expand</span>
)}
</pre>
) : (
msg.text
)}
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
<div className="flex p-4 bg-white border-t">
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") onSend();
}}
/>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
onClick={onSend}
>
Send
</button>
</div>
</div>
);
}
export default ChatWindow;
4. CodeSidebar Component (components/CodeSidebar.js)
This component displays the full code snippet in a sidebar when a code message is clicked.
// src/components/CodeSidebar.js
import React from "react";
import { FaTimes } from "react-icons/fa";
function CodeSidebar({ code, onClose }) {
return (
<div className="fixed top-0 right-0 w-1/3 h-full bg-gray-100 shadow-lg p-4 overflow-y-auto">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold">Code Snippet</h2>
<button onClick={onClose}>
<FaTimes size={20} />
</button>
</div>
<pre className="bg-white p-4 rounded shadow overflow-auto">
<code>{code}</code>
</pre>
</div>
);
}
export default CodeSidebar;
5. Updated App Component (App.js)
Now, let's integrate all the components into the main App.js file.
// src/App.js
import React, { useState } from "react";
import axios from "axios";
import Sidebar from "./components/Sidebar";
import Header from "./components/Header";
import ChatWindow from "./components/ChatWindow";
import CodeSidebar from "./components/CodeSidebar";
import { FaSearch } from "react-icons/fa";
function App() {
const [input, setInput] = useState("");
const [chats, setChats] = useState([]);
const [activeChat, setActiveChat] = useState(null);
const [codeSnippet, setCodeSnippet] = useState(null);
const [commonQueries] = useState([
"What's the weather today?",
"Tell me a joke",
"Show me a React example",
]);
const sendMessage = async () => {
if (input.trim() === "") return;
const updatedChats = [...chats];
if (activeChat === null) {
// Starting a new chat
updatedChats.push([]);
setActiveChat(updatedChats.length - 1);
}
const chatIndex = activeChat !== null ? activeChat : updatedChats.length;
// Add user message
const userMessage = { sender: "user", text: input };
updatedChats[chatIndex] = [...(updatedChats[chatIndex] || []), userMessage];
setChats(updatedChats);
try {
const response = await axios.post("http://localhost:8000/api/chat", {
text: input,
});
// Check if the response contains code
const botText = response.data.response;
let botMessage = { sender: "bot", text: botText };
// Simple check for code block (you might want to implement a better logic)
if (botText.includes("```")) {
const codeMatch = botText.match(/```(?:\w+)?\n([\s\S]*?)```/);
if (codeMatch) {
const code = codeMatch[1];
botMessage = { sender: "bot", text: botText, isCode: true, code };
}
}
updatedChats[chatIndex] = [...updatedChats[chatIndex], botMessage];
setChats([...updatedChats]);
} catch (error) {
console.error("Error sending message:", error);
const errorMessage = {
sender: "bot",
text: "Sorry, something went wrong.",
};
updatedChats[chatIndex] = [...updatedChats[chatIndex], errorMessage];
setChats([...updatedChats]);
}
setInput("");
};
const startNewChat = () => {
setActiveChat(null);
setCodeSnippet(null);
};
const handleCodeClick = (code) => {
setCodeSnippet(code);
};
return (
<div className="flex h-screen">
{/* Sidebar */}
<Sidebar
chats={chats}
setActiveChat={setActiveChat}
activeChat={activeChat}
onNewChat={startNewChat}
/>
{/* Main Content */}
<div className="flex-1 flex flex-col">
{/* Header */}
<Header />
{/* Search Box and Common Queries (Visible when no active chat) */}
{activeChat === null && (
<div className="p-4 bg-gray-100">
{/* Search Box */}
<div className="flex mb-4">
<input
type="text"
className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
placeholder="Enter your query..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") sendMessage();
}}
/>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
onClick={sendMessage}
>
<FaSearch />
</button>
</div>
{/* Common Queries */}
<div>
<h3 className="text-lg font-semibold mb-2">Common Queries:</h3>
<div className="flex flex-wrap gap-2">
{commonQueries.map((query, index) => (
<button
key={index}
className="bg-gray-200 text-gray-800 px-3 py-1 rounded hover:bg-gray-300"
onClick={() => setInput(query)}
>
{query}
</button>
))}
</div>
</div>
</div>
)}
{/* Chat Window (Visible when a chat is active) */}
{activeChat !== null && (
<ChatWindow
messages={chats[activeChat]}
onSend={sendMessage}
input={input}
setInput={setInput}
onCodeClick={handleCodeClick}
/>
)}
</div>
{/* Code Sidebar */}
{codeSnippet && (
<CodeSidebar code={codeSnippet} onClose={() => setCodeSnippet(null)} />
)}
</div>
);
}
export default App;
6. Styling (index.css)
Ensure your index.css includes the Tailwind directives. If you've followed Tailwind's installation, it should already be set. Here's a basic setup:
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom styles can be added below */
7. Explanation of Features Implemented
-
Greeting Header:
- The
Header component dynamically displays "Good Morning", "Good Afternoon", or "Good Evening" based on the user's local time.
- An AI icon (
FaRobot) is displayed alongside the greeting.
-
Sidebar:
- The
Sidebar component lists all previous chats and allows the user to start a new chat.
- If there are no chats, it prompts the user to start one.
- The sidebar remains fixed on the left side of the screen.
-
Search Box and Common Queries:
- When no chat is active (
activeChat === null), a search box is displayed at the top of the main content.
- Below the search box, commonly used queries are listed as clickable buttons. Clicking a common query populates the search box.
-
Chat Interface:
- Upon sending a message, the search box is replaced with the
ChatWindow.
- The
ChatWindow displays messages between the user and the AI.
- Messages from the user are aligned to the right with a blue background, while AI messages are aligned to the left with a light gray background.
- Input for new messages is located at the bottom of the
ChatWindow.
-
Code Snippets:
- If the AI response contains a code snippet (detected by the presence of ```), it's marked as a code message.
- Clicking on a truncated code snippet (if longer than 100 characters) opens the
CodeSidebar displaying the full code in a dedicated sidebar.
-
Responsive Design:
- The layout uses Flexbox to ensure that the sidebar, main content, and code sidebar adjust gracefully to different screen sizes.
8. Additional Considerations
-
Backend API Handling:
- Ensure that your backend API (
http://localhost:8000/api/chat) properly handles the incoming requests and returns responses in the expected format.
- For code snippets, the backend should format the response to include code blocks using triple backticks (```) to allow the frontend to detect and handle them accordingly.
-
Enhancements:
- Persistent Chats: Implement local storage or integrate with a database to persist chats across sessions.
- Authentication: Add user authentication to manage different users' chats.
- Improved Code Detection: Enhance the logic for detecting code snippets, possibly by using more sophisticated parsing or metadata from the backend.
-
Error Handling:
- Currently, if the API call fails, a generic error message is displayed. You can enhance this by providing more detailed error feedback based on the error type.
-
Styling:
- Customize the colors, fonts, and overall design to better match the aesthetics of Claude AI and ChatGPT.
- Consider adding animations or transitions for opening and closing the code sidebar to improve user experience.
9. Final Notes
The provided implementation offers a robust foundation for the desired chatbot interface. Feel free to adjust and expand upon the components to cater to additional features or design preferences. Ensure that all dependencies are installed and properly configured, and test the interface thoroughly to provide a seamless user experience.
If you require further assistance with other files or specific functionalities, feel free to ask!