Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | import { useState, useEffect, useRef, useCallback, useMemo, type MutableRefObject, type RefObject, type CSSProperties } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { List, type ListImperativeAPI } from 'react-window'; import { useChatStore, Message } from '../store/chatStore'; import { useConnectionStore } from '../store/connectionStore'; import { useAgentStore } from '../store/agentStore'; import { useConfigStore } from '../store/configStore'; import { Paperclip, ChevronDown, Terminal, SquarePen, ArrowUp, MessageSquare, Download, Copy, Check } from 'lucide-react'; import { Button, EmptyState, MessageListSkeleton, LoadingDots } from './ui'; import { listItemVariants, defaultTransition, fadeInVariants } from '../lib/animations'; import { FirstConversationPrompt } from './FirstConversationPrompt'; import { MessageSearch } from './MessageSearch'; import { OfflineIndicator } from './OfflineIndicator'; import { useVirtualizedMessages, type VirtualizedMessageItem } from '../lib/message-virtualization'; // Default heights for virtualized messages const DEFAULT_MESSAGE_HEIGHTS: Record<string, number> = { user: 80, assistant: 150, tool: 120, hand: 120, workflow: 100, system: 60, }; // Threshold for enabling virtualization (messages count) const VIRTUALIZATION_THRESHOLD = 100; export function ChatArea() { const { messages, currentAgent, isStreaming, isLoading, currentModel, sendMessage: sendToGateway, setCurrentModel, initStreamListener, newConversation, } = useChatStore(); const connectionState = useConnectionStore((s) => s.connectionState); const clones = useAgentStore((s) => s.clones); const models = useConfigStore((s) => s.models); const [input, setInput] = useState(''); const [showModelPicker, setShowModelPicker] = useState(false); const scrollRef = useRef<HTMLDivElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null); const messageRefs = useRef<Map<string, HTMLDivElement>>(new Map()); // Convert messages to virtualization format const virtualizedMessages: VirtualizedMessageItem[] = useMemo( () => messages.map((msg) => ({ id: msg.id, height: DEFAULT_MESSAGE_HEIGHTS[msg.role] ?? 100, role: msg.role, })), [messages] ); // Use virtualization hook const { listRef, getHeight, setHeight, scrollToBottom, } = useVirtualizedMessages(virtualizedMessages, DEFAULT_MESSAGE_HEIGHTS); // Whether to use virtualization const useVirtualization = messages.length >= VIRTUALIZATION_THRESHOLD; // Get current clone for first conversation prompt const currentClone = useMemo(() => { if (!currentAgent) return null; return clones.find((c) => c.id === currentAgent.id) || null; }, [currentAgent, clones]); // Check if should show first conversation prompt const showFirstPrompt = messages.length === 0 && currentClone && !currentClone.onboardingCompleted; // Handle suggestion click from first conversation prompt const handleSelectSuggestion = (text: string) => { setInput(text); textareaRef.current?.focus(); }; // Auto-resize textarea const adjustTextarea = useCallback(() => { const el = textareaRef.current; if (el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 160) + 'px'; } }, []); // Init agent stream listener on mount useEffect(() => { const unsub = initStreamListener(); return unsub; }, []); // Auto-scroll to bottom on new messages useEffect(() => { if (scrollRef.current && !useVirtualization) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } else if (useVirtualization && messages.length > 0) { scrollToBottom(); } }, [messages, useVirtualization, scrollToBottom]); const handleSend = () => { if (!input.trim() || isStreaming) return; // Allow sending in offline mode - message will be queued sendToGateway(input); setInput(''); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; const connected = connectionState === 'connected'; // Navigate to a specific message by ID const handleNavigateToMessage = useCallback((messageId: string) => { const messageEl = messageRefs.current.get(messageId); if (messageEl && scrollRef.current) { messageEl.scrollIntoView({ behavior: 'smooth', block: 'center' }); // Add highlight effect messageEl.classList.add('ring-2', 'ring-orange-400', 'ring-offset-2'); setTimeout(() => { messageEl.classList.remove('ring-2', 'ring-orange-400', 'ring-offset-2'); }, 2000); } }, []); return ( <div className="flex flex-col h-full"> {/* Header */} {/* Header */} <div className="h-14 border-b border-gray-100 dark:border-gray-800 flex items-center justify-between px-6 flex-shrink-0 bg-white dark:bg-gray-900"> <div className="flex items-center gap-2"> <h2 className="font-semibold text-gray-900 dark:text-gray-100">{currentAgent?.name || 'ZCLAW'}</h2> {isStreaming ? ( <span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1"> <span className="w-1.5 h-1.5 bg-gray-500 dark:bg-gray-400 rounded-full thinking-dot"></span> 正在输入中 </span> ) : ( <span className={`text-xs flex items-center gap-1 ${connected ? 'text-green-500' : 'text-gray-500 dark:text-gray-400'}`}> <span className={`w-1.5 h-1.5 rounded-full ${connected ? 'bg-green-400' : 'bg-gray-300 dark:bg-gray-600'}`}></span> {connected ? 'Gateway 已连接' : 'Gateway 未连接'} </span> )} </div> <div className="flex items-center gap-2"> {/* Offline indicator in header */} <OfflineIndicator compact /> {messages.length > 0 && ( <MessageSearch onNavigateToMessage={handleNavigateToMessage} /> )} {messages.length > 0 && ( <Button variant="ghost" size="sm" onClick={newConversation} title="新对话" aria-label="开始新对话" className="flex items-center gap-1.5 text-gray-500 dark:text-gray-400 hover:text-orange-600 dark:hover:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20" > <SquarePen className="w-3.5 h-3.5" /> 新对话 </Button> )} </div> </div> {/* Messages */} <div ref={scrollRef} className="flex-1 overflow-y-auto custom-scrollbar bg-white dark:bg-gray-900"> <AnimatePresence mode="popLayout"> {/* Loading skeleton */} {isLoading && messages.length === 0 && ( <motion.div key="loading-skeleton" variants={fadeInVariants} initial="initial" animate="animate" exit="exit" > <MessageListSkeleton count={3} /> </motion.div> )} {/* Empty state */} {!isLoading && messages.length === 0 && ( <motion.div key="empty-state" variants={fadeInVariants} initial="initial" animate="animate" exit="exit" > {showFirstPrompt && currentClone ? ( <FirstConversationPrompt clone={currentClone} onSelectSuggestion={handleSelectSuggestion} /> ) : ( <EmptyState icon={<MessageSquare className="w-8 h-8" />} title="Welcome to ZCLAW" description={connected ? 'Send a message to start the conversation.' : 'Please connect to Gateway first in Settings.'} /> )} </motion.div> )} {/* Virtualized list for large message counts, smooth scroll for small counts */} {useVirtualization && messages.length > 0 ? ( <VirtualizedMessageList messages={messages} listRef={listRef} getHeight={getHeight} onHeightChange={setHeight} messageRefs={messageRefs} /> ) : ( messages.map((message) => ( <motion.div key={message.id} ref={(el) => { if (el) messageRefs.current.set(message.id, el); }} variants={listItemVariants} initial="hidden" animate="visible" layout transition={defaultTransition} > <MessageBubble message={message} /> </motion.div> )) )} </AnimatePresence> </div> {/* Input */} <div className="border-t border-gray-100 dark:border-gray-800 p-4 bg-white dark:bg-gray-900"> <div className="max-w-4xl mx-auto"> <div className="relative flex items-end gap-2 bg-gray-50 dark:bg-gray-800 rounded-2xl border border-gray-200 dark:border-gray-700 p-2 focus-within:border-orange-300 dark:focus-within:border-orange-600 focus-within:ring-2 focus-within:ring-orange-100 dark:focus-within:ring-orange-900/30 transition-all"> <Button variant="ghost" size="sm" className="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" aria-label="添加附件" > <Paperclip className="w-5 h-5" /> </Button> <div className="flex-1 py-1"> <textarea ref={textareaRef} value={input} onChange={(e) => { setInput(e.target.value); adjustTextarea(); }} onKeyDown={handleKeyDown} placeholder={ isStreaming ? 'Agent 正在回复...' : `发送给 ${currentAgent?.name || 'ZCLAW'}${!connected ? ' (离线模式)' : ''}` } disabled={isStreaming} rows={1} className="w-full bg-transparent border-none focus:outline-none text-gray-700 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 disabled:opacity-50 resize-none leading-relaxed mt-1" style={{ minHeight: '24px', maxHeight: '160px' }} /> </div> <div className="flex items-center gap-2 pr-2 pb-1 relative"> <Button variant="ghost" size="sm" onClick={() => setShowModelPicker(!showModelPicker)} className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700" aria-label="选择模型" aria-expanded={showModelPicker} > <span>{currentModel}</span> <ChevronDown className="w-3 h-3" /> </Button> {showModelPicker && ( <div className="absolute bottom-full right-8 mb-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 min-w-[160px] max-h-48 overflow-y-auto z-10"> {models.length > 0 ? ( models.map((model) => ( <button key={model.id} onClick={() => { setCurrentModel(model.id); setShowModelPicker(false); }} className={`w-full text-left px-3 py-2 text-xs hover:bg-gray-50 dark:hover:bg-gray-700 ${model.id === currentModel ? 'text-orange-600 dark:text-orange-400 font-medium' : 'text-gray-700 dark:text-gray-300'}`} > {model.name} </button> )) ) : ( <div className="px-3 py-2 text-xs text-gray-400"> {connected ? '加载中...' : '未连接 Gateway'} </div> )} </div> )} <Button variant="primary" size="sm" onClick={handleSend} disabled={isStreaming || !input.trim()} className="w-8 h-8 rounded-full p-0 flex items-center justify-center bg-orange-500 hover:bg-orange-600 text-white disabled:opacity-50" aria-label="发送消息" > <ArrowUp className="w-4 h-4 text-white" /> </Button> </div> </div> <div className="text-center mt-2 text-xs text-gray-500 dark:text-gray-400"> Agent 在本地运行,内容由 AI 生成 </div> </div> </div> </div> ); } /** Code block with copy and download functionality */ function CodeBlock({ code, language, index }: { code: string; language: string; index: number }) { const [copied, setCopied] = useState(false); const [downloading, setDownloading] = useState(false); // Infer filename from language or content const inferFilename = (): string => { const extMap: Record<string, string> = { javascript: 'js', typescript: 'ts', python: 'py', rust: 'rs', go: 'go', java: 'java', cpp: 'cpp', c: 'c', csharp: 'cs', html: 'html', css: 'css', scss: 'scss', json: 'json', yaml: 'yaml', yml: 'yaml', xml: 'xml', sql: 'sql', shell: 'sh', bash: 'sh', powershell: 'ps1', markdown: 'md', md: 'md', dockerfile: 'dockerfile', }; // Check if language contains a filename (e.g., ```app.tsx) if (language.includes('.') || language.includes('/')) { return language; } // Check for common patterns in code const codeLower = code.toLowerCase(); if (codeLower.includes('<!doctype html') || codeLower.includes('<html')) { return 'index.html'; } if (codeLower.includes('package.json') || (codeLower.includes('"name"') && codeLower.includes('"version"'))) { return 'package.json'; } if (codeLower.startsWith('{') && (codeLower.includes('"import"') || codeLower.includes('"export"'))) { return 'config.json'; } // Use language extension const ext = extMap[language.toLowerCase()] || language.toLowerCase(); return `code-${index + 1}.${ext || 'txt'}`; }; const handleCopy = async () => { try { await navigator.clipboard.writeText(code); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (err) { console.error('Failed to copy:', err); } }; const handleDownload = () => { setDownloading(true); try { const filename = inferFilename(); const blob = new Blob([code], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } catch (err) { console.error('Failed to download:', err); } setTimeout(() => setDownloading(false), 500); }; return ( <div className="relative group my-2"> <pre className="bg-gray-900 text-gray-100 rounded-lg p-3 overflow-x-auto text-xs font-mono leading-relaxed"> {language && ( <div className="text-gray-500 text-[10px] mb-1 uppercase flex items-center justify-between"> <span>{language}</span> </div> )} <code>{code}</code> </pre> {/* Action buttons - show on hover */} <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity"> <button onClick={handleCopy} className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300 hover:text-white transition-colors" title="复制代码" > {copied ? <Check className="w-3.5 h-3.5 text-green-400" /> : <Copy className="w-3.5 h-3.5" />} </button> <button onClick={handleDownload} className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300 hover:text-white transition-colors" title="下载文件" disabled={downloading} > <Download className={`w-3.5 h-3.5 ${downloading ? 'animate-pulse' : ''}`} /> </button> </div> </div> ); } /** Lightweight markdown renderer — handles code blocks, inline code, bold, italic, links */ function sanitizeUrl(url: string): string { const safeProtocols = ['http:', 'https:', 'mailto:']; try { const parsed = new URL(url, window.location.origin); if (safeProtocols.includes(parsed.protocol)) { return parsed.href; } } catch { // Invalid URL } return '#'; } function renderMarkdown(text: string): React.ReactNode[] { const nodes: React.ReactNode[] = []; const lines = text.split('\n'); let i = 0; while (i < lines.length) { const line = lines[i]; // Fenced code block if (line.startsWith('```')) { const lang = line.slice(3).trim(); const codeLines: string[] = []; i++; while (i < lines.length && !lines[i].startsWith('```')) { codeLines.push(lines[i]); i++; } i++; // skip closing ``` nodes.push( <CodeBlock key={nodes.length} code={codeLines.join('\n')} language={lang} index={nodes.length} /> ); continue; } // Normal line — parse inline markdown nodes.push( <span key={nodes.length}> {i > 0 && lines[i - 1] !== undefined && !nodes[nodes.length - 1]?.toString().includes('pre') && '\n'} {renderInline(line)} </span> ); i++; } return nodes; } function renderInline(text: string): React.ReactNode[] { const parts: React.ReactNode[] = []; // Pattern: **bold**, *italic*, `code`, [text](url) const regex = /(\*\*(.+?)\*\*)|(\*(.+?)\*)|(`(.+?)`)|(\[(.+?)\]\((.+?)\))/g; let lastIndex = 0; let match: RegExpExecArray | null; while ((match = regex.exec(text)) !== null) { // Text before match if (match.index > lastIndex) { parts.push(text.slice(lastIndex, match.index)); } if (match[1]) { // **bold** parts.push(<strong key={parts.length} className="font-semibold">{match[2]}</strong>); } else if (match[3]) { // *italic* parts.push(<em key={parts.length}>{match[4]}</em>); } else if (match[5]) { // `code` parts.push( <code key={parts.length} className="bg-gray-100 dark:bg-gray-700 text-orange-700 dark:text-orange-400 px-1 py-0.5 rounded text-[0.85em] font-mono"> {match[6]} </code> ); } else if (match[7]) { // [text](url) - 使用 sanitizeUrl 防止 XSS parts.push( <a key={parts.length} href={sanitizeUrl(match[9])} target="_blank" rel="noopener noreferrer" className="text-orange-600 dark:text-orange-400 underline hover:text-orange-700 dark:hover:text-orange-300">{match[8]}</a> ); } lastIndex = match.index + match[0].length; } if (lastIndex < text.length) { parts.push(text.slice(lastIndex)); } return parts.length > 0 ? parts : [text]; } function MessageBubble({ message }: { message: Message }) { if (message.role === 'tool') { return ( <div className="ml-12 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 text-xs font-mono"> <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1"> <Terminal className="w-3.5 h-3.5" /> <span className="font-semibold">{message.toolName || 'tool'}</span> </div> {message.toolInput && ( <pre className="text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-900 rounded p-2 mb-1 overflow-x-auto">{message.toolInput}</pre> )} {message.content && ( <pre className="text-green-700 dark:text-green-400 bg-white dark:bg-gray-900 rounded p-2 overflow-x-auto">{message.content}</pre> )} </div> ); } const isUser = message.role === 'user'; // 思考中状态:streaming 且内容为空时显示思考指示器 const isThinking = message.streaming && !message.content; // Download message as Markdown file const handleDownloadMessage = () => { if (!message.content) return; const timestamp = new Date().toISOString().slice(0, 10); const filename = `message-${timestamp}.md`; const blob = new Blob([message.content], { type: 'text/markdown;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; return ( <div className={`flex gap-4 ${isUser ? 'justify-end' : ''}`}> <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${isUser ? 'bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-200 order-last' : 'agent-avatar text-white'}`} > {isUser ? '用' : 'Z'} </div> <div className={isUser ? 'max-w-2xl' : 'flex-1 max-w-3xl'}> {isThinking ? ( // Thinking indicator <div className="flex items-center gap-2 px-4 py-3 text-gray-500 dark:text-gray-400"> <LoadingDots /> <span className="text-sm">Thinking...</span> </div> ) : ( <div className={`p-4 shadow-sm ${isUser ? 'chat-bubble-user shadow-md' : 'chat-bubble-assistant'} relative group`}> <div className={`leading-relaxed whitespace-pre-wrap ${isUser ? 'text-white' : 'text-gray-700 dark:text-gray-200'}`}> {message.content ? (isUser ? message.content : renderMarkdown(message.content)) : '...'} {message.streaming && <span className="inline-block w-1.5 h-4 bg-orange-500 animate-pulse ml-0.5 align-text-bottom rounded-sm" />} </div> {message.error && ( <p className="text-xs text-red-500 mt-2">{message.error}</p> )} {/* Download button for AI messages - show on hover */} {!isUser && message.content && !message.streaming && ( <button onClick={handleDownloadMessage} className="absolute top-2 right-2 p-1.5 bg-gray-200/80 dark:bg-gray-700/80 hover:bg-gray-300 dark:hover:bg-gray-600 rounded text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors opacity-0 group-hover:opacity-100" title="下载为 Markdown" > <Download className="w-3.5 h-3.5" /> </button> )} </div> )} </div> </div> ); } // === Virtualized Message Components === interface VirtualizedMessageRowProps { message: Message; onHeightChange: (height: number) => void; messageRefs: MutableRefObject<Map<string, HTMLDivElement>>; } /** * Single row in the virtualized list. * Measures actual height after render and reports back. */ function VirtualizedMessageRow({ message, onHeightChange, messageRefs, style, ariaAttributes, }: VirtualizedMessageRowProps & { style: CSSProperties; ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem'; }; }) { const rowRef = useRef<HTMLDivElement>(null); // Measure height after mount useEffect(() => { if (rowRef.current) { const height = rowRef.current.getBoundingClientRect().height; if (height > 0) { onHeightChange(height); } } }, [message.content, message.streaming, onHeightChange]); return ( <div ref={(el) => { if (el) { (rowRef as MutableRefObject<HTMLDivElement | null>).current = el; messageRefs.current.set(message.id, el); } }} style={style} className="py-3" {...ariaAttributes} > <MessageBubble message={message} /> </div> ); } interface VirtualizedMessageListProps { messages: Message[]; listRef: RefObject<ListImperativeAPI | null>; getHeight: (id: string, role: string) => number; onHeightChange: (id: string, height: number) => void; messageRefs: MutableRefObject<Map<string, HTMLDivElement>>; } /** * Virtualized message list for efficient rendering of large message counts. * Uses react-window's List with dynamic height measurement. */ function VirtualizedMessageList({ messages, listRef, getHeight, onHeightChange, messageRefs, }: VirtualizedMessageListProps) { // Row component for react-window v2 const RowComponent = (props: { ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem'; }; index: number; style: CSSProperties; }) => ( <VirtualizedMessageRow message={messages[props.index]} onHeightChange={(h) => onHeightChange(messages[props.index].id, h)} messageRefs={messageRefs} style={props.style} ariaAttributes={props.ariaAttributes} /> ); return ( <List listRef={listRef} rowComponent={RowComponent} rowProps={{}} rowHeight={(index: number) => getHeight(messages[index].id, messages[index].role)} rowCount={messages.length} defaultHeight={500} overscanCount={5} className="focus:outline-none" /> ); } |