Building a comprehensive AI assistant interface with React and TailwindCSS involves creating multiple components and managing the state efficiently. Below is a step-by-step guide to help you set up the frontend based on your requirements.
Table of Contents
- Project Setup
- Installing Dependencies
- TailwindCSS Configuration
- Project Structure
- Implementing Components
- Utility Functions
- Styling with TailwindCSS
- Persisting Data
- Final Thoughts
Project Setup
First, we'll set up a new React project using Vite for a faster development experience.
# Install Vite globally if you haven't already
npm install -g create-vite
# Create a new React project
npm create vite@latest ai-assistant --template react
# Navigate to the project directory
cd ai-assistant
# Install dependencies
npm install
Installing Dependencies
We'll need several dependencies to meet the requirements:
- TailwindCSS for styling
- React Router for navigation
- React Markdown for rendering markdown
- React Copy-to-Clipboard for copy functionality
- React Icons for icons
- LocalForage or localStorage for persisting data
Install the necessary packages:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
npm install react-router-dom react-markdown copy-to-clipboard react-icons localforage
TailwindCSS Configuration
Configure TailwindCSS by updating tailwind.config.js:
// tailwind.config.js
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,jsx,ts,tsx}",
],
darkMode: 'class', // Enable dark mode
theme: {
extend: {},
},
plugins: [],
}
Update your src/index.css to include Tailwind's base styles:
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Project Structure
Organize your project with the following structure:
ai-assistant/
├── src/
│ ├── components/
│ │ ├── Sidebar.jsx
│ │ ├── Home.jsx
│ │ ├── Chat.jsx
│ │ ├── MessageInput.jsx
│ │ ├── CodePane.jsx
│ │ ├── ModulePresets.jsx
│ ├── context/
│ │ └── ThemeContext.jsx
│ ├── utils/
│ │ └── api.js
│ ├── App.jsx
│ ├── main.jsx
│ └── index.css
├── tailwind.config.js
├── package.json
└── ...
Implementing Components
1. App Component
The App component sets up the routing and theme context.
// src/App.jsx
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Sidebar from './components/Sidebar';
import Home from './components/Home';
import Chat from './components/Chat';
import { ThemeContext, themes } from './context/ThemeContext';
function App() {
const [theme, setTheme] = useState(themes.light);
// Load theme from localStorage
useEffect(() => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) setTheme(savedTheme);
}, []);
// Toggle theme and save to localStorage
const toggleTheme = () => {
const newTheme = theme === themes.light ? themes.dark : themes.light;
setTheme(newTheme);
localStorage.setItem('theme', newTheme);
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<div className={theme === themes.dark ? 'dark' : ''}>
<div className="min-h-screen bg-gray-100 dark:bg-gray-900 flex">
<Router>
<Sidebar />
<div className="flex-1">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/chat/:id" element={<Chat />} />
</Routes>
</div>
</Router>
</div>
</ThemeContext.Provider>
</div>
);
}
export default App;
2. Theme Context
Manage light and dark themes using Context API.
// src/context/ThemeContext.jsx
import React from 'react';
export const themes = {
light: 'light',
dark: 'dark',
};
export const ThemeContext = React.createContext({
theme: themes.light,
toggleTheme: () => {},
});
3. Sidebar Component
The sidebar displays chat history and includes theme toggling.
// src/components/Sidebar.jsx
import React, { useEffect, useState, useContext } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { ThemeContext } from '../context/ThemeContext';
import { FaSun, FaMoon } from 'react-icons/fa';
function Sidebar() {
const [chats, setChats] = useState([]);
const navigate = useNavigate();
const { theme, toggleTheme } = useContext(ThemeContext);
useEffect(() => {
const savedChats = JSON.parse(localStorage.getItem('chatHistory')) || [];
setChats(savedChats);
}, []);
const addNewChat = () => {
const newChat = { id: Date.now(), name: `Assistant ${chats.length + 1}` };
const updatedChats = [...chats, newChat];
setChats(updatedChats);
localStorage.setItem('chatHistory', JSON.stringify(updatedChats));
navigate(`/chat/${newChat.id}`);
};
return (
<div className="w-64 bg-white dark:bg-gray-800 shadow-md">
<div className="p-4 flex justify-between items-center">
<h2 className="text-xl font-bold text-gray-800 dark:text-white">AI Assistant</h2>
<button onClick={toggleTheme} className="text-gray-800 dark:text-white">
{theme === 'light' ? <FaMoon /> : <FaSun />}
</button>
</div>
<hr className="border-gray-200 dark:border-gray-700" />
<div className="p-4 flex flex-col space-y-2">
{chats.map(chat => (
<Link
key={chat.id}
to={`/chat/${chat.id}`}
className="block p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
>
{chat.name}
</Link>
))}
<button
onClick={addNewChat}
className="mt-2 p-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
+ New Chat
</button>
</div>
</div>
);
}
export default Sidebar;
4. Home Page
The home page greets the user based on the time of day and includes a message box to start a chat.
// src/components/Home.jsx
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function Home() {
const [greeting, setGreeting] = useState('Hello');
const [input, setInput] = useState('');
const navigate = useNavigate();
useEffect(() => {
const hour = new Date().getHours();
if (hour < 12) setGreeting('Good morning');
else if (hour < 18) setGreeting('Good afternoon');
else setGreeting('Good evening');
}, []);
const startChat = () => {
// Implement logic to create a new chat and navigate
navigate('/chat/new');
};
return (
<div className="flex flex-col items-center justify-center h-full p-4">
<h1 className="text-4xl font-bold mb-6 text-gray-800 dark:text-white">{greeting}!</h1>
<div className="w-full max-w-md">
<textarea
className="w-full p-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
placeholder="Type your message..."
value={input}
onChange={e => setInput(e.target.value)}
rows={4}
></textarea>
<button
onClick={startChat}
className="mt-4 w-full p-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
>
Start Chat
</button>
</div>
</div>
);
}
export default Home;
5. Chat Interface
The Chat component manages the chat history, message sending, and interactions.
// src/components/Chat.jsx
import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import MessageInput from './MessageInput';
import CodePane from './CodePane';
import ReactMarkdown from 'react-markdown';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { FiCopy, FiExternalLink } from 'react-icons/fi';
import localforage from 'localforage';
function Chat() {
const { id } = useParams();
const [messages, setMessages] = useState([]);
const [code, setCode] = useState(null);
const [showCodePane, setShowCodePane] = useState(false);
const [systemPrompt, setSystemPrompt] = useState('');
const messagesEndRef = useRef(null);
useEffect(() => {
// Load chat history
const loadChat = async () => {
const savedChats = (await localforage.getItem('chatHistory')) || [];
const chat = savedChats.find(c => c.id.toString() === id);
if (chat) {
setMessages(chat.messages || []);
setSystemPrompt(chat.systemPrompt || '');
}
};
loadChat();
}, [id]);
useEffect(() => {
// Scroll to bottom when messages change
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const sendMessage = async (text) => {
const newMessage = { sender: 'user', text };
const updatedMessages = [...messages, newMessage];
setMessages(updatedMessages);
await saveChat(updatedMessages);
// Send to backend
try {
const response = await fetch('http://localhost:8000/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
const data = await response.json();
const botMessage = { sender: 'bot', text: data.response };
setMessages(prev => [...prev, botMessage]);
await saveChat([...updatedMessages, botMessage]);
// Check if the bot response contains code
const codeMatch = data.response.match(/```
```/);
if (codeMatch) {
setCode(codeMatch[1]);
}
} catch (error) {
console.error('Error:', error);
}
};
const saveChat = async (updatedMessages) => {
const savedChats = (await localforage.getItem('chatHistory')) || [];
const updatedChats = savedChats.map(c =>
c.id.toString() === id ? { ...c, messages: updatedMessages, systemPrompt } : c
);
await localforage.setItem('chatHistory', updatedChats);
};
const toggleCodePane = () => {
setShowCodePane(!showCodePane);
};
const handleSystemPromptChange = (e) => {
setSystemPrompt(e.target.value);
// Update in localStorage
localforage.getItem('chatHistory').then(savedChats => {
const updatedChats = savedChats.map(c =>
c.id.toString() === id ? { ...c, systemPrompt: e.target.value } : c
);
localforage.setItem('chatHistory', updatedChats);
});
};
const insertModule = (moduleTag) => {
setSystemPrompt(prev => `${prev}\n${moduleTag}`);
// Update in localStorage
localforage.getItem('chatHistory').then(savedChats => {
const updatedChats = savedChats.map(c =>
c.id.toString() === id ? { ...c, systemPrompt: `${c.systemPrompt}\n${moduleTag}` } : c
);
localforage.setItem('chatHistory', updatedChats);
});
};
return (
<div className="flex flex-col h-full">
<div className="p-4 border-b dark:border-gray-700">
<textarea
className="w-full p-2 border rounded dark:bg-gray-700 dark:text-white"
placeholder="Enter system prompt..."
value={systemPrompt}
onChange={handleSystemPromptChange}
rows={3}
></textarea>
</div>
<div className="flex-1 overflow-y-auto p-4">
{messages.map((msg, index) => (
<div key={index} className={`mb-4 ${msg.sender === 'user' ? 'text-right' : 'text-left'}`}>
<div
className={`inline-block p-3 rounded ${
msg.sender === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white'
} max-w-md`}
>
<ReactMarkdown
children={msg.text}
components={{
code({ node, inline, className, children, ...props }) {
return !inline ? (
<pre className="relative">
<code className={`${className} bg-gray-100 dark:bg-gray-800 p-2 block`}>
{children}
</code>
<CopyToClipboard text={children}>
<button className="absolute top-2 right-2 text-gray-500 dark:text-gray-300">
<FiCopy />
</button>
</CopyToClipboard>
{msg.sender === 'bot' && (
<button
onClick={toggleCodePane}
className="absolute top-2 right-10 text-gray-500 dark:text-gray-300"
>
<FiExternalLink />
</button>
)}
</pre>
) : (
<code className={`${className} bg-gray-100 dark:bg-gray-800 p-1 rounded`}>
{children}
</code>
);
},
}}
/>
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
<MessageInput onSend={sendMessage} insertModule={insertModule} />
{showCodePane && code && <CodePane code={code} onClose={toggleCodePane} />}
</div>
);
}
export default Chat;
6. Message Input
The MessageInput component handles sending messages and inserting modules.
// src/components/MessageInput.jsx
import React, { useState } from 'react';
import { FiSend, FiPlus } from 'react-icons/fi';
function MessageInput({ onSend, insertModule }) {
const [input, setInput] = useState('');
const [showModules, setShowModules] = useState(false);
const handleSend = () => {
if (input.trim() !== '') {
onSend(input);
setInput('');
}
};
const handleKeyPress = (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const modules = [
'<information>',
'<log>',
'<instructions>',
// Add more modules as needed
];
return (
<div className="p-4 border-t dark:border-gray-700 flex flex-col">
{showModules && (
<div className="mb-2 flex flex-wrap gap-2">
{modules.map((module, index) => (
<button
key={index}
onClick={() => insertModule(module)}
className="px-3 py-1 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-white rounded"
>
{module}
</button>
))}
</div>
)}
<div className="flex items-center">
<button
onClick={() => setShowModules(!showModules)}
className="mr-2 text-gray-600 dark:text-gray-300"
>
<FiPlus />
</button>
<textarea
className="flex-1 p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
placeholder="Type your message..."
value={input}
onChange={e => setInput(e.target.value)}
onKeyPress={handleKeyPress}
rows={1}
></textarea>
<button onClick={handleSend} className="ml-2 text-blue-500">
<FiSend size={24} />
</button>
</div>
</div>
);
}
export default MessageInput;
7. Code Pop-Out Pane
The CodePane component displays code in a separate side pane.
// src/components/CodePane.jsx
import React from 'react';
import ReactMarkdown from 'react-markdown';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { FiCopy, FiX } from 'react-icons/fi';
function CodePane({ code, onClose }) {
return (
<div className="fixed right-0 top-0 h-full w-1/3 bg-white dark:bg-gray-800 shadow-lg p-4 overflow-auto z-50">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold text-gray-800 dark:text-white">Code Snippet</h2>
<button onClick={onClose} className="text-gray-800 dark:text-white">
<FiX size={24} />
</button>
</div>
<pre className="relative bg-gray-100 dark:bg-gray-700 p-4 rounded">
<code>
{code}
</code>
<CopyToClipboard text={code}>
<button className="absolute top-2 right-2 text-gray-500 dark:text-gray-300">
<FiCopy />
</button>
</CopyToClipboard>
</pre>
</div>
);
}
export default CodePane;
8. Module Presets
The module presets are already integrated into the MessageInput component as buttons that insert XML tags into the system prompt.
If you wish to have a separate component for managing presets, you can create one. However, for simplicity, the insertion functionality is handled directly within the MessageInput.
Utility Functions
Create a utility file for API interactions.
// src/utils/api.js
export const sendMessage = async (text) => {
const response = await fetch('http://localhost:8000/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
// Add more API utilities as needed
Styling with TailwindCSS
TailwindCSS classes are used throughout the components to style elements. Make sure classes correspond to the desired appearance, especially for dark mode.
Example:
<div className="bg-white dark:bg-gray-800">
{/* Content */}
</div>
Persisting Data
We're using localforage to persist chat history and settings in localStorage. Ensure data is saved and loaded correctly in each component.
Example in Sidebar:
// Saving a new chat
const addNewChat = () => {
const newChat = { id: Date.now(), name: `Assistant ${chats.length + 1}`, messages: [] };
const updatedChats = [...chats, newChat];
setChats(updatedChats);
localforage.setItem('chatHistory', updatedChats);
navigate(`/chat/${newChat.id}`);
};
Note: Ensure all mutations to chat data also update localforage.
Final Thoughts
This setup provides a solid foundation for your AI assistant frontend. Here's a summary of the features covered:
- Home Page Greeting: Dynamically displays a greeting based on the time of day.
- Chat Interface: Allows sending and receiving messages with markdown and code support.
- Code Pop-Out Pane: View and copy code snippets in a separate pane.
- Modules Insertion: Insert predefined XML tags into the system prompt.
- Sidebar with Chat History: Persisted across sessions using
localStorage.
- Light/Dark Theme: Toggle between themes with persistence.
- Copy Functionality: Easily copy messages and code snippets.
Additional Enhancements
To further enhance the application, consider implementing:
- Authentication: Secure user data and manage multiple users.
- Better State Management: Utilize Context API or Redux for more complex state handling.
- Error Handling: Improve user feedback for failed operations.
- Responsive Design: Ensure the interface works well on all device sizes.
- Animations: Add subtle animations for transitions and interactions.
Feel free to expand upon this foundation to suit your specific needs. If you encounter any issues or need further assistance, don't hesitate to ask!