hooks.ts
Overview
hooks.ts provides a comprehensive collection of custom React hooks designed to manage chat-related state, routing parameters, user interactions, and API interactions within a chat application. These hooks abstract complex logic such as fetching, updating, and manipulating conversations and dialogs, handling message lifecycle events, modal visibility, and UI state management around chat dialogs and conversations.
The file integrates multiple external hooks and utilities, including React Query for async state management, URL search parameters for routing, and SSE for streaming message responses. It acts as a central place for chat UI logic and state orchestration, promoting modularity and reusability across the chat system.
Detailed Documentation
Key Concepts and Entities
Dialog (
IDialog): Represents a chat dialog template or configuration.Conversation (
IConversation): An individual chat instance tied to a dialog, containing messages.Message (
Message,IMessage): Represents individual chat messages with content, role, and metadata.ChatSearchParams: URL parameters used to control chat state (e.g., conversationId, isNew).
Modal State: UI state for showing/hiding modals such as dialog or conversation editors.
Exports and Their Functionality
1. useSetChatRouteParams
Purpose:
Manage chat-related URL search parameters, specifically the isNew flag indicating if a conversation is new.
API:
setConversationIsNew(value: string): void
Sets theisNewURL parameter.getConversationIsNew(): string | null
Retrieves the currentisNewURL parameter.
Usage Example:
const { setConversationIsNew, getConversationIsNew } = useSetChatRouteParams();
setConversationIsNew('true');
const isNew = getConversationIsNew();
2. useSetNewConversationRouteParams
Purpose:
Set multiple chat route parameters at once, specifically ConversationId and isNew.
API:
setNewConversationRouteParams(conversationId: string, isNew: string): void
Sets both conversation ID and new conversation flag in URL parameters.
3. useSelectCurrentDialog
Purpose:
Select the current dialog from mutation state keyed by 'fetchDialog'.
Returns:
The latest
IDialogobject or empty object if none.
4. useSelectPromptConfigParameters
Purpose:
Extracts and maps prompt configuration parameters from the current dialog for UI display or editing.
Returns:
Array of
VariableTableDataTypeobjects representing variables and their optionality.
Important Details:
If no dialog ID exists (new chat), returns a default parameter with key
knowledge.
5. useDeleteDialog
Purpose:
Provides a handler to delete dialogs with a confirmation modal.
API:
onRemoveDialog(dialogIds: string[]): void
Shows delete confirmation and removes dialogs upon confirmation.
6. useHandleItemHover
Purpose:
Manages hover state for UI items by tracking an activated ID.
API:
activated: string— currently hovered item ID.handleItemEnter(id: string): void— sets hover state.handleItemLeave(): void— clears hover state.
7. useEditDialog
Purpose:
Manages state and modal visibility for editing dialogs.
API:
dialogSettingLoading: boolean— loading state during update.initialDialog: IDialog— current dialog state.onDialogEditOk(dialog: IDialog): Promise<void>— submits dialog edits.dialogEditVisible: boolean— modal visibility.hideDialogEditModal(): void— hides modal and resets dialog state.showDialogEditModal(dialogId?: string): Promise<void>— shows modal and optionally loads dialog data.clearDialog(): void— resets dialog state.
8. useFindPrologueFromDialogList
Purpose:
Retrieves the prologue text from the currently selected dialog list.
Returns:
The
prologuestring from the dialog's prompt config.
9. useSelectDerivedConversationList
Purpose:
Manages a list of conversations derived from the fetched conversation list, allowing temporary conversation insertion (e.g., for new chats).
API:
list: IConversation[]— derived conversation list.addTemporaryConversation(): void— adds a temporary new conversation with prologue message.loading: boolean— loading status.
10. useSetConversation
Purpose:
Updates or creates a conversation via API, binding it to the current dialog.
API:
setConversation(message: string, isNew?: boolean, conversationId?: string): Promise<any>
Updates conversation with a message and returns API response.
11. useSelectNextMessages
Purpose:
Manages message state for the current conversation, including adding, removing, and initializing messages (including prologue for new chats).
Returns:
UI refs (
scrollRef,messageContainerRef)derivedMessages: IMessage[]Loading flag
Message manipulation methods:
addNewestAnsweraddNewestQuestionremoveLatestMessageremoveMessageByIdremoveMessagesAfterCurrentMessage
12. useHandleMessageInputChange
Purpose:
Manages controlled input state for the chat message textarea.
Returns:
handleInputChange: ChangeEventHandler<HTMLTextAreaElement>— updates internal state.value: string— current input value.setValue(value: string): void— sets input value.
13. useSendNextMessage
Purpose:
Manages sending messages with Server-Sent Events (SSE) support, handling new or existing conversations, streaming answers, and message lifecycle.
Parameters:
controller: AbortController— used to abort ongoing SSE requests.
Returns:
Methods and states for message input and sending:
handlePressEnter(documentIds: string[]): void— sends message on enter key.handleInputChangevaluesetValueregenerateMessagesendLoading: booleanloading: booleanscrollRefmessageContainerRefderivedMessagesremoveMessageByIdstopOutputMessage
Important Implementation Details:
Handles new conversations by creating them before sending messages.
Uses SSE (
useSendMessageWithSse) for streaming message completions.Maintains UI state with derived messages.
Supports aborting message streaming.
14. useGetFileIcon
Purpose:
Returns a function that maps a filename's extension to an SVG icon path.
API:
getFileIcon(filename: string): string
15. useDeleteConversation
Purpose:
Provides a handler for deleting conversations with confirmation modal.
API:
onRemoveConversation(conversationIds: string[]): void
16. useRenameConversation
Purpose:
Manages state and modal visibility for renaming conversations.
API:
conversationRenameLoading: booleaninitialConversationName: stringonConversationRenameOk(name: string): Promise<void>conversationRenameVisible: booleanhideConversationRenameModal(): voidshowConversationRenameModal(conversationId: string): Promise<void>
17. useGetSendButtonDisabled
Purpose:
Returns a boolean indicating if the send button should be disabled based on current route parameters.
18. useSendButtonDisabled
Purpose:
Returns a boolean indicating if the send button should be disabled based on current input value (empty or whitespace).
19. useCreateConversationBeforeUploadDocument
Purpose:
Creates a new conversation if needed before uploading a document, based on route parameters.
API:
createConversationBeforeUploadDocument(message: string): Promise<any>dialogId: string
Important Implementation Details and Algorithms
Route Parameter Management: Uses
useSearchParamsto read and update URL query parameters, allowing the chat UI to respond to URL changes and maintain state across page reloads or navigation.Message Streaming: Uses SSE via
useSendMessageWithSseto stream conversation completions in real-time, allowing incremental message display and user interaction during response generation.Optimistic UI Updates: Implements temporary conversations and prologues for new chats to provide immediate user feedback before server confirmation.
State Isolation: Separates dialog editing, renaming, and deletion logic into dedicated hooks managing modals and API calls, promoting single responsibility and composability.
Unique ID Generation: Uses
uuidto create stable keys for React rendering, ensuring consistent state and minimizing re-renders.
Interaction with Other System Parts
API Layer: Uses
api.completeConversationto send message data to backend and get streaming responses.Chat Hooks: Relies on imported hooks such as
useFetchManualConversationanduseUpdateNextConversationfor fetching/updating chat data.Common Hooks: Uses modal and translation hooks (
useSetModalState,useTranslate) for UI state and internationalization.Utilities: Utilizes utility functions like
getFileExtension,getConversationId, and lodash methods for data manipulation.React Query: Leverages
useMutationStatefor mutation caching and selection.Routing: Integrates tightly with URL parameters to synchronize chat state with the browser history.
Visual Diagram
classDiagram
class useSetChatRouteParams {
+setConversationIsNew(value: string): void
+getConversationIsNew(): string | null
}
class useSetNewConversationRouteParams {
+setNewConversationRouteParams(conversationId: string, isNew: string): void
}
class useSelectCurrentDialog {
+(): IDialog
}
class useSelectPromptConfigParameters {
+(): VariableTableDataType[]
}
class useDeleteDialog {
+onRemoveDialog(dialogIds: string[]): void
}
class useHandleItemHover {
+activated: string
+handleItemEnter(id: string): void
+handleItemLeave(): void
}
class useEditDialog {
+dialogSettingLoading: boolean
+initialDialog: IDialog
+onDialogEditOk(dialog: IDialog): Promise<void>
+dialogEditVisible: boolean
+hideDialogEditModal(): void
+showDialogEditModal(dialogId?: string): Promise<void>
+clearDialog(): void
}
class useSelectDerivedConversationList {
+list: IConversation[]
+addTemporaryConversation(): void
+loading: boolean
}
class useSetConversation {
+setConversation(message: string, isNew?: boolean, conversationId?: string): Promise<any>
}
class useSelectNextMessages {
+scrollRef
+messageContainerRef
+derivedMessages: IMessage[]
+loading: boolean
+addNewestAnswer()
+addNewestQuestion()
+removeLatestMessage()
+removeMessageById()
+removeMessagesAfterCurrentMessage()
}
class useHandleMessageInputChange {
+handleInputChange()
+value: string
+setValue(value: string): void
}
class useSendNextMessage {
+handlePressEnter(documentIds: string[]): void
+handleInputChange()
+value: string
+setValue(value: string): void
+regenerateMessage()
+sendLoading: boolean
+loading: boolean
+scrollRef
+messageContainerRef
+derivedMessages: IMessage[]
+removeMessageById()
+stopOutputMessage()
}
class useGetFileIcon {
+getFileIcon(filename: string): string
}
class useDeleteConversation {
+onRemoveConversation(conversationIds: string[]): void
}
class useRenameConversation {
+conversationRenameLoading: boolean
+initialConversationName: string
+onConversationRenameOk(name: string): Promise<void>
+conversationRenameVisible: boolean
+hideConversationRenameModal(): void
+showConversationRenameModal(conversationId: string): Promise<void>
}
class useGetSendButtonDisabled {
+(): boolean
}
class useSendButtonDisabled {
+value: string -> boolean
}
class useCreateConversationBeforeUploadDocument {
+createConversationBeforeUploadDocument(message: string): Promise<any>
+dialogId: string
}
useSendNextMessage --> useSetConversation : uses
useSendNextMessage --> useSelectNextMessages : uses
useSendNextMessage --> useHandleMessageInputChange : uses
useSendNextMessage --> useSetChatRouteParams : uses
useEditDialog --> useFetchManualDialog : fetchDialog
useEditDialog --> useSetNextDialog : submitDialog
useDeleteDialog --> useRemoveNextDialog : removeDialog
useDeleteConversation --> useRemoveNextConversation : removeConversation
useRenameConversation --> useFetchManualConversation : fetchConversation
useRenameConversation --> useUpdateNextConversation : updateConversation
useSelectDerivedConversationList --> useFetchNextConversationList : fetch conversation list
useSelectDerivedConversationList --> useSetNewConversationRouteParams : setNewConversationRouteParams
useSelectDerivedConversationList --> useFindPrologueFromDialogList : prologue
useFindPrologueFromDialogList --> useFetchNextDialogList : fetch dialog list
Summary
This file is a crucial layer in the chat application that encapsulates the complex state management, UI interaction, and API communication logic related to chat dialogs and conversations. It decouples data fetching, mutation, and UI state concerns into reusable hooks, enabling clean, maintainable, and scalable chat features. The integration of URL parameters, SSE streaming, and modal controls provides a responsive and intuitive user experience.