chat-hooks.ts
Overview
The chat-hooks.ts file provides a comprehensive set of React hooks designed to manage chat-related data and actions within a chat application. These hooks abstract the logic for fetching, creating, updating, and deleting dialogs, conversations, tokens, and related data using React Query for efficient server state management. They also handle URL search parameters to maintain UI state, user interactions, and side effects like notifications.
This file acts as a bridge between the UI components and the backend chat service, encapsulating API calls and state logic, enabling cleaner and more maintainable component code.
Detailed Documentation
URL Search Parameter Hooks
These hooks manage and read URL search parameters related to chat dialogs and conversations, enabling navigation and state persistence.
useClickDialogCard()
Purpose: Provides a handler to update the URL search parameter for the selected dialog.
Returns:
{ handleClickDialog: (dialogId: string) => void }Usage:
const { handleClickDialog } = useClickDialogCard(); handleClickDialog('dialog123');Details:
Updates theDialogIdparameter in the URL search string when a dialog card is clicked to reflect the current selection.
useClickConversationCard()
Purpose: Provides a handler to update URL search parameters for the selected conversation.
Returns:
{ handleClickConversation: (conversationId: string, isNew: string) => void }Usage:
const { handleClickConversation } = useClickConversationCard(); handleClickConversation('conv123', 'true');Details:
Updates theConversationIdandisNewparameters in the URL search string on conversation card click.
useGetChatSearchParams()
Purpose: Reads and returns current chat-related URL search parameters.
Returns:
{ dialogId: string; conversationId: string; isNew: string; }Usage:
const { dialogId, conversationId, isNew } = useGetChatSearchParams();Details:
ExtractsDialogId,ConversationId, andisNewfrom the URL.
Dialog Management Hooks
These hooks handle dialog lists, fetching single dialogs, creating, updating, and removing dialogs.
useFetchNextDialogList(pureFetch: boolean = false)
Purpose: Fetches the list of dialogs and manages selection logic.
Parameters:
pureFetch(optional): If true, prevents auto-selection of dialogs.
Returns:
{ data: IDialog[]; loading: boolean; refetch: () => void; }Usage:
const { data: dialogs, loading, refetch } = useFetchNextDialogList();Details:
Fetches dialogs fromchatService.listDialog(). If dialogs exist andpureFetchis false, it updates the URL to select the first dialog. If none, redirects to/chat.
useFetchChatAppList()
Purpose: Fetches the list of chat applications (dialogs) without additional selection logic.
Returns: Same as
useFetchNextDialogList.Usage: Same as above.
useSetNextDialog()
Purpose: Creates or updates a dialog.
Returns:
{ data: any; loading: boolean; setDialog: (params: IDialog) => Promise<number>; }Usage:
const { setDialog } = useSetNextDialog(); await setDialog({ id: 'dialog123', name: 'My Dialog' });Details:
CallschatService.setDialog()to persist changes, invalidates related queries, and shows success messages.
useFetchNextDialog()
Purpose: Fetches details of a single dialog by
dialogIdfrom URL.Returns:
{ data: IDialog; loading: boolean; refetch: () => void; }Usage:
const { data: dialog, loading } = useFetchNextDialog();Details: Disabled if no
dialogIdpresent.
useFetchManualDialog()
Purpose: Manually fetch a dialog by ID.
Returns:
{ data: any; loading: boolean; fetchDialog: (dialogId: string) => Promise<any>; }Usage:
const { fetchDialog } = useFetchManualDialog(); const dialogData = await fetchDialog('dialog123');
useRemoveNextDialog()
Purpose: Removes dialogs by IDs.
Returns:
{ data: any; loading: boolean; removeDialog: (dialogIds: string[]) => Promise<number>; }Usage:
const { removeDialog } = useRemoveNextDialog(); await removeDialog(['dialog123']);Details: Invalidates dialog list queries and shows success message.
Conversation Management Hooks
These hooks fetch, update, and delete conversations and messages.
useFetchNextConversationList()
Purpose: Fetches conversations linked to the current dialog.
Returns:
{ data: IConversation[]; loading: boolean; refetch: () => void; }Usage:
const { data: conversations } = useFetchNextConversationList();Details:
Automatically sets the first conversation in URL or clears if none.
useFetchNextConversation()
Purpose: Fetches details of a conversation by
conversationIdor shared ID.Returns:
{ data: IClientConversation; loading: boolean; refetch: () => void; }Usage:
const { data: conversation } = useFetchNextConversation();Details:
Builds messages list with UUIDs and handles new conversation flags.
useFetchNextConversationSSE()
Purpose: Fetches conversation data via Server-Sent Events (SSE) for real-time updates.
Returns: Same as
useFetchNextConversation.Details: Similar to
useFetchNextConversationbut uses SSE endpoint.
useFetchManualConversation()
Purpose: Manually fetch a conversation by ID.
Returns:
{ data: any; loading: boolean; fetchConversation: (conversationId: string) => Promise<any>; }
useUpdateNextConversation()
Purpose: Updates a conversation.
Returns:
{ data: any; loading: boolean; updateConversation: (params: Record<string, any>) => Promise<any>; }Usage:
const { updateConversation } = useUpdateNextConversation(); await updateConversation({ conversation_id: 'conv123', title: 'New Title' });Details: Invalidates conversation list and shows success message.
useRemoveNextConversation()
Purpose: Removes conversations by IDs under the current dialog.
Returns: Same structure as
useRemoveNextDialog.
useDeleteMessage()
Purpose: Deletes a message from the current conversation.
Returns:
{ data: any; loading: boolean; deleteMessage: (messageId: string) => Promise<number>; }Details: Shows success notification on completion.
useFeedback()
Purpose: Sends feedback (e.g., thumbs up/down) for a conversation.
Parameters:
IFeedbackRequestBodyobject containing feedback details.Returns:
{ data: any; loading: boolean; feedback: (params: IFeedbackRequestBody) => Promise<number>; }Details: Shows success message on operation.
Token Management Hooks
These hooks manage API tokens related to chats.
useCreateNextToken()
Purpose: Creates a new token.
Returns:
{ data: any; loading: boolean; createToken: (params: Record<string, any>) => Promise<any>; }Details: Invalidates token list cache after creation.
useFetchTokenList(params: Record<string, any>)
Purpose: Fetches tokens list based on query parameters.
Returns:
{ data: IToken[]; loading: boolean; refetch: () => void; }
useRemoveNextToken()
Purpose: Removes tokens.
Parameters:
{ tenantId: string; dialogId?: string; tokens: string[] }Returns: Similar structure to other remove hooks.
Details: Invalidates token list cache upon success.
Statistics Hook
useFetchNextStats()
Purpose: Fetches chat usage statistics for a date range.
Returns:
{ data: IStats; loading: boolean; pickerValue: RangeValue; setPickerValue: React.Dispatch<React.SetStateAction<RangeValue>>; }Details:
Defaults to last 7 days. Uses dayjs for date formatting.
Shared Chat Hooks
useCreateNextSharedConversation()
Purpose: Creates a shared (external) conversation, optionally tied to a user.
Returns:
{ data: any; loading: boolean; createSharedConversation: (userId?: string) => Promise<any>; }
useFetchNextSharedConversation(conversationId?: string | null)
Purpose: Fetches a shared conversation by ID (deprecated).
Returns:
{ data: any; loading: boolean; }Details:
Builds message list with UUIDs.
Search Page Hooks
useFetchMindMap()
Purpose: Fetches mind map data related to a question.
Returns:
{ data: any; loading: boolean; fetchMindMap: (params: IAskRequestBody) => Promise<any>; }Details:
Handles errors and displays messages on failure.
useFetchRelatedQuestions()
Purpose: Fetches related questions for a given query string.
Returns:
{ data: string[]; loading: boolean; fetchRelatedQuestions: (question: string) => Promise<string[]>; }
Important Implementation Details
React Query Integration:
The hooks leverageuseQueryanduseMutationfrom React Query (@tanstack/react-query) for data fetching, caching, and mutations.URL State Synchronization:
Hooks likeuseClickDialogCardanduseClickConversationCardmanipulate URL search parameters usinguseSearchParamsfromumito reflect the current dialog/conversation. This allows deep linking and browser navigation support.Message List UUIDs:
Conversations' message lists are wrapped viabuildMessageListWithUuidto ensure unique identifiers, likely for React rendering and tracking.Optimistic UI Updates and Cache Invalidation:
After mutations such as creating or deleting dialogs/conversations/tokens, queries are invalidated to refresh UI state.Internationalization:
Success and error messages usei18n.t()for localization.Error Handling:
Some hooks catch errors and use Ant Design'smessage.errorto notify users.Date Handling:
useFetchNextStatsusesdayjsfor date manipulation and formatting.Deprecated Functions:
useFetchNextSharedConversationis marked deprecated but retained for backward compatibility.
Interaction with Other Parts of the System
API Service:
All data requests are routed throughchatService(imported from@/services/chat-service), which likely abstracts HTTP calls to backend APIs.Interfaces and Types:
Uses TypeScript interfaces (IConversation,IDialog,IStats,IToken, etc.) imported from@/interfacesto type responses and parameters.Utilities:
Uses utility functions from@/utils/chatfor tasks such as verifying conversation IDs and building message lists.Routing and URL Handling:
Usesumi'shistoryanduseSearchParamsfor navigation and URL parameter handling.Localization:
Usesi18nmodule for message translations.UI Feedback:
Relies on Ant Design'smessagecomponent for user notifications.
Visual Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
subgraph URL Search Param Hooks
A1[useClickDialogCard]
A2[useClickConversationCard]
A3[useGetChatSearchParams]
end
subgraph Dialog Hooks
B1[useFetchNextDialogList]
B2[useFetchChatAppList]
B3[useSetNextDialog]
B4[useFetchNextDialog]
B5[useFetchManualDialog]
B6[useRemoveNextDialog]
end
subgraph Conversation Hooks
C1[useFetchNextConversationList]
C2[useFetchNextConversation]
C3[useFetchNextConversationSSE]
C4[useFetchManualConversation]
C5[useUpdateNextConversation]
C6[useRemoveNextConversation]
C7[useDeleteMessage]
C8[useFeedback]
end
subgraph Token Hooks
D1[useCreateNextToken]
D2[useFetchTokenList]
D3[useRemoveNextToken]
end
subgraph Stats & Shared Chat
E1[useFetchNextStats]
E2[useCreateNextSharedConversation]
E3[useFetchNextSharedConversation (deprecated)]
end
subgraph Search Page
F1[useFetchMindMap]
F2[useFetchRelatedQuestions]
end
%% Relationships
A1 --> B1
A2 --> C1
A3 --> B4
A3 --> C2
B1 --> B4
B3 --> B1
B6 --> B1
C1 --> C2
C4 --> C2
C5 --> C1
C6 --> C1
C7 --> C2
C8 --> C2
D1 --> D2
D3 --> D2
E2 --> C2
E3 --> C2
Summary
chat-hooks.ts is a central collection of React hooks designed to manage the chat application's dialogs, conversations, tokens, statistics, and shared chat sessions. It leverages React Query for async data management and Umi for URL state synchronization. The hooks provide an organized, reusable, and declarative approach to handle complex chat-related data flows and user interactions, helping developers build a responsive and feature-rich chat UI efficiently.
If you need further details on any specific hook or its integration, please let me know!