To achieve the desired behavior where your custom text box (InlineCodeEditor) grows to fill the available space not occupied by the buttons and wraps its content appropriately, you need to properly configure your Flexbox layout and ensure the CSS properties allow for responsive resizing and wrapping.
Below is a step-by-step guide to help you modify your existing components to accomplish this.
1. Understanding the Current Layout
Current Structure in ChatInterface.js
<div className="flex flex-row">
<div className="flex-grow">
<InlineCodeEditor
value={message}
onChange={setMessage}
onAttachCode={handleAttachCode}
onKeyDown={handleEditorKeyDown}
/>
</div>
<div className="flex flex-col flex-grow-0 items-end pl-4">
<button
onClick={() => setIsCodeModalOpen(true)}
className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600 flex-grow w-full"
>
Attach Code
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 flex-grow mt-2 w-full"
onClick={handleSend}
>
Send
</button>
</div>
</div>
Current Style in InlineCodeEditor.js
<div className="min-h-[100px] max-h-[300px] overflow-y-auto p-2 focus:outline-none" contentEditable ... />
2. Objective
- Grow the Text Box: Ensure the
InlineCodeEditor expands to fill the available horizontal space not used by the buttons.
- Wrapping Content: Ensure that the text within the
InlineCodeEditor wraps appropriately when reaching the end of the container.
3. Step-by-Step Solution
A. Adjusting the Flex Container in ChatInterface.js
-
Ensure Proper Flex Growth for the Editor
- The parent container for the editor and buttons is using
flex flex-row, which is correct for arranging them side by side.
- The editor container currently uses
flex-grow, which allows it to take up available space.
-
Optimize Button Container
- The button container uses
flex flex-col flex-grow-0, which prevents it from growing and allows it to size based on its content.
- Ensure that buttons have a consistent width and do not take up unnecessary space.
-
Modify the Button Styles
- Remove
flex-grow and w-full from the buttons to prevent them from stretching unnecessarily within their container.
- Instead, set a fixed width or allow them to size based on their content.
-
Implementing the Changes
Here’s the updated structure with comments explaining the changes:
<div className="flex flex-row">
{/* Editor Container */}
<div className="flex-grow">
<InlineCodeEditor
value={message}
onChange={setMessage}
onAttachCode={handleAttachCode}
onKeyDown={handleEditorKeyDown}
/>
</div>
{/* Button Container */}
<div className="flex flex-col flex-shrink-0 items-start pl-4 space-y-2">
{/* Removed flex-grow and w-full to allow buttons to size based on content */}
<button
onClick={() => setIsCodeModalOpen(true)}
className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600"
>
Attach Code
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600"
onClick={handleSend}
>
Send
</button>
</div>
</div>
Changes Explained:
B. Ensuring the Editor Fills the Available Space
-
Update the Editor's Style in InlineCodeEditor.js
- Ensure that the
contentEditable div uses full width.
- Add
w-full to make sure it stretches to fill its parent.
-
Modify the Class Names
<div className="relative border rounded-lg p-2 bg-white dark:bg-[#18181b] text-black dark:text-white">
<div
ref={editorRef}
className="w-full min-h-[100px] max-h-[300px] overflow-y-auto p-2 focus:outline-none"
contentEditable
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onClick={handleBubbleClick}
role="textbox"
aria-multiline="true"
aria-label="Code Editor"
/>
</div>
Changes Explained:
- Added
w-full to the contentEditable div to ensure it takes up all available horizontal space within its container.
C. Ensuring Content Wrapping in the Editor
-
CSS for Wrapping Content
- By default, text within a
div should wrap unless otherwise specified.
- However,
contentEditable elements might have different behaviors based on CSS.
-
Add Word Wrapping
- To ensure that long lines wrap within the editor, add
break-words.
-
Updated Class Names
<div
ref={editorRef}
className="w-full min-h-[100px] max-h-[300px] overflow-y-auto p-2 focus:outline-none break-words"
contentEditable
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onClick={handleBubbleClick}
role="textbox"
aria-multiline="true"
aria-label="Code Editor"
/>
- Added
break-words: This ensures that long words or continuous text will wrap to the next line instead of overflowing.
-
Alternative with word-wrap
If break-words doesn't achieve the desired effect, you can use word-wrap: break-word; via Tailwind's break-all or custom CSS.
<div
ref={editorRef}
className="w-full min-h-[100px] max-h-[300px] overflow-y-auto p-2 focus:outline-none break-all"
contentEditable
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onClick={handleBubbleClick}
role="textbox"
aria-multiline="true"
aria-label="Code Editor"
/>
- Added
break-all: This ensures that the text will wrap at any character to prevent overflow.
D. Responsive Adjustments
To ensure the layout remains responsive across different screen sizes, consider adding responsive utility classes.
-
Update ChatInterface.js Layout
<div className="flex flex-col h-screen">
{/* ...other components... */}
<div
id="message_area"
className="p-4 border-t dark:border-gray-700 bg-white dark:bg-[#161618]"
>
{/* ...system prompt toggles... */}
<div className="flex flex-col md:flex-row">
<div className="flex-1 mb-4 md:mb-0">
<InlineCodeEditor
value={message}
onChange={setMessage}
onAttachCode={handleAttachCode}
onKeyDown={handleEditorKeyDown}
/>
</div>
<div className="flex flex-col md:pl-4">
<button
onClick={() => setIsCodeModalOpen(true)}
className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600 mb-2 md:mb-0"
>
Attach Code
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 mt-2 md:mt-0"
onClick={handleSend}
>
Send
</button>
</div>
</div>
</div>
{/* ...other components... */}
</div>
Changes Explained:
flex flex-col md:flex-row: Stacks the editor and buttons vertically on small screens and horizontally on medium and larger screens.
flex-1: Ensures the editor takes up available space.
- Margin Adjustments (
mb-4 md:mb-0, mb-2 md:mb-0, mt-2 md:mt-0): Adds spacing between buttons and editor on smaller screens while removing it on larger screens where they are side by side.
4. Full Updated Code Snippets
Updated ChatInterface.js
// src/components/ChatInterface.js
import React, { useState, useContext, useRef, useEffect, useCallback } from "react";
import { ChatContext } from "../context/ChatContext";
import Message from "./Message";
import CodeModal from "./CodeModal";
import InlineCodeEditor from "./InlineCodeEditor";
import { escapeHtml } from "../utils/escapeHtml";
function ChatInterface() {
const {
chats,
currentChatId,
addMessage,
updateChat,
selectedModelId,
models,
} = useContext(ChatContext);
const currentChat = chats.find((chat) => chat.id === currentChatId);
const [message, setMessage] = useState("");
const [isTyping, setIsTyping] = useState(false);
const messagesEndRef = useRef(null);
const [isCodeModalOpen, setIsCodeModalOpen] = useState(false);
const [currentEditingCode, setCurrentEditingCode] = useState(null);
const [isSystemPromptOpen, setIsSystemPromptOpen] = useState(false);
const addCodeAttachment = ({ codeContent, fileName, notes }) => {
const escapedCode = escapeHtml(codeContent);
const escapedFileName = escapeHtml(fileName || "untitled");
const escapedNotes = escapeHtml(notes || "");
const codeTag = `<code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCode}</code>`;
setMessage((prev) => prev + codeTag);
};
const handleAttachCode = useCallback((codeSegment = null) => {
setCurrentEditingCode(codeSegment);
setIsCodeModalOpen(true);
}, []);
const handleCodeSave = (updatedCode) => {
if (currentEditingCode) {
// Update existing code
const escapedCode = escapeHtml(updatedCode.codeContent);
const escapedFileName = escapeHtml(updatedCode.fileName || "untitled");
const escapedNotes = escapeHtml(updatedCode.notes || "");
// Improved regex to handle multi-line and special characters
const regex = new RegExp(
`<code\\s+fileName="${currentEditingCode.fileName}"\\s+notes="${currentEditingCode.notes}">([\\s\\S]*?)<\\/code>`
);
const updatedMessage = message.replace(
regex,
`<code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCode}</code>`
);
setMessage(updatedMessage);
} else {
// Add new code
addCodeAttachment(updatedCode);
}
setIsCodeModalOpen(false);
setCurrentEditingCode(null);
};
const handleSend = useCallback(async () => {
if (!message.trim() || !currentChatId || !selectedModelId) return;
// Retrieve the system prompt from the current chat
const systemPrompt = currentChat.systemPrompt || "";
// Combine the system prompt with the user message
// Ensure there's a separator (like a newline) for clarity
const fullMessage = systemPrompt ? `${systemPrompt}\n${message}` : message;
const userMessage = { sender: "user", text: message };
addMessage(currentChatId, userMessage);
setMessage("");
scrollToBottom();
// Set typing indicator
setIsTyping(true);
try {
const response = await fetch("http://localhost:8000/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: fullMessage,
model_id: selectedModelId, // Ensure this is correctly set
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.detail || "Failed to get response from the server."
);
}
const data = await response.json();
const responseText = data.response;
const responseModelId = data.model_id; // Extract model_id from response
const botMessage = {
sender: "bot",
text: responseText,
model_id: responseModelId, // Include model_id
};
addMessage(currentChatId, botMessage);
scrollToBottom();
} catch (error) {
console.error("Error:", error);
const errorMessage = {
sender: "bot",
text: "Sorry, something went wrong. Please try again.",
};
addMessage(currentChatId, errorMessage);
scrollToBottom();
} finally {
// Remove typing indicator
setIsTyping(false);
}
}, [message, currentChatId, selectedModelId, addMessage, currentChat]);
const handleKeyDown = useCallback(
(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
},
[handleSend]
);
const handleEditorKeyDown = useCallback(
(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
},
[handleSend]
);
const scrollToBottom = useCallback(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, []);
if (!currentChat) {
return (
<div className="flex-1 p-4">No active chat. Please start a new chat.</div>
);
}
const handleSystemPromptChange = (e) => {
const newPrompt = e.target.value;
updateChat(currentChatId, { systemPrompt: newPrompt });
};
const toggleSystemPrompt = () => {
setIsSystemPromptOpen(!isSystemPromptOpen);
};
return (
<div className="flex flex-col h-screen">
<div className="flex-1 p-32 pt-8 pb-8 overflow-y-auto bg-[#eeeeee] dark:bg-[#161618]">
{/* Chat Messages */}
{currentChat.messages.map((msg, index) => (
<Message
key={index}
chatId={currentChatId}
messageIndex={index}
sender={msg.sender}
text={msg.text}
model_id={msg.model_id} // Pass model_id
/>
))}
{isTyping && (
<div className="mb-4 flex justify-start">
<div className="max-w-xs md:max-w-md lg:max-w-lg p-3 rounded-lg bg-gray-200 dark:bg-gray-800 text-gray-800 dark:text-gray-200 flex items-center">
<div className="flex space-x-1 mr-2">
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-0"></div>
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-200"></div>
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-400"></div>
</div>
<span className="text-sm">Echo is typing...</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
<div
id="message_area"
className="p-4 border-t dark:border-gray-700 bg-white dark:bg-[#161618]"
>
<button
onClick={toggleSystemPrompt}
className="mb-2 text-sm text-blue-500 hover:underline focus:outline-none"
>
{isSystemPromptOpen ? "Hide System Prompt" : "Show System Prompt"}
</button>
{isSystemPromptOpen && (
<textarea
className="w-full p-2 border rounded-lg resize-none dark:bg-gray-800 dark:text-gray-200 mb-2"
rows="3"
placeholder="Enter system prompt..."
value={currentChat.systemPrompt}
onChange={handleSystemPromptChange}
/>
)}
{/* Updated Flex Container for Editor and Buttons */}
<div className="flex flex-col md:flex-row">
{/* Editor */}
<div className="flex-1 mb-4 md:mb-0">
<InlineCodeEditor
value={message}
onChange={setMessage}
onAttachCode={handleAttachCode}
onKeyDown={handleEditorKeyDown}
/>
</div>
{/* Buttons */}
<div className="flex flex-col md:pl-4 space-y-2">
<button
onClick={() => setIsCodeModalOpen(true)}
className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600"
>
Attach Code
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600"
onClick={handleSend}
>
Send
</button>
</div>
</div>
</div>
{/* Code Modal */}
{isCodeModalOpen && (
<CodeModal
onClose={() => {
setIsCodeModalOpen(false);
setCurrentEditingCode(null);
}}
onSave={handleCodeSave}
initialData={currentEditingCode}
/>
)}
</div>
);
}
export default ChatInterface;
Updated InlineCodeEditor.js
// src/components/InlineCodeEditor.js
import React, { useRef, useEffect, useCallback } from 'react';
import CodeAttachmentBubble from './CodeAttachmentBubble';
import { renderCodeBubble } from '../utils/renderCodeBubble';
function InlineCodeEditor({ value, onChange, onAttachCode }) {
const editorRef = useRef(null);
useEffect(() => {
if (editorRef.current && editorRef.current.innerHTML !== formatContent(value)) {
editorRef.current.innerHTML = formatContent(value);
}
}, [value]);
const formatContent = (content) => {
return content.replace(/<code([^>]*)>([\s\S]*?)<\/code>/g, (match, attributes, code) => {
const fileName = attributes.match(/fileName="([^"]*)"/)?.[1] || 'Untitled';
const notes = attributes.match(/notes="([^"]*)"/)?.[1] || '';
// Pass the actual codeContent to renderCodeBubble
return renderCodeBubble(fileName, notes, code);
});
};
const handleInput = useCallback(() => {
if (editorRef.current) {
const content = editorRef.current.innerHTML;
const plainText = content.replace(/<span class="code-bubble"[^>]*>[^<]*<\/span>/g, (match) => {
const fileName = match.match(/data-filename="([^"]*)"/)?.[1];
const notes = match.match(/data-notes="([^"]*)"/)?.[1];
const codeContentEscaped = match.match(/data-codecontent="([^"]*)"/)?.[1];
// Unescape the codeContent
const codeContent = codeContentEscaped ? decodeURIComponent(codeContentEscaped) : '';
return `<code fileName="${fileName}" notes="${notes}">${codeContent}</code>`;
});
onChange(plainText);
}
}, [onChange]);
const handleKeyDown = useCallback((e) => {
if (e.key === 'Enter') {
if (e.shiftKey) {
// Allow Shift+Enter to insert a newline
// Let the event propagate naturally
} else {
// Prevent default behavior and emit a custom event or handle sending the message
// Here, you might want to trigger the send action if needed
// For InlineCodeEditor, we’ll allow the parent to handle message sending
// by not preventing default here
}
}
}, []);
const handlePaste = (e) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
document.execCommand('insertText', false, text);
};
const handleBubbleClick = useCallback((e) => {
if (e.target.classList.contains('code-bubble')) {
const fileName = e.target.getAttribute('data-filename');
const notes = e.target.getAttribute('data-notes');
const codeContentEscaped = e.target.getAttribute('data-codecontent');
const codeContent = codeContentEscaped ? decodeURIComponent(codeContentEscaped) : '';
onAttachCode({ fileName, notes, codeContent });
}
}, [onAttachCode]);
return (
<div className="relative border rounded-lg p-2 bg-white dark:bg-[#18181b] text-black dark:text-white">
<div
ref={editorRef}
className="w-full min-h-[100px] max-h-[300px] overflow-y-auto p-2 focus:outline-none break-words"
contentEditable
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onClick={handleBubbleClick}
role="textbox"
aria-multiline="true"
aria-label="Code Editor"
/>
</div>
);
}
export default InlineCodeEditor;
5. Additional Recommendations
-
Responsive Design: The updated layout ensures that on smaller screens, the editor and buttons stack vertically, preserving usability on mobile devices.
-
Accessibility: Ensure that all interactive elements are accessible via keyboard and screen readers. You've already included aria-label and appropriate roles, which is excellent.
-
Testing: After making these changes, thoroughly test the layout across different devices and screen sizes to ensure the desired behavior.
-
Customization: Adjust padding, margins, and sizes as needed to better fit your application's design language.
6. Visual Representation
Here's a simplified visualization of the updated layout:
---------------------------------------------------------
| Chat Messages [x] |
| +--------+
| | Inline |
| | Editor |
| +--------+
| [Attach Code] [Send] | Buttons |
---------------------------------------------------------
- Editor: Expands to fill available space.
- Buttons: Positioned to the right of the editor, maintaining their size and not pushing the editor.
7. Final Thoughts
By properly configuring the Flexbox properties and ensuring that the child elements have the correct growth and shrink behaviors, you can create a responsive and flexible input area that adapts to different screen sizes and content lengths. The key is to allow the editor to take up available space while keeping the buttons at their natural sizes.
Feel free to further customize the styles to better match your application's design requirements.