File size: 13,826 Bytes
d5c104e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
import React, { useRef, useState, useCallback, useEffect } from 'react';
import Box from '@mui/material/Box';
import Snackbar from '@mui/material/Snackbar';
import Slide from '@mui/material/Slide';
import IconButton from '@mui/material/IconButton';
import { FaTimes, FaSpinner, FaCheckCircle } from 'react-icons/fa';
import GraphDialog from './ChatComponents/Graph';
import Streaming from './ChatComponents/Streaming';
import SourcePopup from './ChatComponents/SourcePopup';
import './ChatWindow.css';
import bot from '../../Icons/bot.png';
import copy from '../../Icons/copy.png';
import evaluate from '../../Icons/evaluate.png';
import sourcesIcon from '../../Icons/sources.png';
import graphIcon from '../../Icons/graph.png';
import user from '../../Icons/user.png';
import excerpts from '../../Icons/excerpts.png';
// SlideTransition function for both entry and exit transitions.
function SlideTransition(props) {
return <Slide {...props} direction="up" />;
}
function ChatWindow({
blockId,
userMessage,
tokenChunks,
aiAnswer,
thinkingTime,
thoughtLabel,
sourcesRead,
finalSources,
excerptsData,
isLoadingExcerpts,
onFetchExcerpts,
actions,
tasks,
openRightSidebar,
// openLeftSidebar,
isError,
errorMessage
}) {
console.log(`[ChatWindow ${blockId}] Received excerptsData:`, excerptsData);
const answerRef = useRef(null);
const [graphDialogOpen, setGraphDialogOpen] = useState(false);
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [hoveredSourceInfo, setHoveredSourceInfo] = useState(null);
const popupTimeoutRef = useRef(null);
// Get the graph action from the actions prop.
const graphAction = actions && actions.find(a => a.name === "graph");
// Handler for copying answer to clipboard.
const handleCopy = () => {
if (answerRef.current) {
const textToCopy = answerRef.current.innerText || answerRef.current.textContent;
navigator.clipboard.writeText(textToCopy)
.then(() => {
console.log('Copied to clipboard:', textToCopy);
setSnackbarOpen(true);
})
.catch((err) => console.error('Failed to copy text:', err));
}
};
// Snackbar close handler
const handleSnackbarClose = (event, reason) => {
if (reason === 'clickaway') return;
setSnackbarOpen(false);
};
// Combine partial chunks (tokenChunks) if present; else fall back to the aiAnswer string.
const combinedAnswer = (tokenChunks && tokenChunks.length > 0)
? tokenChunks.join("")
: aiAnswer;
const hasTokens = combinedAnswer && combinedAnswer.length > 0;
// Assume streaming is in progress if thinkingTime is not set.
const isStreaming = thinkingTime === null || thinkingTime === undefined;
// Helper to render the thought label.
const renderThoughtLabel = () => {
if (!hasTokens) {
return thoughtLabel;
} else {
if (thoughtLabel && thoughtLabel.startsWith("Thought and searched for")) {
return thoughtLabel;
}
return null;
}
};
// Helper to render sources read.
const renderSourcesRead = () => {
if (!sourcesRead && sourcesRead !== 0) return null;
return sourcesRead;
};
// When tasks first appear, automatically open the sidebar.
const prevTasksRef = useRef(tasks);
useEffect(() => {
if (prevTasksRef.current.length === 0 && tasks && tasks.length > 0) {
openRightSidebar("tasks", blockId);
}
prevTasksRef.current = tasks;
}, [tasks, blockId, openRightSidebar]);
// Handle getting the reference to the content for copy functionality
const handleContentRef = (ref) => {
answerRef.current = ref;
};
// Handle showing the source popup
const showSourcePopup = useCallback((sourceIndex, targetElement, statementText) => {
// Clear any existing timeout to prevent flickering
if (popupTimeoutRef.current) {
clearTimeout(popupTimeoutRef.current);
popupTimeoutRef.current = null;
}
if (!finalSources || !finalSources[sourceIndex] || !targetElement) return;
const rect = targetElement.getBoundingClientRect();
const scrollY = window.scrollY || window.pageYOffset;
const scrollX = window.scrollX || window.pageXOffset;
const newHoverInfo = {
index: sourceIndex,
statementText,
position: {
top: rect.top + scrollY - 10, // Position above the reference
left: rect.left + scrollX + rect.width / 2, // Center horizontally
}
};
setHoveredSourceInfo(newHoverInfo);
}, [finalSources]);
const hideSourcePopup = useCallback(() => {
if (popupTimeoutRef.current) {
clearTimeout(popupTimeoutRef.current); // Clear existing timeout if mouse leaves quickly
}
popupTimeoutRef.current = setTimeout(() => {
setHoveredSourceInfo(null);
popupTimeoutRef.current = null;
}, 15); // Delay allows moving mouse onto popup
}, []);
// Handle mouse enter on the popup to cancel the hide timeout
const cancelHidePopup = useCallback(() => {
// Clear the hide timeout if the mouse enters the popup itself
if (popupTimeoutRef.current) {
clearTimeout(popupTimeoutRef.current);
popupTimeoutRef.current = null;
}
}, []);
// Determine button state and appearance for excerpts icon
const excerptsLoaded = !!excerptsData; // True if excerptsData is not null/empty
const canFetchExcerpts = finalSources && finalSources.length > 0 &&
!isError && !excerptsLoaded && !isLoadingExcerpts;
const buttonDisabled = isLoadingExcerpts || excerptsLoaded; // Disable button if loading or loaded
const buttonIcon = isLoadingExcerpts
? <FaSpinner className="spin" style={{ fontSize: 20 }} />
: excerptsLoaded
? <FaCheckCircle
style={{
width: 22,
height: 22,
color: 'var(--secondary-color)',
filter: 'brightness(0.75)'
}}
/>
: <img src={excerpts} alt="excerpts icon" />;
const buttonClassName = `excerpts-icon ${isLoadingExcerpts ? 'loading' : ''} ${excerptsLoaded ? 'loaded' : ''}`;
return (
<>
{ !hasTokens ? (
// If no tokens, render pre-stream UI.
(!isError && thoughtLabel) ? (
<div className="answer-container">
{/* User Message */}
<div className="message-row user-message">
<div className="message-bubble user-bubble">
<p className="question">{userMessage}</p>
</div>
<div className="user-icon">
<img src={user} alt="user icon" />
</div>
</div>
{/* Bot Message (pre-stream with spinner) */}
<div className="message-row bot-message pre-stream">
<div className="bot-container">
<div className="thinking-info">
<Box mt={1} display="flex" alignItems="center">
<Box className="custom-spinner" />
<Box ml={1}>
<span
className="thinking-time"
onClick={() => openRightSidebar("tasks", blockId)}
>
{thoughtLabel}
</span>
</Box>
</Box>
</div>
</div>
</div>
</div>
) : (
// Render without spinner (user message only)
<div className="answer-container">
<div className="message-row user-message">
<div className="message-bubble user-bubble">
<p className="question">{userMessage}</p>
</div>
<div className="user-icon">
<img src={user} alt="user icon" />
</div>
</div>
</div>
)
) : (
// Render Full Chat Message
<div className="answer-container">
{/* User Message */}
<div className="message-row user-message">
<div className="message-bubble user-bubble">
<p className="question">{userMessage}</p>
</div>
<div className="user-icon">
<img src={user} alt="user icon" />
</div>
</div>
{/* Bot Message */}
<div className="message-row bot-message">
<div className="bot-container">
{!isError && renderThoughtLabel() && (
<div className="thinking-info">
<span
className="thinking-time"
onClick={() => openRightSidebar("tasks", blockId)}
>
{renderThoughtLabel()}
</span>
</div>
)}
{renderSourcesRead() !== null && (
<div className="sources-read-container">
<p className="sources-read">
Sources Read: {renderSourcesRead()}
</p>
</div>
)}
<div className="answer-block">
<div className="bot-icon">
<img src={bot} alt="bot icon" />
</div>
<div className="message-bubble bot-bubble">
<div className="answer">
<Streaming
content={combinedAnswer}
isStreaming={isStreaming}
onContentRef={handleContentRef}
showSourcePopup={showSourcePopup}
hideSourcePopup={hideSourcePopup}
/>
</div>
</div>
<div className="post-icons">
{!isStreaming && (
<div className="copy-icon" onClick={handleCopy}>
<img src={copy} alt="copy icon" />
<span className="tooltip">Copy</span>
</div>
)}
{actions && actions.some(a => a.name === "evaluate") && (
<div className="evaluate-icon" onClick={() => openRightSidebar("evaluate", blockId)}>
<img src={evaluate} alt="evaluate icon" />
<span className="tooltip">Evaluate</span>
</div>
)}
{actions && actions.some(a => a.name === "sources") && (
<div className="sources-icon" onClick={() => openRightSidebar("sources", blockId)}>
<img src={sourcesIcon} alt="sources icon" />
<span className="tooltip">Sources</span>
</div>
)}
{actions && actions.some(a => a.name === "graph") && (
<div className="graph-icon" onClick={() => setGraphDialogOpen(true)}>
<img src={graphIcon} alt="graph icon" />
<span className="tooltip">View Graph</span>
</div>
)}
{/* Show Excerpts Button - Conditionally Rendered */}
{finalSources && finalSources.length > 0 && !isError && (
<div
className={buttonClassName}
onClick={() => canFetchExcerpts && onFetchExcerpts(blockId)}
style={{
cursor: buttonDisabled ? 'default' : 'pointer',
opacity: excerptsLoaded ? 0.6 : 1
}}
>
{buttonIcon}
<span className="tooltip">
{excerptsLoaded ? 'Excerpts Loaded'
: isLoadingExcerpts ? 'Loading Excerpts…'
: 'Show Excerpts'}
</span>
</div>
)}
</div>
</div>
</div>
</div>
{/* Render the GraphDialog when graphDialogOpen is true */}
{graphDialogOpen && (
<GraphDialog
open={graphDialogOpen}
onClose={() => setGraphDialogOpen(false)}
payload={graphAction ? graphAction.payload : { query: userMessage }}
/>
)}
</div>
)}
{/* Render Source Popup */}
{hoveredSourceInfo && finalSources && finalSources[hoveredSourceInfo.index] && (
<SourcePopup
sourceData={finalSources[hoveredSourceInfo.index]}
excerptsData={excerptsData}
position={hoveredSourceInfo.position}
onMouseEnter={cancelHidePopup} // Keep popup open if mouse enters it
onMouseLeave={hideSourcePopup}
statementText={hoveredSourceInfo.statementText}
/>
)}
{/* Render error container if there's an error */}
{isError && (
<div className="error-block" style={{ marginTop: '1rem' }}>
<h3>Error</h3>
<p>{errorMessage}</p>
</div>
)}
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={handleSnackbarClose}
message="Copied To Clipboard"
anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
TransitionComponent={SlideTransition}
ContentProps={{ classes: { root: 'custom-snackbar' } }}
action={
<IconButton
size="small"
aria-label="close"
color="inherit"
onClick={handleSnackbarClose}
>
<FaTimes />
</IconButton>
}
/>
</>
);
}
export default ChatWindow; |