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 | /** * Message Virtualization Utilities * * Provides efficient rendering for large message lists (10,000+ messages) * using react-window's VariableSizeList with dynamic height measurement. * * @module message-virtualization */ import { useRef, useCallback, useMemo, useEffect, type CSSProperties, type ReactNode } from 'react'; import React from 'react'; import type { ListImperativeAPI } from 'react-window'; /** * Message item interface for virtualization */ export interface VirtualizedMessageItem { id: string; height: number; role: 'user' | 'assistant' | 'tool' | 'hand' | 'workflow' | 'system'; } /** * Props for the virtualized message list component */ export interface VirtualizedMessageListProps { messages: VirtualizedMessageItem[]; renderMessage: (id: string, style: CSSProperties) => ReactNode; height: number; width: number | string; overscan?: number; onScroll?: (scrollTop: number) => void; } /** * Default estimated heights for each message type * These are used before actual measurement */ const DEFAULT_HEIGHTS: Record<string, number> = { user: 80, assistant: 150, tool: 100, hand: 120, workflow: 100, system: 60, }; /** * Hook return type for virtualized message management */ export interface UseVirtualizedMessagesReturn { /** Reference to the List instance */ listRef: React.RefObject<ListImperativeAPI | null>; /** Get the current height for a message by id and role */ getHeight: (id: string, role: string) => number; /** Update the measured height for a message */ setHeight: (id: string, height: number) => void; /** Calculate total height of all messages */ totalHeight: number; /** Scroll to the bottom of the list */ scrollToBottom: () => void; /** Scroll to a specific message index */ scrollToIndex: (index: number) => void; /** Reset height cache and recalculate */ resetCache: () => void; } /** * Hook for virtualized message rendering with dynamic height measurement. * * @param messages - Array of message items to virtualize * @param defaultHeights - Optional custom default heights per role * @returns Object containing list ref, height getters/setters, and scroll utilities * * @example * ```tsx * const { listRef, getHeight, setHeight, scrollToBottom } = useVirtualizedMessages(messages); * * // In render: * <VariableSizeList * ref={listRef} * itemCount={messages.length} * itemSize={(index) => getHeight(messages[index].id, messages[index].role)} * > * {({ index, style }) => ( * <MessageRenderer * message={messages[index]} * style={style} * onHeightChange={(h) => setHeight(messages[index].id, h)} * /> * )} * </VariableSizeList> * ``` */ export function useVirtualizedMessages( messages: VirtualizedMessageItem[], defaultHeights: Record<string, number> = DEFAULT_HEIGHTS ): UseVirtualizedMessagesReturn { const listRef = useRef<ListImperativeAPI>(null); const heightsRef = useRef<Map<string, number>>(new Map()); const prevMessagesLengthRef = useRef<number>(0); /** * Get height for a message, falling back to default for role */ const getHeight = useCallback( (id: string, role: string): number => { return heightsRef.current.get(id) ?? defaultHeights[role] ?? 100; }, [defaultHeights] ); /** * Update height when a message is measured * Triggers list recalculation if height changed */ const setHeight = useCallback((id: string, height: number): void => { const current = heightsRef.current.get(id); if (current !== height) { heightsRef.current.set(id, height); // Height updated - the list will use the new height on next render } }, []); /** * Calculate total height of all messages */ const totalHeight = useMemo((): number => { return messages.reduce( (sum, msg) => sum + getHeight(msg.id, msg.role), 0 ); }, [messages, getHeight]); /** * Scroll to the bottom of the list */ const scrollToBottom = useCallback((): void => { if (listRef.current && messages.length > 0) { listRef.current.scrollToRow({ index: messages.length - 1, align: 'end' }); } }, [messages.length]); /** * Scroll to a specific message index */ const scrollToIndex = useCallback((index: number): void => { if (listRef.current && index >= 0 && index < messages.length) { listRef.current.scrollToRow({ index, align: 'center' }); } }, [messages.length]); /** * Reset the height cache and force recalculation */ const resetCache = useCallback((): void => { heightsRef.current.clear(); }, []); /** * Auto-scroll to bottom when new messages arrive */ useEffect(() => { if (messages.length > prevMessagesLengthRef.current) { // New messages added, scroll to bottom scrollToBottom(); } prevMessagesLengthRef.current = messages.length; }, [messages.length, scrollToBottom]); return { listRef, getHeight, setHeight, totalHeight, scrollToBottom, scrollToIndex, resetCache, }; } /** * LRU Cache for rendered messages. * Useful for caching computed message data or rendered content. * * @typeParam T - Type of cached data * * @example * ```tsx * const cache = new MessageCache<ParsedMessageContent>(100); * * // Get or compute * let content = cache.get(messageId); * if (!content) { * content = parseMarkdown(message.content); * cache.set(messageId, content); * } * ``` */ export class MessageCache<T> { private cache: Map<string, { data: T; timestamp: number }>; private readonly maxSize: number; private accessOrder: string[]; constructor(maxSize: number = 100) { this.cache = new Map(); this.maxSize = maxSize; this.accessOrder = []; } /** * Get cached data by key * Updates access order for LRU eviction */ get(key: string): T | undefined { const entry = this.cache.get(key); if (entry) { // Move to end (most recently used) const index = this.accessOrder.indexOf(key); if (index > -1) { this.accessOrder.splice(index, 1); this.accessOrder.push(key); } return entry.data; } return undefined; } /** * Set cached data by key * Evicts oldest entries if at capacity */ set(key: string, data: T): void { // Remove if exists if (this.cache.has(key)) { const index = this.accessOrder.indexOf(key); if (index > -1) { this.accessOrder.splice(index, 1); } } // Evict oldest if at capacity while (this.accessOrder.length >= this.maxSize) { const oldest = this.accessOrder.shift(); if (oldest) { this.cache.delete(oldest); } } this.cache.set(key, { data, timestamp: Date.now() }); this.accessOrder.push(key); } /** * Check if key exists in cache */ has(key: string): boolean { return this.cache.has(key); } /** * Remove a specific key from cache */ delete(key: string): boolean { const index = this.accessOrder.indexOf(key); if (index > -1) { this.accessOrder.splice(index, 1); } return this.cache.delete(key); } /** * Clear all cached data */ clear(): void { this.cache.clear(); this.accessOrder = []; } /** * Get current cache size */ get size(): number { return this.cache.size; } /** * Get all keys in access order (oldest first) */ get keys(): string[] { return [...this.accessOrder]; } } /** * Options for creating a message batcher */ export interface MessageBatcherOptions { /** Maximum messages to batch before flush */ batchSize: number; /** Maximum time to wait before flush (ms) */ maxWaitMs: number; } /** * Message batcher for efficient WebSocket message processing. * Groups incoming messages into batches for optimized rendering. * * @typeParam T - Type of message to batch * * @example * ```tsx * const batcher = createMessageBatcher<ChatMessage>( * (messages) => { * // Process batch of messages * chatStore.addMessages(messages); * }, * { batchSize: 10, maxWaitMs: 50 } * ); * * // Add messages as they arrive * websocket.on('message', (msg) => batcher.add(msg)); * * // Flush remaining on disconnect * websocket.on('close', () => batcher.flush()); * ``` */ export function createMessageBatcher<T>( callback: (messages: T[]) => void, options: MessageBatcherOptions = { batchSize: 10, maxWaitMs: 50 } ): { add: (message: T) => void; flush: () => void; clear: () => void; size: () => number; } { let batch: T[] = []; let timeoutId: ReturnType<typeof setTimeout> | null = null; const flush = (): void => { if (batch.length > 0) { callback([...batch]); batch = []; } if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; } }; return { add: (message: T): void => { batch.push(message); if (batch.length >= options.batchSize) { flush(); } else if (!timeoutId) { timeoutId = setTimeout(flush, options.maxWaitMs); } }, flush, clear: (): void => { batch = []; if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; } }, size: (): number => batch.length, }; } /** * Memoization helper for message content parsing. * Caches parsed content to avoid re-parsing on re-renders. * * @param messageId - Unique message identifier * @param content - Raw content to parse * @param parser - Parsing function * @param cache - Optional cache instance to use * @returns Parsed content */ export function useMemoizedContent<T>( messageId: string, content: string, parser: (content: string) => T, cache?: MessageCache<T> ): T { // Use provided cache or create a default one const cacheRef = useRef<MessageCache<T> | undefined>(undefined); if (!cacheRef.current && !cache) { cacheRef.current = new MessageCache<T>(200); } const activeCache = cache ?? cacheRef.current!; // Check cache first const cached = activeCache.get(messageId); if (cached !== undefined) { return cached; } // Parse and cache const parsed = parser(content); activeCache.set(messageId, parsed); return parsed; } /** * Creates a stable message key for React rendering. * Handles potential duplicate IDs by incorporating index. * * @param id - Message ID * @param index - Message index in list * @returns Stable key string */ export function createMessageKey(id: string, index: number): string { return `${id}-${index}`; } /** * Calculates the visible range of messages for a given viewport. * Useful for lazy loading or prefetching. * * @param scrollTop - Current scroll position * @param containerHeight - Height of visible container * @param messages - Array of messages with heights * @param overscan - Number of extra items to include on each side * @returns Object with start and end indices of visible range */ export function calculateVisibleRange( scrollTop: number, containerHeight: number, messages: VirtualizedMessageItem[], overscan: number = 3 ): { start: number; end: number } { let currentOffset = 0; let start = 0; let end = messages.length - 1; // Find start index for (let i = 0; i < messages.length; i++) { const msgHeight = messages[i].height; if (currentOffset + msgHeight > scrollTop) { start = Math.max(0, i - overscan); break; } currentOffset += msgHeight; } // Find end index const targetEnd = scrollTop + containerHeight; currentOffset = 0; for (let i = 0; i < messages.length; i++) { const msgHeight = messages[i].height; currentOffset += msgHeight; if (currentOffset >= targetEnd) { end = Math.min(messages.length - 1, i + overscan); break; } } return { start, end }; } /** * Debounced scroll handler factory. * Prevents excessive re-renders during fast scrolling. * * @param callback - Function to call with scroll position * @param delay - Debounce delay in ms * @returns Debounced scroll handler */ export function createDebouncedScrollHandler( callback: (scrollTop: number) => void, delay: number = 100 ): (scrollTop: number) => void { let timeoutId: ReturnType<typeof setTimeout> | null = null; let lastValue = 0; return (scrollTop: number): void => { lastValue = scrollTop; if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { callback(lastValue); timeoutId = null; }, delay); }; } export type { VirtualizedMessageItem as MessageItem, VirtualizedMessageListProps as MessageListProps, }; |