use-select-conversation-list.ts
Overview
This TypeScript file provides a set of React hooks designed to manage and interact with a conversation list within a chat application. It primarily focuses on fetching conversation and dialog data, managing URL parameters related to conversations, and maintaining an enhanced conversation list state that supports temporary conversations with predefined prologues.
The hooks abstract away complexities such as fetching data, syncing URL parameters, and handling UI state changes related to conversation selection and creation, enabling components to easily integrate conversation list functionalities.
Detailed Explanation of Exports
1. useFindPrologueFromDialogList
Purpose
Retrieves the "prologue" text content associated with the currently selected dialog from the dialog list fetched from the backend.
Functionality
Uses the current URL parameter
id(assumed to be the dialog ID).Fetches the dialog list via
useFetchDialogList.Memoizes and returns the
prologuefield from the matched dialog'sprompt_config.
Parameters
None
Returns
string | undefined — The prologue text if found, otherwise undefined.
Usage Example
const prologue = useFindPrologueFromDialogList();
console.log("Dialog prologue:", prologue);
2. useSetNewConversationRouteParams
Purpose
Provides a function to update the browser URL search parameters to reflect a newly created conversation's ID and its "new" status.
Functionality
Reads current URL search parameters.
Creates a new
URLSearchParamsinstance for manipulation.Returns a callback function
setNewConversationRouteParamsthat updates the URL parameters:ConversationId(fromChatSearchParamsenum) is set to the new conversation's ID.isNewis set to a string indicating whether the conversation is new.
Parameters
None
Returns
{ setNewConversationRouteParams: (conversationId: string, isNew: string) => void }— An object with the setter function.
Usage Example
const { setNewConversationRouteParams } = useSetNewConversationRouteParams();
setNewConversationRouteParams('abc123', 'true');
3. useSelectDerivedConversationList
Purpose
Manages a conversation list state that merges fetched conversations with optionally added temporary conversations (e.g., newly created ones). It also handles searching and loading states.
Functionality
Fetches conversation list and loading state using
useFetchConversationList.Retrieves the current dialog ID from URL parameters.
Retrieves the dialog prologue.
Uses
useSetNewConversationRouteParamsto update URL parameters on new conversation creation.Maintains a local
liststate representing the current conversation list, allowing insertion of temporary conversations at the front.Provides a method
addTemporaryConversationthat:Generates a new conversation ID.
Updates the URL parameters to reflect the new conversation.
Prepends a temporary conversation object with a name from translation and the dialog prologue as the first message.
Synchronizes the local list state with the fetched conversation list on load.
Parameters
None
Returns
{
list: IConversation[]; // The conversation list state (including temporary conversations)
addTemporaryConversation: () => void; // Function to add a new temporary conversation
loading: boolean; // Loading state of the conversation list fetch
handleInputChange: (event: React.ChangeEvent<HTMLInputElement>) => void; // Handler for search input changes
searchString: string; // Current search string for filtering conversations
}
Usage Example
const {
list,
addTemporaryConversation,
loading,
handleInputChange,
searchString,
} = useSelectDerivedConversationList();
return (
<>
<input value={searchString} onChange={handleInputChange} />
{loading ? <Spinner /> : list.map(c => <ConversationCard key={c.id} conversation={c} />)}
<button onClick={addTemporaryConversation}>New Conversation</button>
</>
);
Important Implementation Details and Algorithms
Memoization: Uses React's
useMemoto optimize expensive lookups, such as finding the prologue from dialogs and cloning URL search parameters.URL Parameter Sync: The
useSetNewConversationRouteParamshook ensures the URL always reflects the active conversation and whether it is new, enabling deep linking and reload consistency.Temporary Conversations: When a user creates a new conversation, it is immediately added to the UI list with a temporary entry containing a unique ID, a localized default name, linked dialog ID, and the dialog's prologue as the first assistant message. This temporary state allows for optimistic UI updates before backend confirmation.
Separation of Concerns: Fetching data (
useFetchConversationList,useFetchDialogList), translation (useTranslate), URL management (useParams,useSearchParams), and state management are modularized into custom hooks imported and composed here.
Interaction with Other System Parts
Data Fetching Hooks:
useFetchConversationListanduseFetchDialogListare responsible for fetching conversation and dialog data from the backend or database.
Constants and Types:
ChatSearchParamsandMessageTypeprovide constants for query parameter keys and message role types.IConversationinterface defines the shape of conversation objects.
Utilities:
getConversationIdgenerates unique conversation IDs.
Routing:
Uses
umi'suseParamsanduseSearchParamsfor accessing and updating URL parameters.
Localization:
useTranslateis used to obtain localized strings like "newConversation".
Together, these dependencies enable seamless integration of conversation selection and creation within the broader chat application with URL-based routing and data handling.
Mermaid Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[useSelectDerivedConversationList]
A --> B[useFetchConversationList]
A --> C[useParams (dialogId)]
A --> D[useFindPrologueFromDialogList]
D --> E[useFetchDialogList]
A --> F[useSetNewConversationRouteParams]
F --> G[useSearchParams]
subgraph "Temporary Conversation Creation"
A --> H[addTemporaryConversation]
H --> I[getConversationId]
H --> F
H --> D
end
style A fill:#f9f,stroke:#333,stroke-width:2px
style H fill:#bbf,stroke:#333,stroke-width:1.5px
style B fill:#afa,stroke:#333
style D fill:#ffa,stroke:#333
style F fill:#aaf,stroke:#333
Summary
This file is a utility module containing custom React hooks to facilitate conversation list selection, management, and routing within a chat app. It abstracts fetching dialogs and conversations, synchronizes URL parameters for conversation navigation, and supports adding temporary conversations with dialog-based prologues. Its design promotes modularity, performance optimization through memoization, and user experience improvements with immediate UI feedback on new conversations.
References
React Hooks: https://reactjs.org/docs/hooks-intro.html
Umi Routing: https://umijs.org/docs/routing
MermaidJS Class and Flowchart Diagrams: https://mermaid-js.github.io/mermaid/#/flowchart
TypeScript Interfaces and Types: https://www.typescriptlang.org/docs/handbook/interfaces.html