use-cache-chat-log.ts
Overview
The use-cache-chat-log.ts file defines a custom React hook, useCacheChatLog, designed to manage and cache chat event logs efficiently in a React application. It provides mechanisms to store, filter, and manipulate chat events based on message IDs and event types, enabling components to easily access and maintain stateful event data related to chat conversations.
This hook is particularly useful in chat or messaging applications where events such as message updates, message completions, and other related events need to be cached and filtered dynamically. It improves performance by caching event lists per message ID and exposing utility functions to query this cached data.
Detailed Documentation
Constants
ExcludeTypes: MessageEventType[]
An array of event types to be excluded in certain filtered views.
Currently excludes:
MessageEventType.MessageMessageEventType.MessageEnd
Used to filter out standard "message" events and message completion events when only other event types are needed.
Hook: useCacheChatLog()
A React hook that manages chat event logs, caching them by message ID and providing filtering capabilities.
Returns
An object containing the following properties and methods:
Name | Type | Description |
|---|---|---|
|
| The current global list of all chat events stored. |
| Filtered events for the current message ID excluding events in | |
| Function to get filtered events by any message ID, excluding | |
Setter function to replace the entire event list. | ||
| Clears all cached events and message caches. | |
| Appends new events to the current event list and caches them by message ID. | |
| [(eventType: string) => IEventList \ | undefined](/projects/311/74054) |
| [(messageId: string) => IEventList \ | undefined](/projects/311/74054) |
|
| Setter function to change the currently active message ID. |
| The current active message ID that filters most queries. |
Internal State Variables
eventList: IEventList
Stores the list of chat events currently being tracked globally.messageIdPool: Record<string, IEventList>
A dictionary mapping message IDs to their corresponding event lists, enabling quick lookup and caching.currentMessageId: string
The ID of the currently active message used for filtering event queries.
Functions and Methods
useEffect for syncing messageIdPool
Watches changes to
currentMessageIdandeventList.Updates the
messageIdPoolcache by assigning the currenteventListto the activecurrentMessageId.
filterEventListByMessageId(messageId: string): IEventList | undefined
Parameters:
messageId- The message ID to filter events by.Returns:
An array of events (IEventList) associated with the givenmessageId, or undefined if none exists.Description:
Filters the cached events to only those whosemessage_idmatches the argument.
filterEventListByEventType(eventType: string): IEventList | undefined
Parameters:
eventType- The event type string to filter by.Returns:
An array of events filtered by event type within the current message ID, or undefined.Description:
Retrieves all events for the current message ID that match the specified event type.
clearEventList(): void
Description:
Clears all cached events and resets both the global event list and the message ID pool.
addEventList(events: IEventList, message_id: string): void
Parameters:
events- An array of events to append.message_id- The message ID these events are associated with.
Description:
Adds a new array of events to the existing global event list and updates the cache for the specified message ID.
currentEventListWithoutMessage: INodeEvent[]
Description:
A memoized filtered array of events for the current message ID, excluding events listed inExcludeTypes.
currentEventListWithoutMessageById(messageId: string): INodeEvent[]
Parameters:
messageId- The message ID to filter by.Returns:
A filtered array of events for the specified message ID, excluding events inExcludeTypes.
Usage Example
import React from 'react';
import { useCacheChatLog } from './use-cache-chat-log';
function ChatComponent() {
const {
eventList,
addEventList,
clearEventList,
filterEventListByMessageId,
setCurrentMessageId,
currentMessageId,
currentEventListWithoutMessage,
} = useCacheChatLog();
React.useEffect(() => {
// Simulate receiving new events for message "msg123"
const newEvents = [
{ message_id: 'msg123', event: 'typing', content: 'User is typing...' },
{ message_id: 'msg123', event: 'message', content: 'Hello!' },
];
addEventList(newEvents, 'msg123');
setCurrentMessageId('msg123');
}, [addEventList, setCurrentMessageId]);
return (
<div>
<h2>Current Message ID: {currentMessageId}</h2>
<h3>Filtered Events (excluding message events):</h3>
<ul>
{currentEventListWithoutMessage.map((event, idx) => (
<li key={idx}>{event.event}: {event.content}</li>
))}
</ul>
</div>
);
}
Implementation Details
State Synchronization: The hook uses a React
useEffecthook to synchronize themessageIdPoolcache with the currenteventListwhenever thecurrentMessageIdoreventListchanges. This ensures cache consistency without manual intervention.Filtering Logic: Filtering is done by simple array
filteroperations checkingmessage_idandeventproperties. The exclusion of certain event types is implemented by checking that none of the excluded types match the event.Caching Strategy: The
messageIdPoolstores events grouped by message ID, avoiding repeated filtering over the entire event list when querying by message ID.Memoization:
useMemoanduseCallbackare used extensively to prevent unnecessary recalculations or re-renders when dependent state or props have not changed.
Interaction with Other Parts of the System
Imports:
Imports types
IEventList,INodeEvent, andMessageEventTypefrom'@/hooks/use-send-message', indicating that this hook depends on the message event data structures and constants defined elsewhere in the system.
Usage Context:
Intended to be used within React components that handle chat or messaging functionalities.
Other components or hooks can consume the cached event data for rendering chat logs, handling message states, or responding to specific event types.
Event Types:
The
MessageEventTypeenum or constants fromuse-send-messageare central to filtering and event identification.
Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[Start: useCacheChatLog Hook] --> B{State Variables}
B --> |eventList| C[Array of all chat events]
B --> |messageIdPool| D[Map: messageId -> event list]
B --> |currentMessageId| E[String: active message ID]
A --> F[addEventList(events, message_id)]
F --> C
F --> D
A --> G[clearEventList()]
G --> C
G --> D
A --> H[filterEventListByMessageId(messageId)]
H --> D
A --> I[filterEventListByEventType(eventType)]
I --> D
I --> E
A --> J[currentEventListWithoutMessage]
J --> D
J --> E
A --> K[currentEventListWithoutMessageById(messageId)]
K --> D
E --> L[useEffect sync messageIdPool with eventList]
style B fill:#f9f,stroke:#333,stroke-width:1px
style C fill:#bbf,stroke:#333,stroke-width:1px
style D fill:#bbf,stroke:#333,stroke-width:1px
style E fill:#bbf,stroke:#333,stroke-width:1px
style F fill:#afa,stroke:#333,stroke-width:1px
style G fill:#faa,stroke:#333,stroke-width:1px
style H fill:#ffa,stroke:#333,stroke-width:1px
style I fill:#ffa,stroke:#333,stroke-width:1px
style J fill:#aaf,stroke:#333,stroke-width:1px
style K fill:#aaf,stroke:#333,stroke-width:1px
Summary
The useCacheChatLog hook is a robust utility for managing chat event caching and filtering in React applications. By maintaining a cache keyed by message IDs and exposing flexible filtering methods, it supports efficient chat log management and dynamic event querying, critical for responsive chat UI components. Its thoughtful use of React state and hooks ensures optimal rendering behavior and easy integration into complex chat or messaging systems.